├── .eslintignore ├── react-native.config.js ├── .gitignore ├── .prettierrc.js ├── babel.config.js ├── src ├── index.ts └── commands │ ├── index.ts │ ├── common │ ├── ObjcPatcher.ts │ ├── __tests__ │ │ └── objcPatcher.test.ts │ └── buildIOS.ts │ ├── getAppSizeIOS.ts │ ├── getAppSizeAndroid.ts │ └── measureIOS.ts ├── jest.config.js ├── definitions ├── react-native-community__cli-platform-android │ └── index.d.ts ├── react-native-community__cli-tools │ └── index.d.ts └── react-native-community__cli-platform-ios │ └── index.d.ts ├── tsconfig.json ├── .eslintrc.js ├── LICENSE ├── .github └── workflows │ └── build.yml ├── package.json └── README.md /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | build/ 3 | coverage/ 4 | -------------------------------------------------------------------------------- /react-native.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | module.exports = require('./build').pluginConfig; 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | .vscode 4 | build/ 5 | coverage/ 6 | *.tsbuildinfo 7 | yarn-error.log 8 | .eslintcache 9 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | singleQuote: true, 3 | trailingComma: 'all', 4 | bracketSpacing: false, 5 | jsxBracketSameLine: true, 6 | }; 7 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ['@babel/preset-env', {targets: {node: '8'}}], 4 | '@babel/preset-typescript', 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import commands from './commands'; 6 | 7 | const pluginConfig = { 8 | commands, 9 | }; 10 | 11 | export = { 12 | pluginConfig, 13 | }; 14 | -------------------------------------------------------------------------------- /src/commands/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import getAppSizeIOS from './getAppSizeIOS'; 6 | import getAppSizeAndroid from './getAppSizeAndroid'; 7 | import measureIOS from './measureIOS'; 8 | 9 | export default [getAppSizeIOS, getAppSizeAndroid, measureIOS]; 10 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | const common = {testEnvironment: 'node'}; 2 | 3 | module.exports = { 4 | projects: [ 5 | { 6 | ...common, 7 | displayName: 'unit', 8 | // setupFiles: ['/jest/setupUnitTests.js'], 9 | testMatch: ['/**/__tests__/*{.,-}test.[jt]s'], 10 | }, 11 | ], 12 | collectCoverageFrom: [ 13 | 'src/**/*.ts', 14 | '!**/__mocks__/**', 15 | '!**/__tests__/**', 16 | '!**/build/**', 17 | ], 18 | }; 19 | -------------------------------------------------------------------------------- /definitions/react-native-community__cli-platform-android/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | declare module '@react-native-community/cli-platform-android/build/link/warnAboutManuallyLinkedLibs' { 10 | import {Config} from '@react-native-community/cli-types'; 11 | export default function warnAboutManuallyLinkedLibs( 12 | config: Config, 13 | platform?: string, 14 | linkConfig?: ReturnType, 15 | ): void; 16 | } 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2017", 4 | "module": "commonjs", 5 | "lib": ["es2017"], 6 | "declaration": true, 7 | "declarationMap": true, 8 | "composite": true, 9 | // "emitDeclarationOnly": true, 10 | 11 | "strict": true, 12 | 13 | /* Additional Checks */ 14 | "noUnusedLocals": true, 15 | "noUnusedParameters": true, 16 | "noImplicitReturns": true, 17 | "noFallthroughCasesInSwitch": true, 18 | 19 | /* Module Resolution Options */ 20 | "moduleResolution": "node", 21 | "esModuleInterop": true, 22 | "resolveJsonModule": true, 23 | 24 | "rootDir": "src", 25 | "outDir": "build", 26 | "typeRoots": ["./node_modules/@types", "definitions"] 27 | }, 28 | "exclude": ["**/__tests__/**/*", "**/build/**/*"] 29 | } 30 | -------------------------------------------------------------------------------- /definitions/react-native-community__cli-tools/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | declare module '@react-native-community/cli-tools' { 10 | export const logger: { 11 | success: (...messages: string[]) => void; 12 | info: (...messages: string[]) => void; 13 | warn: (...messages: string[]) => void; 14 | error: (...messages: string[]) => void; 15 | debug: (...messages: string[]) => void; 16 | log: (...messages: string[]) => void; 17 | setVerbose: (level: boolean) => void; 18 | isVerbose: () => boolean; 19 | disable: () => void; 20 | enable: () => void; 21 | }; 22 | 23 | export class CLIError extends Error { 24 | constructor(msg: string, originalError?: Error | string); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const prettierConfig = require('./.prettierrc'); 2 | 3 | module.exports = { 4 | parser: '@typescript-eslint/parser', 5 | plugins: ['@typescript-eslint'], 6 | extends: [ 7 | '@react-native-community', 8 | 'eslint:recommended', 9 | 'plugin:@typescript-eslint/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | ], 12 | env: { 13 | node: true, 14 | }, 15 | settings: { 16 | react: { 17 | version: 'latest', 18 | }, 19 | }, 20 | overrides: [ 21 | { 22 | files: [ 23 | '**/__mocks__/**', 24 | '**/__fixtures__/**', 25 | '**/__e2e__/**', 26 | 'jest/**', 27 | ], 28 | env: { 29 | jest: true, 30 | }, 31 | }, 32 | { 33 | files: ['*.ts', '**/*.ts'], 34 | rules: { 35 | 'prettier/prettier': [2, {prettierConfig, parser: 'typescript'}], 36 | }, 37 | }, 38 | { 39 | files: ['*.js'], 40 | rules: { 41 | '@typescript-eslint/no-var-requires': 'off', 42 | }, 43 | }, 44 | ], 45 | }; 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kudo Chien 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | path-ignore: 6 | - '*.md' 7 | - '**/*.md' 8 | pull_request: 9 | branches: 10 | - master 11 | path-ignore: 12 | - '*.md' 13 | - '**/*.md' 14 | 15 | jobs: 16 | build-and-test: 17 | name: Build and Test 18 | runs-on: ubuntu-latest 19 | strategy: 20 | matrix: 21 | node: [10, 12] 22 | 23 | steps: 24 | - uses: actions/checkout@v2 25 | 26 | - uses: actions/setup-node@v1 27 | with: 28 | node-version: ${{ matrix.node }} 29 | 30 | - name: Get yarn cache directory path 31 | id: yarn-cache-dir-path 32 | run: echo "::set-output name=dir::$(yarn cache dir)" 33 | 34 | - uses: actions/cache@v1 35 | id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) 36 | with: 37 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 38 | key: ${{ runner.os }}-node${{ matrix.node }}-yarn-${{ hashFiles('**/yarn.lock') }} 39 | restore-keys: | 40 | ${{ runner.os }}-node${{ matrix.node}}-yarn- 41 | 42 | - name: Install dependencies 43 | run: yarn --frozen-lockfile 44 | 45 | - name: Run unit tests 46 | run: yarn test:ci:unit 47 | 48 | - name: Lint 49 | run: yarn lint 50 | 51 | - name: Build 52 | run: yarn build 53 | -------------------------------------------------------------------------------- /src/commands/common/ObjcPatcher.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import fs from 'fs'; 6 | 7 | export default class ObjcPatcher { 8 | _content: string; 9 | _patchSig: string; 10 | 11 | constructor(fromFile: string, patchSignature: string) { 12 | this._content = fs.readFileSync(fromFile, {encoding: 'utf8'}); 13 | this._patchSig = `/* Patched by ObjcPatcher: ${patchSignature} */\n`; 14 | } 15 | 16 | isPatched(): boolean { 17 | return this._content.indexOf(this._patchSig) >= 0; 18 | } 19 | 20 | addImport(file: string, searchPattern = '\n#import'): ObjcPatcher { 21 | const lastImportBegin = this._content.lastIndexOf(searchPattern); 22 | const lastImportEnd = this._content.indexOf('\n', lastImportBegin + 1); 23 | const headPart = this._content.substring(0, lastImportEnd); 24 | const tailPart = this._content.substring(lastImportEnd); 25 | this._content = headPart + `\n#import ${file}` + tailPart; 26 | return this; 27 | } 28 | 29 | addFunction(code: string): ObjcPatcher { 30 | const lastImplEnd = this._content.lastIndexOf('\n@end'); 31 | const headPart = this._content.substring(0, lastImplEnd); 32 | const tailPart = this._content.substring(lastImplEnd); 33 | this._content = headPart + `\n${code}` + tailPart; 34 | return this; 35 | } 36 | 37 | replace(searchValue: string | RegExp, replaceValue: string): ObjcPatcher { 38 | this._content = this._content.replace(searchValue, replaceValue); 39 | return this; 40 | } 41 | 42 | write(toFile: string): void { 43 | this._addPatchSigIfNeeded(); 44 | fs.writeFileSync(toFile, this._content); 45 | } 46 | 47 | _addPatchSigIfNeeded(): ObjcPatcher { 48 | if (this.isPatched()) { 49 | return this; 50 | } 51 | this._content = this._patchSig + this._content; 52 | return this; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/commands/getAppSizeIOS.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | * @format 8 | */ 9 | 10 | import ChildProcess from 'child_process'; 11 | import {build} from './common/buildIOS'; 12 | import {Config} from '@react-native-community/cli-types'; 13 | import {logger} from '@react-native-community/cli-tools'; 14 | 15 | type Options = { 16 | sdk: string; 17 | configuration: string; 18 | scheme?: string; 19 | projectPath: string; 20 | verbose: boolean; 21 | }; 22 | 23 | async function getAppSize( 24 | _argv: Array, 25 | ctx: Config, 26 | args: Options, 27 | ): Promise { 28 | const appPath = await build(ctx, args); 29 | 30 | const size = Number( 31 | ChildProcess.execFileSync('du', ['-s', appPath], { 32 | encoding: 'utf8', 33 | }).split('\t')[0], 34 | ); 35 | 36 | logger.info(`Generated app size:\n${JSON.stringify({[appPath]: size})}`); 37 | } 38 | 39 | export default { 40 | name: 'get-appsize-ios', 41 | description: 'get the generated IPA size from run-ios output', 42 | func: getAppSize, 43 | options: [ 44 | { 45 | name: '--sdk [string]', 46 | description: 47 | 'Setup SDK to build the code, e.g. "iphoneos" or "iphonesimulator"', 48 | default: 'iphonesimulator', 49 | }, 50 | { 51 | name: '--configuration [string]', 52 | description: 'Explicitly set the scheme configuration to use', 53 | default: 'Debug', 54 | }, 55 | { 56 | name: '--scheme [string]', 57 | description: 'Explicitly set Xcode scheme to use', 58 | }, 59 | { 60 | name: '--project-path [string]', 61 | description: 62 | 'Path relative to project root where the Xcode project ' + 63 | '(.xcodeproj) lives.', 64 | default: 'ios', 65 | }, 66 | { 67 | name: '--verbose', 68 | description: 'Show build log', 69 | }, 70 | ], 71 | }; 72 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-cli-plugin-benchmark", 3 | "version": "0.3.0", 4 | "description": "React Native CLI Plugin for Benchmark Regression", 5 | "scripts": { 6 | "build": "yarn tsc", 7 | "lint": "eslint --ext .js,.ts . --cache --report-unused-disable-directives", 8 | "test": "jest", 9 | "test:ci:unit": "jest --ci --coverage", 10 | "publish": "rimraf ./build ./tsconfig.tsbuildinfo && yarn build && yarn publish" 11 | }, 12 | "main": "build/index.js", 13 | "files": [ 14 | "build", 15 | "react-native.config.js" 16 | ], 17 | "repository": "https://github.com/Kudo/react-native-cli-plugin-benchmark", 18 | "license": "MIT", 19 | "jest": { 20 | "testEnvironment": "node" 21 | }, 22 | "devDependencies": { 23 | "@babel/core": "^7.10.5", 24 | "@babel/preset-env": "^7.10.4", 25 | "@babel/preset-typescript": "^7.10.4", 26 | "@react-native-community/cli-platform-android": "^4.10.1", 27 | "@react-native-community/cli-platform-ios": "^4.10.1", 28 | "@react-native-community/cli-tools": "^4.10.1", 29 | "@react-native-community/cli-types": "^4.10.1", 30 | "@react-native-community/eslint-config": "^2.0.0", 31 | "@types/glob": "^7.1.3", 32 | "@types/graceful-fs": "^4.1.3", 33 | "@types/jest": "^26.0.5", 34 | "@types/lodash": "^4.14.157", 35 | "@types/node": "^14.0.23", 36 | "@types/node-fetch": "^2.5.7", 37 | "@typescript-eslint/eslint-plugin": "^3.6.1", 38 | "@typescript-eslint/parser": "^3.6.1", 39 | "eslint": "^7.5.0", 40 | "eslint-import-resolver-alias": "^1.1.2", 41 | "eslint-import-resolver-typescript": "^2.0.0", 42 | "eslint-plugin-import": "^2.22.0", 43 | "eslint-plugin-prettier": "^3.1.4", 44 | "jest": "^26.1.0", 45 | "prettier": "^2.0.5", 46 | "rimraf": "^3.0.2", 47 | "typescript": "^3.9.7" 48 | }, 49 | "peerDependencies": { 50 | "@react-native-community/cli": ">= 3.0.0" 51 | }, 52 | "dependencies": { 53 | "execa": "^4.0.3", 54 | "glob": "^7.1.6", 55 | "graceful-fs": "^4.2.4", 56 | "lodash": "^4.17.19" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /definitions/react-native-community__cli-platform-ios/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | declare module '@react-native-community/cli-platform-ios/build/commands/runIOS' { 10 | import {Config} from '@react-native-community/cli-types'; 11 | 12 | type FlagsT = { 13 | simulator?: string; 14 | configuration: string; 15 | scheme?: string; 16 | projectPath: string; 17 | device?: string | true; 18 | udid?: string; 19 | packager: boolean; 20 | verbose: boolean; 21 | port: number; 22 | terminal: string | undefined; 23 | }; 24 | 25 | function runIOS( 26 | _: Array, 27 | ctx: Config, 28 | args: FlagsT, 29 | ): void | Promise; 30 | 31 | export const _default: { 32 | name: string; 33 | description: string; 34 | func: typeof runIOS; 35 | examples: { 36 | desc: string; 37 | cmd: string; 38 | }[]; 39 | options: ( 40 | | { 41 | name: string; 42 | description: string; 43 | default: string; 44 | parse?: undefined; 45 | } 46 | | { 47 | name: string; 48 | description: string; 49 | default?: undefined; 50 | parse?: undefined; 51 | } 52 | | { 53 | name: string; 54 | default: string | number; 55 | parse: (val: string) => number; 56 | description?: undefined; 57 | } 58 | | { 59 | name: string; 60 | description: string; 61 | default: () => string | undefined; 62 | parse?: undefined; 63 | } 64 | )[]; 65 | }; 66 | 67 | export default _default; 68 | } 69 | 70 | declare module '@react-native-community/cli-platform-ios/build/commands/runIOS/findXcodeProject' { 71 | export type ProjectInfo = { 72 | name: string; 73 | isWorkspace: boolean; 74 | }; 75 | function findXcodeProject(files: Array): ProjectInfo | null; 76 | export default findXcodeProject; 77 | } 78 | 79 | declare module '@react-native-community/cli-platform-ios/build/link/warnAboutPodInstall' { 80 | import {Config} from '@react-native-community/cli-types'; 81 | export default function warnAboutPodInstall(config: Config): void; 82 | } 83 | 84 | declare module '@react-native-community/cli-platform-ios/build/link/warnAboutManuallyLinkedLibs' { 85 | import {Config} from '@react-native-community/cli-types'; 86 | export default function warnAboutManuallyLinkedLibs( 87 | config: Config, 88 | platform?: string, 89 | linkConfig?: ReturnType, 90 | ): void; 91 | } 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/react-native-cli-plugin-benchmark.svg)](https://badge.fury.io/js/react-native-cli-plugin-benchmark) 2 | ![GitHub Actions CI](https://github.com/Kudo/react-native-cli-plugin-benchmark/workflows/Build/badge.svg) 3 | 4 | # react-native-cli-plugin-benchmark 5 | React Native CLI Plugin for Benchmark Regression 6 | 7 | ## Installation 8 | ```sh 9 | $ yarn add react-native-cli-plugin-benchmark 10 | ``` 11 | 12 | ## Supported Commands 13 | 14 | ### react-native get-appsize-ios 15 | Get the generated IPA size from run-ios output 16 | 17 | ```sh 18 | $ react-native get-appsize-ios --configuration Release --sdk iphoneos 19 | info Found Xcode workspace "RNApp.xcworkspace" 20 | info Building (using "xcodebuild -workspace RNApp.xcworkspace -configuration Release -scheme RNApp -sdk iphoneos CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO") 21 | info Generated app size: 22 | {"/Users/kudo/Library/Developer/Xcode/DerivedData/RNApp-auhfmjezpdwqwhasqmpbigmosgfe/Build/Products/Release-iphoneos/RNApp.app":37632} 23 | ``` 24 | 25 | ### react-native get-appsize-android 26 | Get the generated APK size from run-android output 27 | 28 | ```sh 29 | $ react-native get-appsize-android --variant release 30 | info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. 31 | info Building the app... 32 | info Generated app size: 33 | {"/Users/kudo/RNApp/android/app/build/outputs/apk/release/app-release.apk":19603464} 34 | ``` 35 | 36 | ### react-native measure-ios 37 | Measure from run-ios output 38 | Note that the command in fact to patch AppDelegate to log some information after 5 seconds from launch. 39 | The information are from RCTPerformanceLogger and task memory. 40 | 41 | ```sh 42 | $ react-native measure-ios --configuration Release --no-packager 43 | info Found Xcode workspace "RNApp.xcworkspace" 44 | info Launching iPhone X (iOS 12.4) 45 | info Building (using "xcodebuild -workspace RNApp.xcworkspace -configuration Release -scheme RNApp -destination id=6FF18363-C213-4E59-9A83-3117EE7AE6FE") 46 | ▸ Compiling diy-fp.cc 47 | ▸ Compiling bignum.cc 48 | ▸ Compiling cached-powers.cc 49 | ▸ Compiling double-conversion.cc 50 | ... 51 | info Launching "org.reactjs.native.example.RNApp" 52 | success Successfully launched the app on the simulator 53 | info Measurement result: 54 | { 55 | "duration.RCTPLScriptDownload": "2", 56 | "duration.RCTPLScriptExecution": "181", 57 | "duration.RCTPLRAMBundleLoad": "0", 58 | "duration.RCTPLRAMStartupCodeSize": "0", 59 | "duration.RCTPLRAMStartupNativeRequires": "0", 60 | "duration.RCTPLRAMStartupNativeRequiresCount": "0", 61 | "duration.RCTPLRAMNativeRequires": "0", 62 | "duration.RCTPLRAMNativeRequiresCount": "0", 63 | "duration.RCTPLNativeModuleInit": "2", 64 | "duration.RCTPLNativeModuleMainThread": "56", 65 | "duration.RCTPLNativeModulePrepareConfig": "0", 66 | "duration.RCTPLNativeModuleMainThreadUsesCount": "4", 67 | "duration.RCTPLNativeModuleSetup": "0", 68 | "duration.RCTPLTurboModuleSetup": "0", 69 | "duration.RCTPLJSCWrapperOpenLibrary": "0", 70 | "duration.RCTPLBridgeStartup": "284", 71 | "duration.RCTPLTTI": "474", 72 | "duration.RCTPLBundleSize": "652466", 73 | "memory": "55541760" 74 | } 75 | ``` 76 | -------------------------------------------------------------------------------- /src/commands/getAppSizeAndroid.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | * @format 8 | */ 9 | import glob from 'glob'; 10 | import path from 'path'; 11 | import execa from 'execa'; 12 | import chalk from 'chalk'; 13 | import fs from 'fs'; 14 | import {Config} from '@react-native-community/cli-types'; 15 | import {logger, CLIError} from '@react-native-community/cli-tools'; 16 | import warnAboutManuallyLinkedLibs from '@react-native-community/cli-platform-android/build/link/warnAboutManuallyLinkedLibs'; 17 | 18 | // Verifies this is an Android project 19 | function checkAndroid(root: string): boolean { 20 | return fs.existsSync(path.join(root, 'android/gradlew')); 21 | } 22 | 23 | // Validates that the package name is correct 24 | function validatePackageName(packageName: string): boolean { 25 | return /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/.test(packageName); 26 | } 27 | 28 | function performChecks(config: Config, args: Options): void { 29 | if (!checkAndroid(args.root)) { 30 | throw new CLIError( 31 | 'Android project not found. Are you sure this is a React Native project?', 32 | ); 33 | } 34 | 35 | // warn after we have done basic system checks 36 | warnAboutManuallyLinkedLibs(config); 37 | } 38 | 39 | function buildApk(gradlew: string, clean = true, verbose = false): void { 40 | try { 41 | // using '-x lint' in order to ignore linting errors while building the apk 42 | const gradleArgs = ['build', '-x', 'lint']; 43 | if (clean) { 44 | gradleArgs.unshift('clean'); 45 | } 46 | logger.info('Building the app...'); 47 | logger.debug(`Running command "${gradlew} ${gradleArgs.join(' ')}"`); 48 | execa.sync(gradlew, gradleArgs, {stdio: verbose ? 'inherit' : 'ignore'}); 49 | } catch (error) { 50 | throw new CLIError('Failed to build the app.', error); 51 | } 52 | } 53 | 54 | async function build( 55 | config: Config, 56 | args: Options, 57 | verbose = false, 58 | ): Promise { 59 | performChecks(config, args); 60 | 61 | if (args.jetifier) { 62 | logger.info( 63 | `Running ${chalk.bold( 64 | 'jetifier', 65 | )} to migrate libraries to AndroidX. ${chalk.dim( 66 | 'You can disable it using "--no-jetifier" flag.', 67 | )}`, 68 | ); 69 | 70 | try { 71 | await execa(require.resolve('jetifier/bin/jetify'), { 72 | stdio: verbose ? 'inherit' : 'ignore', 73 | }); 74 | } catch (error) { 75 | throw new CLIError('Failed to run jetifier.', error); 76 | } 77 | } 78 | 79 | process.chdir(path.join(args.root, 'android')); 80 | const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew'; 81 | 82 | // "app" is usually the default value for Android apps with only 1 app 83 | const {appFolder} = args; 84 | const androidManifest = fs.readFileSync( 85 | `${appFolder}/src/main/AndroidManifest.xml`, 86 | 'utf8', 87 | ); 88 | 89 | const packageNameMatchArray = androidManifest.match(/package="(.+?)"/); 90 | if (!packageNameMatchArray || packageNameMatchArray.length === 0) { 91 | throw new CLIError( 92 | `Failed to build the app: No package name found. Found errors in ${chalk.underline.dim( 93 | `${appFolder}/src/main/AndroidManifest.xml`, 94 | )}`, 95 | ); 96 | } 97 | 98 | const packageName = packageNameMatchArray[1]; 99 | 100 | if (!validatePackageName(packageName)) { 101 | logger.warn( 102 | `Invalid application's package name "${chalk.bgRed( 103 | packageName, 104 | )}" in 'AndroidManifest.xml'. Read guidelines for setting the package name here: ${chalk.underline.dim( 105 | 'https://developer.android.com/studio/build/application-id', 106 | )}`, 107 | ); // we can also directly add the package naming rules here 108 | } 109 | 110 | buildApk(cmd); 111 | } 112 | 113 | export interface Options { 114 | tasks?: Array; 115 | root: string; 116 | variant: string; 117 | appFolder: string; 118 | jetifier: boolean; 119 | } 120 | 121 | /** 122 | * Get generated APK size from as `run-android` 123 | */ 124 | async function getApkSize( 125 | _argv: Array, 126 | config: Config, 127 | args: Options, 128 | ): Promise<{[apk: string]: number}> { 129 | await build(config, args); 130 | 131 | const {appFolder} = args; 132 | const variant = args.variant.toLowerCase(); 133 | const buildDirectory = `${appFolder}/build/outputs/apk/${variant}`; 134 | const apks = glob.sync(path.join(buildDirectory, '**/*.apk'), {nodir: true}); 135 | 136 | type ApkWithSizeType = {[apk: string]: number}; 137 | const apksWithSize = apks.reduce((map: ApkWithSizeType, apk) => { 138 | const {size} = fs.statSync(apk); 139 | const apkPath = path.resolve(apk); 140 | map[apkPath] = size; 141 | return map; 142 | }, {}); 143 | logger.info(`Generated app size:\n${JSON.stringify(apksWithSize)}`); 144 | return apksWithSize; 145 | } 146 | 147 | export default { 148 | name: 'get-appsize-android', 149 | description: 'get the generated APK size from run-android output', 150 | func: getApkSize, 151 | options: [ 152 | { 153 | name: '--root [string]', 154 | description: 155 | 'Override the root directory for the android build (which contains the android directory)', 156 | default: '', 157 | }, 158 | { 159 | name: '--variant [string]', 160 | description: "Specify your app's build variant", 161 | default: 'debug', 162 | }, 163 | { 164 | name: '--appFolder [string]', 165 | description: 166 | 'Specify a different application folder name for the android source. If not, we assume is "app"', 167 | default: 'app', 168 | }, 169 | { 170 | name: '--tasks [list]', 171 | description: 'Run custom Gradle tasks. By default it\'s "installDebug"', 172 | parse: (val: string): Array => val.split(','), 173 | }, 174 | { 175 | name: '--no-jetifier', 176 | description: 177 | 'Do not run "jetifier" – the AndroidX transition tool. By default it runs before Gradle to ease working with libraries that don\'t support AndroidX yet. See more at: https://www.npmjs.com/package/jetifier.', 178 | default: false, 179 | }, 180 | { 181 | name: '--verbose', 182 | description: 'Show build log', 183 | default: false, 184 | }, 185 | ], 186 | }; 187 | -------------------------------------------------------------------------------- /src/commands/common/__tests__/objcPatcher.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import ObjcPatcher from '../ObjcPatcher'; 6 | import fs from 'fs'; 7 | 8 | jest.mock('fs'); 9 | 10 | describe('ObjcPatcher', () => { 11 | test('addImport() will append imports', () => { 12 | const beforePatch = `\ 13 | #import 14 | #import 15 | 16 | @implementation AppDelegate 17 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 18 | { 19 | return NO; 20 | } 21 | `; 22 | 23 | const afterPatch = `\ 24 | /* Patched by ObjcPatcher: foo */ 25 | #import 26 | #import 27 | #import 28 | 29 | @implementation AppDelegate 30 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 31 | { 32 | return NO; 33 | } 34 | `; 35 | fs.readFileSync = jest.fn().mockReturnValueOnce(beforePatch); 36 | 37 | fs.writeFileSync = jest.fn(); 38 | 39 | const patcher = new ObjcPatcher('/foo', 'foo'); 40 | patcher.addImport('').write('/bar'); 41 | expect(fs.writeFileSync.mock.calls[0][0]).toBe('/bar'); 42 | expect(fs.writeFileSync.mock.calls[0][1]).toBe(afterPatch); 43 | }); 44 | 45 | test('addImport() will append imports for specified searchPattern', () => { 46 | const beforePatch = `\ 47 | #import 48 | #import 49 | 50 | #if DEBUG 51 | #import 52 | #endif 53 | 54 | @implementation AppDelegate 55 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 56 | { 57 | return NO; 58 | } 59 | `; 60 | 61 | const afterPatch = `\ 62 | /* Patched by ObjcPatcher: foo */ 63 | #import 64 | #import 65 | #import 66 | 67 | #if DEBUG 68 | #import 69 | #endif 70 | 71 | @implementation AppDelegate 72 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 73 | { 74 | return NO; 75 | } 76 | `; 77 | fs.readFileSync = jest.fn().mockReturnValueOnce(beforePatch); 78 | 79 | fs.writeFileSync = jest.fn(); 80 | 81 | const patcher = new ObjcPatcher('/foo', 'foo'); 82 | patcher 83 | .addImport('', '\n#import ') 84 | .write('/bar'); 85 | expect(fs.writeFileSync.mock.calls[0][0]).toBe('/bar'); 86 | expect(fs.writeFileSync.mock.calls[0][1]).toBe(afterPatch); 87 | }); 88 | 89 | test('isPatched() returns false if the file has not been patched', () => { 90 | const beforePatch = `\ 91 | #import 92 | #import 93 | 94 | @implementation AppDelegate 95 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 96 | { 97 | return NO; 98 | } 99 | `; 100 | 101 | fs.readFileSync = jest.fn().mockReturnValueOnce(beforePatch); 102 | const patcher = new ObjcPatcher('/foo', 'foo'); 103 | expect(patcher.isPatched()).toBe(false); 104 | }); 105 | 106 | test('isPatched() returns true if the file has been patched', () => { 107 | const afterPatch = `\ 108 | /* Patched by ObjcPatcher: foo */ 109 | #import 110 | #import 111 | 112 | @implementation AppDelegate 113 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 114 | { 115 | return NO; 116 | } 117 | `; 118 | 119 | fs.readFileSync = jest.fn().mockReturnValueOnce(afterPatch); 120 | const patcher = new ObjcPatcher('/foo', 'foo'); 121 | expect(patcher.isPatched()).toBe(true); 122 | }); 123 | 124 | test('addFunction() will add code block before last @end', () => { 125 | const beforePatch = `\ 126 | #import 127 | #import 128 | 129 | @implementation AppDelegate 130 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 131 | { 132 | self.window.rootViewController = rootViewController; 133 | return NO; 134 | } 135 | @end 136 | `; 137 | 138 | const afterPatch = `\ 139 | /* Patched by ObjcPatcher: foo */ 140 | #import 141 | #import 142 | 143 | @implementation AppDelegate 144 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 145 | { 146 | self.window.rootViewController = rootViewController; 147 | return NO; 148 | } 149 | 150 | - (void)foo 151 | { 152 | } 153 | @end 154 | `; 155 | 156 | fs.readFileSync = jest.fn().mockReturnValueOnce(beforePatch); 157 | 158 | fs.writeFileSync = jest.fn(); 159 | 160 | const patcher = new ObjcPatcher('/foo', 'foo'); 161 | const addCode = ` 162 | - (void)foo 163 | { 164 | }`; 165 | patcher.addFunction(addCode).write('/bar'); 166 | expect(fs.writeFileSync.mock.calls[0][1]).toBe(afterPatch); 167 | }); 168 | 169 | test('replace() is simply passthrough String.replace', () => { 170 | const beforePatch = `\ 171 | #import 172 | #import 173 | 174 | @implementation AppDelegate 175 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 176 | { 177 | self.window.rootViewController = rootViewController; 178 | return NO; 179 | } 180 | `; 181 | 182 | const afterPatch = `\ 183 | /* Patched by ObjcPatcher: foo */ 184 | #import 185 | #import 186 | 187 | @implementation AppDelegate 188 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 189 | { 190 | self.window.rootViewController = rootViewController; 191 | dispatch_async(dispatch_get_main_queue(), ^{ 192 | NSLog(@"AsyncTask"); 193 | }); 194 | return NO; 195 | } 196 | `; 197 | 198 | fs.readFileSync = jest.fn().mockReturnValueOnce(beforePatch); 199 | 200 | fs.writeFileSync = jest.fn(); 201 | 202 | const patcher = new ObjcPatcher('/foo', 'foo'); 203 | const patchCode = `\ 204 | dispatch_async(dispatch_get_main_queue(), ^{ 205 | NSLog(@"AsyncTask"); 206 | });`; 207 | patcher 208 | .replace( 209 | /(^\s*self.window.rootViewController = rootViewController;\s*$)/m, 210 | `$1\n${patchCode}`, 211 | ) 212 | .write('/bar'); 213 | expect(fs.writeFileSync.mock.calls[0][1]).toBe(afterPatch); 214 | }); 215 | }); 216 | -------------------------------------------------------------------------------- /src/commands/common/buildIOS.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | * @format 8 | */ 9 | 10 | import ChildProcess from 'child_process'; 11 | import fs from 'fs'; 12 | import path from 'path'; 13 | import chalk from 'chalk'; 14 | import {Config} from '@react-native-community/cli-types'; 15 | import findXcodeProject, { 16 | ProjectInfo, 17 | } from '@react-native-community/cli-platform-ios/build/commands/runIOS/findXcodeProject'; 18 | import warnAboutManuallyLinkedLibs from '@react-native-community/cli-platform-ios/build/link/warnAboutManuallyLinkedLibs'; 19 | import warnAboutPodInstall from '@react-native-community/cli-platform-ios/build/link/warnAboutPodInstall'; 20 | import {logger, CLIError} from '@react-native-community/cli-tools'; 21 | 22 | type Options = { 23 | sdk: string; 24 | configuration: string; 25 | scheme?: string; 26 | projectPath: string; 27 | verbose: boolean; 28 | }; 29 | 30 | function getProductName(buildOutput: string): string | null { 31 | const productNameMatch = /export FULL_PRODUCT_NAME="?(.+).app"?$/m.exec( 32 | buildOutput, 33 | ); 34 | return productNameMatch ? productNameMatch[1] : null; 35 | } 36 | 37 | function getTargetBuildDir(buildSettings: string): string | null { 38 | const targetBuildMatch = /TARGET_BUILD_DIR = (.+)$/m.exec(buildSettings); 39 | return targetBuildMatch && targetBuildMatch[1] 40 | ? targetBuildMatch[1].trim() 41 | : null; 42 | } 43 | 44 | export function getBuildPath( 45 | xcodeProject: ProjectInfo, 46 | configuration: string, 47 | appName: string, 48 | sdk: string, 49 | scheme: string, 50 | ): string { 51 | const buildSettings = ChildProcess.execFileSync( 52 | 'xcodebuild', 53 | [ 54 | xcodeProject.isWorkspace ? '-workspace' : '-project', 55 | xcodeProject.name, 56 | '-scheme', 57 | scheme, 58 | '-sdk', 59 | sdk, 60 | '-configuration', 61 | configuration, 62 | '-showBuildSettings', 63 | ], 64 | {encoding: 'utf8'}, 65 | ); 66 | const targetBuildDir = getTargetBuildDir(buildSettings); 67 | if (!targetBuildDir) { 68 | throw new CLIError('Failed to get the target build directory.'); 69 | } 70 | 71 | return `${targetBuildDir}/${appName}.app`; 72 | } 73 | 74 | function xcprettyAvailable(): boolean { 75 | try { 76 | ChildProcess.execSync('xcpretty --version', { 77 | stdio: [0, 'pipe', 'ignore'], 78 | }); 79 | } catch (error) { 80 | return false; 81 | } 82 | return true; 83 | } 84 | 85 | function getProcessOptions(): Record { 86 | return { 87 | env: { 88 | ...process.env, 89 | RCT_NO_LAUNCH_PACKAGER: 'true', 90 | }, 91 | }; 92 | } 93 | 94 | function buildProject( 95 | xcodeProject: ProjectInfo, 96 | scheme: string, 97 | args: Options, 98 | ): Promise { 99 | return new Promise((resolve, reject) => { 100 | const extraArgs = []; 101 | 102 | if (args.sdk.startsWith('iphoneos')) { 103 | extraArgs.push( 104 | 'CODE_SIGN_IDENTITY=""', 105 | 'CODE_SIGNING_REQUIRED=NO', 106 | 'CODE_SIGNING_ALLOWED=NO', 107 | ); 108 | } 109 | 110 | const xcodebuildArgs = [ 111 | xcodeProject.isWorkspace ? '-workspace' : '-project', 112 | xcodeProject.name, 113 | '-configuration', 114 | args.configuration, 115 | '-scheme', 116 | scheme, 117 | '-sdk', 118 | args.sdk, 119 | ...extraArgs, 120 | ]; 121 | logger.info( 122 | `Building ${chalk.dim( 123 | `(using "xcodebuild ${xcodebuildArgs.join(' ')}")`, 124 | )}`, 125 | ); 126 | let xcpretty: ReturnType | false; 127 | if (args.verbose) { 128 | xcpretty = 129 | xcprettyAvailable() && 130 | ChildProcess.spawn('xcpretty', [], { 131 | stdio: ['pipe', process.stdout, process.stderr], 132 | }); 133 | } 134 | const buildProcess = ChildProcess.spawn( 135 | 'xcodebuild', 136 | xcodebuildArgs, 137 | getProcessOptions(), 138 | ); 139 | let buildOutput = ''; 140 | let errorOutput = ''; 141 | buildProcess.stdout.on('data', (data: Buffer) => { 142 | const stringData = data.toString(); 143 | buildOutput += stringData; 144 | if (xcpretty && xcpretty.stdin) { 145 | xcpretty.stdin.write(data); 146 | } else { 147 | if (logger.isVerbose()) { 148 | logger.debug(stringData); 149 | } else if (args.verbose) { 150 | process.stdout.write('.'); 151 | } 152 | } 153 | }); 154 | buildProcess.stderr.on('data', (data: Buffer) => { 155 | errorOutput += data; 156 | }); 157 | buildProcess.on('close', (code: number) => { 158 | if (xcpretty && xcpretty.stdin) { 159 | xcpretty.stdin.end(); 160 | } else if (args.verbose) { 161 | process.stdout.write('\n'); 162 | } 163 | if (code !== 0) { 164 | reject( 165 | new CLIError( 166 | ` 167 | Failed to build iOS project. 168 | 169 | We ran "xcodebuild" command but it exited with error code ${code}. To debug build 170 | logs further, consider building your app with Xcode.app, by opening 171 | ${xcodeProject.name}. 172 | `, 173 | buildOutput + '\n' + errorOutput, 174 | ), 175 | ); 176 | return; 177 | } 178 | resolve(getProductName(buildOutput) || scheme); 179 | }); 180 | }); 181 | } 182 | 183 | export async function build(ctx: Config, args: Options): Promise { 184 | if (!fs.existsSync(args.projectPath)) { 185 | throw new CLIError( 186 | 'iOS project folder not found. Are you sure this is a React Native project?', 187 | ); 188 | } 189 | 190 | warnAboutManuallyLinkedLibs(ctx); 191 | warnAboutPodInstall(ctx); 192 | 193 | process.chdir(args.projectPath); 194 | 195 | const xcodeProject = findXcodeProject(fs.readdirSync('.')); 196 | if (!xcodeProject) { 197 | throw new CLIError( 198 | `Could not find Xcode project files in "${args.projectPath}" folder`, 199 | ); 200 | } 201 | 202 | const inferredSchemeName = path.basename( 203 | xcodeProject.name, 204 | path.extname(xcodeProject.name), 205 | ); 206 | const scheme = args.scheme || inferredSchemeName; 207 | 208 | logger.info( 209 | `Found Xcode ${ 210 | xcodeProject.isWorkspace ? 'workspace' : 'project' 211 | } "${chalk.bold(xcodeProject.name)}"`, 212 | ); 213 | 214 | const appName = await buildProject(xcodeProject, scheme, args); 215 | 216 | const appPath = getBuildPath( 217 | xcodeProject, 218 | args.configuration, 219 | appName, 220 | args.sdk, 221 | scheme, 222 | ); 223 | 224 | return appPath; 225 | } 226 | -------------------------------------------------------------------------------- /src/commands/measureIOS.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | * @format 8 | */ 9 | 10 | import fs from 'fs'; 11 | import {spawn} from 'child_process'; 12 | import glob from 'glob'; 13 | import {Config, IOSProjectConfig} from '@react-native-community/cli-types'; 14 | import {CLIError} from '@react-native-community/cli-tools'; 15 | import ObjcPatcher from './common/ObjcPatcher'; 16 | import runIOS from '@react-native-community/cli-platform-ios/build/commands/runIOS'; 17 | import {logger} from '@react-native-community/cli-tools'; 18 | 19 | function patchProject(projectConfig: IOSProjectConfig, patchTag: string): void { 20 | const appDelegates = glob.sync(`${projectConfig.sourceDir}/**/AppDelegate.m`); 21 | 22 | const addFunctionGetRssMemory = `\ 23 | // Refer from React/CoreModules/RCTPerfMonitor.mm 24 | static vm_size_t RCTGetResidentMemorySize(void) 25 | { 26 | vm_size_t memoryUsageInByte = 0; 27 | task_vm_info_data_t vmInfo; 28 | mach_msg_type_number_t count = TASK_VM_INFO_COUNT; 29 | kern_return_t kernelReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vmInfo, &count); 30 | if(kernelReturn == KERN_SUCCESS) { 31 | memoryUsageInByte = (vm_size_t) vmInfo.phys_footprint; 32 | } 33 | return memoryUsageInByte; 34 | } 35 | `; 36 | 37 | const searchPatternWithinDidFinishLaunchingWithOptions = new RegExp( 38 | /(^\s*self.window.rootViewController = rootViewController;\s*$)/m, 39 | ); 40 | const addCodeMeasureAfterFiveSeconds = ` 41 | dispatch_after( 42 | dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), 43 | dispatch_get_main_queue(), 44 | ^{ 45 | // Begin 46 | NSLog(@"{{tag}}.LOG_BEGIN="); 47 | 48 | // PerformanceLogger 49 | RCTPerformanceLogger* perfLogger = bridge.performanceLogger; 50 | NSLog(@"{{tag}}.duration.RCTPLScriptDownload=%lld", [perfLogger durationForTag:RCTPLScriptDownload]); 51 | NSLog(@"{{tag}}.duration.RCTPLScriptExecution=%lld", [perfLogger durationForTag:RCTPLScriptExecution]); 52 | NSLog(@"{{tag}}.duration.RCTPLRAMBundleLoad=%lld", [perfLogger durationForTag:RCTPLRAMBundleLoad]); 53 | NSLog(@"{{tag}}.duration.RCTPLRAMStartupCodeSize=%lld", [perfLogger durationForTag:RCTPLRAMStartupCodeSize]); 54 | NSLog(@"{{tag}}.duration.RCTPLRAMStartupNativeRequires=%lld", [perfLogger durationForTag:RCTPLRAMStartupNativeRequires]); 55 | NSLog(@"{{tag}}.duration.RCTPLRAMStartupNativeRequiresCount=%lld", [perfLogger durationForTag:RCTPLRAMStartupNativeRequiresCount]); 56 | NSLog(@"{{tag}}.duration.RCTPLRAMNativeRequires=%lld", [perfLogger durationForTag:RCTPLRAMNativeRequires]); 57 | NSLog(@"{{tag}}.duration.RCTPLRAMNativeRequiresCount=%lld", [perfLogger durationForTag:RCTPLRAMNativeRequiresCount]); 58 | NSLog(@"{{tag}}.duration.RCTPLNativeModuleInit=%lld", [perfLogger durationForTag:RCTPLNativeModuleInit]); 59 | NSLog(@"{{tag}}.duration.RCTPLNativeModuleMainThread=%lld", [perfLogger durationForTag:RCTPLNativeModuleMainThread]); 60 | NSLog(@"{{tag}}.duration.RCTPLNativeModulePrepareConfig=%lld", [perfLogger durationForTag:RCTPLNativeModulePrepareConfig]); 61 | NSLog(@"{{tag}}.duration.RCTPLNativeModuleMainThreadUsesCount=%lld", [perfLogger durationForTag:RCTPLNativeModuleMainThreadUsesCount]); 62 | NSLog(@"{{tag}}.duration.RCTPLNativeModuleSetup=%lld", [perfLogger durationForTag:RCTPLNativeModuleSetup]); 63 | NSLog(@"{{tag}}.duration.RCTPLTurboModuleSetup=%lld", [perfLogger durationForTag:RCTPLTurboModuleSetup]); 64 | NSLog(@"{{tag}}.duration.RCTPLJSCWrapperOpenLibrary=%lld", [perfLogger durationForTag:RCTPLJSCWrapperOpenLibrary]); 65 | NSLog(@"{{tag}}.duration.RCTPLBridgeStartup=%lld", [perfLogger durationForTag:RCTPLBridgeStartup]); 66 | NSLog(@"{{tag}}.duration.RCTPLTTI=%lld", [perfLogger durationForTag:RCTPLTTI]); 67 | NSLog(@"{{tag}}.duration.RCTPLBundleSize=%lld", [perfLogger durationForTag:RCTPLBundleSize]); 68 | 69 | // Memory 70 | NSLog(@"{{tag}}.memory=%lu", (unsigned long) RCTGetResidentMemorySize()); 71 | 72 | // End 73 | NSLog(@"{{tag}}.LOG_END="); 74 | }); 75 | `.replace(/\{\{tag\}\}/g, patchTag); 76 | for (const appDelegate of appDelegates) { 77 | const patcher = new ObjcPatcher(appDelegate, patchTag); 78 | if (patcher.isPatched()) { 79 | continue; 80 | } 81 | patcher 82 | .addImport('', '\n#import ') 83 | .addFunction(addFunctionGetRssMemory) 84 | .addImport( 85 | '', 86 | '\n#import ', 87 | ) 88 | .replace( 89 | searchPatternWithinDidFinishLaunchingWithOptions, 90 | `$1\n${addCodeMeasureAfterFiveSeconds}`, 91 | ) 92 | .write(appDelegate + 'm'); 93 | } 94 | 95 | const content = fs 96 | .readFileSync(projectConfig.pbxprojPath) 97 | .toString() 98 | .replace( 99 | /(AppDelegate.m[^m].*\slastKnownFileType = )sourcecode\.c\.objc;/g, 100 | '$1sourcecode.c.objcpp;', 101 | ) 102 | .replace(/(AppDelegate.m)([^m])/g, '$1m$2'); 103 | fs.writeFileSync(projectConfig.pbxprojPath, content); 104 | } 105 | 106 | async function waitSimulatorLog( 107 | patchTag: string, 108 | ): Promise<{[key: string]: string}> { 109 | return new Promise((resolve) => { 110 | const result: {[key: string]: string} = {}; 111 | const child = spawn('xcrun', [ 112 | 'simctl', 113 | 'spawn', 114 | 'booted', 115 | 'log', 116 | 'stream', 117 | '--predicate', 118 | `eventMessage contains "${patchTag}."`, 119 | ]); 120 | 121 | child.stdout.on('data', (data: Buffer) => { 122 | const lines = data.toString().split(/\r?\n/); 123 | const pattern = new RegExp(`\\s(${patchTag})\\.(.+?)=(.*)`); 124 | for (const line of lines) { 125 | const matches = line.match(pattern); 126 | if (matches) { 127 | const key = matches[2]; 128 | const value = matches[3]; 129 | if (key === 'LOG_BEGIN') { 130 | // nop 131 | } else if (key === 'LOG_END') { 132 | child.kill(); 133 | resolve(result); 134 | } else { 135 | result[key] = value; 136 | } 137 | } 138 | } 139 | }); 140 | }); 141 | } 142 | 143 | async function measure( 144 | _argv: Array, 145 | ctx: Config, 146 | args: Parameters[2], 147 | ): Promise { 148 | const projectConfig = ctx.project.ios; 149 | if (projectConfig == null) { 150 | throw new CLIError('iOS platform project config is null'); 151 | } 152 | 153 | const patchTag = 'measure-ios'; 154 | patchProject(projectConfig, patchTag); 155 | 156 | await runIOS.func([], ctx, args); 157 | const result = await waitSimulatorLog(patchTag); 158 | logger.info(`Measurement result:\n${JSON.stringify(result, null, 4)}`); 159 | } 160 | 161 | /** 162 | * @format 163 | */ 164 | 165 | export default { 166 | name: 'measure-ios', 167 | description: 'measure from run-ios output', 168 | func: measure, 169 | options: runIOS.options, 170 | }; 171 | --------------------------------------------------------------------------------