From aba4ec0c0984caf3bec75a803080bd95722b35db Mon Sep 17 00:00:00 2001 From: Eli White Date: Fri, 11 May 2018 12:43:49 -0700 Subject: [PATCH] Prettier RN local-cli Reviewed By: yungsters Differential Revision: D7962462 fbshipit-source-id: 0afe2092af8703895de91a6d1400315c3173aa6d --- local-cli/__mocks__/beeper.js | 7 +- local-cli/bundle/__mocks__/sign.js | 3 + .../filterPlatformAssetScales-test.js | 19 +- .../__tests__/getAssetDestPathAndroid-test.js | 20 +- .../__tests__/getAssetDestPathIOS-test.js | 2 + local-cli/bundle/assetPathUtils.js | 31 +- local-cli/bundle/buildBundle.js | 7 +- local-cli/bundle/bundle.js | 3 + local-cli/bundle/bundleCommandLineArgs.js | 76 +- local-cli/bundle/getAssetDestPathAndroid.js | 8 +- local-cli/bundle/getAssetDestPathIOS.js | 1 + local-cli/bundle/saveAssets.js | 42 +- local-cli/bundle/types.flow.js | 2 + local-cli/bundle/unbundle.js | 6 +- local-cli/cli.js | 3 + local-cli/cliEntry.js | 61 +- local-cli/commands.js | 16 +- local-cli/core/__fixtures__/android.js | 22 +- local-cli/core/__fixtures__/commands.js | 23 +- local-cli/core/__fixtures__/dependencies.js | 2 + local-cli/core/__fixtures__/ios.js | 14 +- local-cli/core/__fixtures__/projects.js | 8 +- .../__tests__/ios/findPodfilePath.spec.js | 1 + .../__tests__/ios/findPodspecName.spec.js | 13 +- .../core/android/findAndroidAppFolder.js | 3 + local-cli/core/android/findManifest.js | 3 + .../core/android/findPackageClassName.js | 5 +- local-cli/core/android/index.js | 34 +- local-cli/core/android/readManifest.js | 3 + local-cli/core/findAssets.js | 14 +- local-cli/core/findPlugins.js | 22 +- local-cli/core/index.js | 51 +- local-cli/core/ios/findPodfilePath.js | 2 + local-cli/core/ios/findPodspecName.js | 13 +- local-cli/core/ios/findProject.js | 3 + local-cli/core/ios/index.js | 5 +- local-cli/core/makeCommand.js | 9 +- local-cli/core/wrapCommands.js | 5 +- local-cli/dependencies/dependencies.js | 69 +- local-cli/eject/eject.js | 41 +- .../copyProjectTemplateAndReplace.js | 83 +- local-cli/generator/printRunInstructions.js | 15 +- local-cli/generator/promptSync.js | 61 +- local-cli/generator/templates.js | 127 ++- local-cli/info/info.js | 15 +- local-cli/init/init.js | 36 +- local-cli/install/install.js | 3 + local-cli/install/uninstall.js | 3 + local-cli/library/library.js | 52 +- .../link/__tests__/android/applyPatch.spec.js | 11 +- .../__tests__/android/isInstalled.spec.js | 9 +- .../__tests__/android/makeBuildPatch.spec.js | 7 +- .../__tests__/android/makeImportPatch.spec.js | 6 +- .../android/makePackagePatch.spec.js | 6 +- .../android/makeSettingsPatch.spec.js | 45 +- .../android/makeStringsPatch.spec.js | 6 +- .../android/normalizeProjectName.spec.js | 11 +- .../__tests__/getDependencyConfig.spec.js | 3 +- .../__tests__/getProjectDependencies.spec.js | 8 +- .../link/__tests__/groupFilesByType.spec.js | 13 +- .../__tests__/ios/addFileToProject.spec.js | 8 +- .../ios/addProjectToLibraries.spec.js | 3 +- .../__tests__/ios/addSharedLibraries.spec.js | 5 +- .../link/__tests__/ios/createGroup.spec.js | 16 +- .../__tests__/ios/getBuildProperty.spec.js | 3 +- local-cli/link/__tests__/ios/getGroup.spec.js | 3 +- .../__tests__/ios/getHeaderSearchPath.spec.js | 62 +- .../__tests__/ios/getHeadersInFolder.spec.js | 1 + local-cli/link/__tests__/ios/getPlist.spec.js | 3 +- .../link/__tests__/ios/getPlistPath.spec.js | 3 +- .../link/__tests__/ios/getProducts.spec.js | 3 +- .../link/__tests__/ios/getTargets.spec.js | 3 +- .../__tests__/ios/hasLibraryImported.spec.js | 3 +- .../link/__tests__/ios/isInstalled.spec.js | 11 +- .../ios/mapHeaderSearchPaths.spec.js | 3 +- .../ios/removeProjectFromLibraries.js | 5 +- .../ios/removeProjectFromProject.spec.js | 8 +- .../__tests__/ios/removeSharedLibrary.spec.js | 5 +- .../link/__tests__/ios/writePlist.spec.js | 7 +- local-cli/link/__tests__/link.spec.js | 187 ++-- .../__tests__/pods/findLineToAddPod.spec.js | 21 +- .../pods/findMarkedLinesInPodfile.spec.js | 14 +- .../__tests__/pods/findPodTargetLine.spec.js | 1 + .../link/__tests__/pods/isInstalled.spec.js | 17 +- .../__tests__/pods/removePodEntry.spec.js | 16 +- .../link/__tests__/promiseWaterfall.spec.js | 9 +- local-cli/link/android/copyAssets.js | 7 +- local-cli/link/android/fs.js | 12 +- local-cli/link/android/index.js | 4 +- local-cli/link/android/isInstalled.js | 2 + local-cli/link/android/patches/applyParams.js | 15 +- local-cli/link/android/patches/applyPatch.js | 10 +- .../link/android/patches/makeBuildPatch.js | 6 +- .../link/android/patches/makeImportPatch.js | 2 + .../link/android/patches/makePackagePatch.js | 2 + .../link/android/patches/makeSettingsPatch.js | 14 +- .../link/android/patches/makeStringsPatch.js | 19 +- .../android/patches/normalizeProjectName.js | 1 + local-cli/link/android/patches/revokePatch.js | 8 +- .../link/android/registerNativeModule.js | 10 +- local-cli/link/android/unlinkAssets.js | 10 +- .../link/android/unregisterNativeModule.js | 12 +- local-cli/link/commandStub.js | 4 +- local-cli/link/getDependencyConfig.js | 2 + local-cli/link/getProjectDependencies.js | 6 +- local-cli/link/groupFilesByType.js | 2 + local-cli/link/ios/addFileToProject.js | 2 + local-cli/link/ios/addProjectToLibraries.js | 2 + local-cli/link/ios/addSharedLibraries.js | 4 +- local-cli/link/ios/addToHeaderSearchPaths.js | 2 + local-cli/link/ios/common/isInstalled.js | 7 +- .../link/ios/common/registerNativeModule.js | 7 +- .../link/ios/common/unregisterNativeModule.js | 7 +- local-cli/link/ios/copyAssets.js | 18 +- local-cli/link/ios/createGroup.js | 28 +- local-cli/link/ios/createGroupWithMessage.js | 4 +- local-cli/link/ios/getBuildProperty.js | 10 +- local-cli/link/ios/getGroup.js | 7 +- local-cli/link/ios/getHeaderSearchPath.js | 23 +- local-cli/link/ios/getHeadersInFolder.js | 9 +- local-cli/link/ios/getPlist.js | 6 +- local-cli/link/ios/getPlistPath.js | 4 +- local-cli/link/ios/getProducts.js | 5 +- local-cli/link/ios/getTargets.js | 20 +- local-cli/link/ios/hasLibraryImported.js | 9 +- local-cli/link/ios/index.js | 4 +- local-cli/link/ios/isInstalled.js | 2 + local-cli/link/ios/mapHeaderSearchPaths.js | 22 +- local-cli/link/ios/registerNativeModule.js | 29 +- .../link/ios/removeFromHeaderSearchPaths.js | 6 +- .../removeFromPbxItemContainerProxySection.js | 7 +- .../ios/removeFromPbxReferenceProxySection.js | 2 + .../link/ios/removeFromProjectReferences.js | 8 +- .../link/ios/removeFromStaticLibraries.js | 2 + local-cli/link/ios/removeProductGroup.js | 2 + .../link/ios/removeProjectFromLibraries.js | 6 +- .../link/ios/removeProjectFromProject.js | 2 + local-cli/link/ios/removeSharedLibraries.js | 4 +- local-cli/link/ios/unlinkAssets.js | 17 +- local-cli/link/ios/unregisterNativeModule.js | 25 +- local-cli/link/ios/writePlist.js | 4 +- local-cli/link/link.js | 126 ++- local-cli/link/pods/addPodEntry.js | 15 +- local-cli/link/pods/findLineToAddPod.js | 7 +- .../link/pods/findMarkedLinesInPodfile.js | 4 +- local-cli/link/pods/findPodTargetLine.js | 7 +- local-cli/link/pods/isInstalled.js | 7 +- local-cli/link/pods/readPodfile.js | 2 + local-cli/link/pods/registerNativeModule.js | 10 +- local-cli/link/pods/removePodEntry.js | 9 +- local-cli/link/pods/savePodFile.js | 2 + local-cli/link/pods/unregisterNativeModule.js | 8 +- local-cli/link/pollParams.js | 15 +- local-cli/link/promiseWaterfall.js | 4 +- local-cli/link/promisify.js | 9 +- local-cli/link/unlink.js | 113 ++- local-cli/logAndroid/logAndroid.js | 16 +- local-cli/logIOS/logIOS.js | 32 +- local-cli/runAndroid/adb.js | 7 +- local-cli/runAndroid/runAndroid.js | 384 +++++--- .../__tests__/findMatchingSimulator-test.js | 871 +++++++++--------- .../runIOS/__tests__/findXcodeProject-test.js | 62 +- .../__tests__/parseIOSDevicesList-test.js | 39 +- local-cli/runIOS/findMatchingSimulator.js | 9 +- local-cli/runIOS/findXcodeProject.js | 8 +- local-cli/runIOS/parseIOSDevicesList.js | 14 +- local-cli/runIOS/runIOS.js | 364 +++++--- local-cli/server/checkNodeVersion.js | 29 +- .../middleware/copyToClipBoardMiddleware.js | 3 + local-cli/server/middleware/indexPage.js | 3 + .../middleware/loadRawBodyMiddleware.js | 3 + .../openStackFrameInEditorMiddleware.js | 3 + .../server/middleware/statusPageMiddleware.js | 3 + .../middleware/systraceProfileMiddleware.js | 7 +- local-cli/server/middleware/unless.js | 5 +- local-cli/server/server.js | 177 ++-- local-cli/server/util/copyToClipBoard.js | 33 +- .../server/util/debugger-ui/debuggerWorker.js | 15 +- local-cli/server/util/jsPackagerClient.js | 93 +- local-cli/server/util/launchChrome.js | 41 +- local-cli/server/util/launchEditor.js | 48 +- local-cli/server/util/messageSocket.js | 111 ++- local-cli/server/util/webSocketProxy.js | 16 +- local-cli/templates/HelloNavigation/App.js | 6 +- .../components/KeyboardSpacer.js | 36 +- .../HelloNavigation/components/ListItem.js | 6 +- .../templates/HelloNavigation/lib/Backend.js | 16 +- .../views/HomeScreenTabNavigator.js | 4 +- .../views/chat/ChatListScreen.js | 15 +- .../HelloNavigation/views/chat/ChatScreen.js | 49 +- .../views/welcome/WelcomeScreen.js | 19 +- .../views/welcome/WelcomeText.android.js | 24 +- .../views/welcome/WelcomeText.ios.js | 25 +- local-cli/templates/HelloWorld/App.js | 29 +- .../templates/HelloWorld/__tests__/App.js | 6 +- local-cli/templates/HelloWorld/index.js | 6 +- local-cli/upgrade/upgrade.js | 82 +- local-cli/util/PackageManager.js | 10 +- local-cli/util/__mocks__/log.js | 3 + local-cli/util/assertRequiredOptions.js | 7 +- local-cli/util/copyAndReplace.js | 26 +- local-cli/util/findReactNativeScripts.js | 4 +- local-cli/util/findSymlinksPaths.js | 15 +- local-cli/util/isPackagerRunning.js | 17 +- local-cli/util/isValidPackageName.js | 3 + local-cli/util/log.js | 3 + local-cli/util/parseCommandLine.js | 3 + local-cli/util/walk.js | 3 + local-cli/util/yarn.js | 11 +- 209 files changed, 3167 insertions(+), 2071 deletions(-) diff --git a/local-cli/__mocks__/beeper.js b/local-cli/__mocks__/beeper.js index 2bbac3717fb..6628a2edc06 100644 --- a/local-cli/__mocks__/beeper.js +++ b/local-cli/__mocks__/beeper.js @@ -3,10 +3,13 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ - 'use strict'; + +'use strict'; // beeper@1.1.0 has a return statement outside of a function // and therefore doesn't parse. Let's mock it so that we can // run the tests. -module.exports = function () {}; +module.exports = function() {}; diff --git a/local-cli/bundle/__mocks__/sign.js b/local-cli/bundle/__mocks__/sign.js index a7f2bdb6fc8..f8f9174f9b6 100644 --- a/local-cli/bundle/__mocks__/sign.js +++ b/local-cli/bundle/__mocks__/sign.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; function sign(source) { diff --git a/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js b/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js index d39058dc6ba..3b6f3b355e0 100644 --- a/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js +++ b/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js @@ -4,19 +4,23 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ + 'use strict'; -jest - .dontMock('../filterPlatformAssetScales') - .dontMock('../assetPathUtils'); +jest.dontMock('../filterPlatformAssetScales').dontMock('../assetPathUtils'); const filterPlatformAssetScales = require('../filterPlatformAssetScales'); describe('filterPlatformAssetScales', () => { it('removes everything but 2x and 3x for iOS', () => { - expect(filterPlatformAssetScales('ios', [1, 1.5, 2, 3, 4])).toEqual([1, 2, 3]); + expect(filterPlatformAssetScales('ios', [1, 1.5, 2, 3, 4])).toEqual([ + 1, + 2, + 3, + ]); expect(filterPlatformAssetScales('ios', [3, 4])).toEqual([3]); }); @@ -28,6 +32,11 @@ describe('filterPlatformAssetScales', () => { }); it('keeps all scales for unknown platform', () => { - expect(filterPlatformAssetScales('freebsd', [1, 1.5, 2, 3.7])).toEqual([1, 1.5, 2, 3.7]); + expect(filterPlatformAssetScales('freebsd', [1, 1.5, 2, 3.7])).toEqual([ + 1, + 1.5, + 2, + 3.7, + ]); }); }); diff --git a/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js b/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js index bd8e78d18d0..cca0ce2af61 100644 --- a/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js +++ b/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js @@ -4,13 +4,13 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ + 'use strict'; -jest - .dontMock('../getAssetDestPathAndroid') - .dontMock('../assetPathUtils'); +jest.dontMock('../getAssetDestPathAndroid').dontMock('../assetPathUtils'); const getAssetDestPathAndroid = require('../getAssetDestPathAndroid'); @@ -24,7 +24,9 @@ describe('getAssetDestPathAndroid', () => { const expectDestPathForScaleToStartWith = (scale, path) => { if (!getAssetDestPathAndroid(asset, scale).startsWith(path)) { - throw new Error(`asset for scale ${scale} should start with path '${path}'`); + throw new Error( + `asset for scale ${scale} should start with path '${path}'`, + ); } }; @@ -43,7 +45,7 @@ describe('getAssetDestPathAndroid', () => { }; expect(getAssetDestPathAndroid(asset, 1)).toBe( - 'drawable-mdpi/app_test_icon.png' + 'drawable-mdpi/app_test_icon.png', ); }); @@ -54,9 +56,7 @@ describe('getAssetDestPathAndroid', () => { httpServerLocation: '/assets/RKJSModules/Apps/AndroidSample/Assets', }; - expect( - getAssetDestPathAndroid(asset, 1).startsWith('assets_') - ).toBeFalsy(); + expect(getAssetDestPathAndroid(asset, 1).startsWith('assets_')).toBeFalsy(); }); it('should put non-drawable resources to `raw/`', () => { @@ -66,8 +66,6 @@ describe('getAssetDestPathAndroid', () => { httpServerLocation: '/assets/app/test', }; - expect(getAssetDestPathAndroid(asset, 1)).toBe( - 'raw/app_test_video.mp4' - ); + expect(getAssetDestPathAndroid(asset, 1)).toBe('raw/app_test_video.mp4'); }); }); diff --git a/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js b/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js index 52e54530ba7..620c01571c7 100644 --- a/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js +++ b/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ + 'use strict'; jest.dontMock('../getAssetDestPathIOS'); diff --git a/local-cli/bundle/assetPathUtils.js b/local-cli/bundle/assetPathUtils.js index 891908eb480..95d2f6c6939 100644 --- a/local-cli/bundle/assetPathUtils.js +++ b/local-cli/bundle/assetPathUtils.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -17,12 +18,18 @@ import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry'; */ function getAndroidAssetSuffix(scale: number): string { switch (scale) { - case 0.75: return 'ldpi'; - case 1: return 'mdpi'; - case 1.5: return 'hdpi'; - case 2: return 'xhdpi'; - case 3: return 'xxhdpi'; - case 4: return 'xxxhdpi'; + case 0.75: + return 'ldpi'; + case 1: + return 'mdpi'; + case 1.5: + return 'hdpi'; + case 2: + return 'xhdpi'; + case 3: + return 'xxhdpi'; + case 4: + return 'xxxhdpi'; } throw new Error('no such scale'); } @@ -45,8 +52,8 @@ function getAndroidResourceFolderName(asset: PackagerAsset, scale: number) { var suffix = getAndroidAssetSuffix(scale); if (!suffix) { throw new Error( - 'Don\'t know which android drawable suffix to use for asset: ' + - JSON.stringify(asset) + "Don't know which android drawable suffix to use for asset: " + + JSON.stringify(asset), ); } const androidFolder = 'drawable-' + suffix; @@ -57,9 +64,9 @@ function getAndroidResourceIdentifier(asset: PackagerAsset) { var folderPath = getBasePath(asset); return (folderPath + '/' + asset.name) .toLowerCase() - .replace(/\//g, '_') // Encode folder structure in file name - .replace(/([^a-z0-9_])/g, '') // Remove illegal chars - .replace(/^assets_/, ''); // Remove "assets_" prefix + .replace(/\//g, '_') // Encode folder structure in file name + .replace(/([^a-z0-9_])/g, '') // Remove illegal chars + .replace(/^assets_/, ''); // Remove "assets_" prefix } function getBasePath(asset: PackagerAsset) { @@ -74,5 +81,5 @@ module.exports = { getAndroidAssetSuffix: getAndroidAssetSuffix, getAndroidResourceFolderName: getAndroidResourceFolderName, getAndroidResourceIdentifier: getAndroidResourceIdentifier, - getBasePath: getBasePath + getBasePath: getBasePath, }; diff --git a/local-cli/bundle/buildBundle.js b/local-cli/bundle/buildBundle.js index 66872a9c816..b6ad5a55105 100644 --- a/local-cli/bundle/buildBundle.js +++ b/local-cli/bundle/buildBundle.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -117,11 +118,7 @@ async function buildBundle( }); // When we're done saving bundle output and the assets, we're done. - const assets = await saveAssets( - outputAssets, - args.platform, - args.assetsDest, - ); + const assets = await saveAssets(outputAssets, args.platform, args.assetsDest); server.end(); diff --git a/local-cli/bundle/bundle.js b/local-cli/bundle/bundle.js index 7bc7099b58f..96d995db46c 100644 --- a/local-cli/bundle/bundle.js +++ b/local-cli/bundle/bundle.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const buildBundle = require('./buildBundle'); diff --git a/local-cli/bundle/bundleCommandLineArgs.js b/local-cli/bundle/bundleCommandLineArgs.js index cc63e32505a..4853f877ab7 100644 --- a/local-cli/bundle/bundleCommandLineArgs.js +++ b/local-cli/bundle/bundleCommandLineArgs.js @@ -3,68 +3,94 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; module.exports = [ { command: '--entry-file ', - description: 'Path to the root JS file, either absolute or relative to JS root', - }, { + description: + 'Path to the root JS file, either absolute or relative to JS root', + }, + { command: '--platform [string]', description: 'Either "ios" or "android"', default: 'ios', - }, { + }, + { command: '--transformer [string]', description: 'Specify a custom transformer to be used', - }, { + }, + { command: '--dev [boolean]', description: 'If false, warnings are disabled and the bundle is minified', - parse: (val) => val === 'false' ? false : true, + parse: val => (val === 'false' ? false : true), default: true, - }, { + }, + { command: '--minify [boolean]', - description: 'Allows overriding whether bundle is minified. This defaults to ' + + description: + 'Allows overriding whether bundle is minified. This defaults to ' + 'false if dev is true, and true if dev is false. Disabling minification ' + 'can be useful for speeding up production builds for testing purposes.', - parse: (val) => val === 'false' ? false : true, - }, { + parse: val => (val === 'false' ? false : true), + }, + { command: '--bundle-output ', - description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle', - }, { + description: + 'File name where to store the resulting bundle, ex. /tmp/groups.bundle', + }, + { command: '--bundle-encoding [string]', - description: 'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).', + description: + 'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).', default: 'utf8', - }, { + }, + { command: '--max-workers [number]', - description: 'Specifies the maximum number of workers the worker-pool ' + + description: + 'Specifies the maximum number of workers the worker-pool ' + 'will spawn for transforming files. This defaults to the number of the ' + 'cores available on your machine.', parse: (workers: string) => Number(workers), - }, { + }, + { command: '--sourcemap-output [string]', - description: 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map', - }, { + description: + 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map', + }, + { command: '--sourcemap-sources-root [string]', - description: 'Path to make sourcemap\'s sources entries relative to, ex. /root/dir', - }, { + description: + "Path to make sourcemap's sources entries relative to, ex. /root/dir", + }, + { command: '--sourcemap-use-absolute-path', description: 'Report SourceMapURL using its full path', default: false, - }, { + }, + { command: '--assets-dest [string]', - description: 'Directory name where to store assets referenced in the bundle', - }, { + description: + 'Directory name where to store assets referenced in the bundle', + }, + { command: '--verbose', description: 'Enables logging', default: false, - }, { + }, + { command: '--reset-cache', description: 'Removes cached files', default: false, - }, { + }, + { command: '--read-global-cache', - description: 'Try to fetch transformed JS code from the global cache, if configured.', + description: + 'Try to fetch transformed JS code from the global cache, if configured.', default: false, }, ]; diff --git a/local-cli/bundle/getAssetDestPathAndroid.js b/local-cli/bundle/getAssetDestPathAndroid.js index bdd3c49e32e..f827e3ed9e5 100644 --- a/local-cli/bundle/getAssetDestPathAndroid.js +++ b/local-cli/bundle/getAssetDestPathAndroid.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -15,8 +16,11 @@ const path = require('path'); import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry'; function getAssetDestPathAndroid(asset: PackagerAsset, scale: number): string { - const androidFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale); - const fileName = assetPathUtils.getAndroidResourceIdentifier(asset); + const androidFolder = assetPathUtils.getAndroidResourceFolderName( + asset, + scale, + ); + const fileName = assetPathUtils.getAndroidResourceIdentifier(asset); return path.join(androidFolder, fileName + '.' + asset.type); } diff --git a/local-cli/bundle/getAssetDestPathIOS.js b/local-cli/bundle/getAssetDestPathIOS.js index 61b935a1703..cca4a87d773 100644 --- a/local-cli/bundle/getAssetDestPathIOS.js +++ b/local-cli/bundle/getAssetDestPathIOS.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ diff --git a/local-cli/bundle/saveAssets.js b/local-cli/bundle/saveAssets.js index 94fe559a2b4..b069c332b48 100644 --- a/local-cli/bundle/saveAssets.js +++ b/local-cli/bundle/saveAssets.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const filterPlatformAssetScales = require('./filterPlatformAssetScales'); @@ -14,33 +17,29 @@ const log = require('../util/log').out('bundle'); const mkdirp = require('mkdirp'); const path = require('path'); -function saveAssets( - assets, - platform, - assetsDest -) { +function saveAssets(assets, platform, assetsDest) { if (!assetsDest) { console.warn('Assets destination folder is not set, skipping...'); return Promise.resolve(); } - const getAssetDestPath = platform === 'android' - ? getAssetDestPathAndroid - : getAssetDestPathIOS; + const getAssetDestPath = + platform === 'android' ? getAssetDestPathAndroid : getAssetDestPathIOS; const filesToCopy = Object.create(null); // Map src -> dest - assets - .forEach(asset => { - const validScales = new Set(filterPlatformAssetScales(platform, asset.scales)); - asset.scales.forEach((scale, idx) => { - if (!validScales.has(scale)) { - return; - } - const src = asset.files[idx]; - const dest = path.join(assetsDest, getAssetDestPath(asset, scale)); - filesToCopy[src] = dest; - }); + assets.forEach(asset => { + const validScales = new Set( + filterPlatformAssetScales(platform, asset.scales), + ); + asset.scales.forEach((scale, idx) => { + if (!validScales.has(scale)) { + return; + } + const src = asset.files[idx]; + const dest = path.join(assetsDest, getAssetDestPath(asset, scale)); + filesToCopy[src] = dest; }); + }); return copyAll(filesToCopy); } @@ -53,7 +52,7 @@ function copyAll(filesToCopy) { log('Copying ' + queue.length + ' asset files'); return new Promise((resolve, reject) => { - const copyNext = (error) => { + const copyNext = error => { if (error) { return reject(error); } @@ -76,7 +75,8 @@ function copy(src, dest, callback) { if (err) { return callback(err); } - fs.createReadStream(src) + fs + .createReadStream(src) .pipe(fs.createWriteStream(dest)) .on('finish', callback); }); diff --git a/local-cli/bundle/types.flow.js b/local-cli/bundle/types.flow.js index ecf86af407e..3fb3d930ee1 100644 --- a/local-cli/bundle/types.flow.js +++ b/local-cli/bundle/types.flow.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; /* $FlowFixMe(site=react_native_oss) */ diff --git a/local-cli/bundle/unbundle.js b/local-cli/bundle/unbundle.js index bc7785fd0ee..da4a4f70d6a 100644 --- a/local-cli/bundle/unbundle.js +++ b/local-cli/bundle/unbundle.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const bundleWithOutput = require('./bundle').withOutput; @@ -23,7 +26,8 @@ module.exports = { func: unbundle, options: bundleCommandLineArgs.concat({ command: '--indexed-unbundle', - description: 'Force indexed unbundle file format, even when building for android', + description: + 'Force indexed unbundle file format, even when building for android', default: false, }), }; diff --git a/local-cli/cli.js b/local-cli/cli.js index 3f31cbad477..04f0950052b 100644 --- a/local-cli/cli.js +++ b/local-cli/cli.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; // gracefulify() has to be called before anything else runs diff --git a/local-cli/cliEntry.js b/local-cli/cliEntry.js index 018dd8459a5..952ccd29bcf 100644 --- a/local-cli/cliEntry.js +++ b/local-cli/cliEntry.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; const config = require('./core'); @@ -30,9 +32,9 @@ import type {RNConfig} from './core'; commander.version(pkg.version); -const defaultOptParser = (val) => val; +const defaultOptParser = val => val; -const handleError = (err) => { +const handleError = err => { console.error(); console.error(err.message || err); console.error(); @@ -48,15 +50,12 @@ function printHelpInformation() { } const sourceInformation = this.pkg - ? [ - ` ${chalk.bold('Source:')} ${this.pkg.name}@${this.pkg.version}`, - '', - ] + ? [` ${chalk.bold('Source:')} ${this.pkg.name}@${this.pkg.version}`, ''] : []; let output = [ '', - chalk.bold(chalk.cyan((` react-native ${cmdName} ${this.usage()}`))), + chalk.bold(chalk.cyan(` react-native ${cmdName} ${this.usage()}`)), ` ${this._description}`, '', ...sourceInformation, @@ -67,9 +66,9 @@ function printHelpInformation() { ]; if (this.examples && this.examples.length > 0) { - const formattedUsage = this.examples.map( - example => ` ${example.desc}: \n ${chalk.cyan(example.cmd)}`, - ).join('\n\n'); + const formattedUsage = this.examples + .map(example => ` ${example.desc}: \n ${chalk.cyan(example.cmd)}`) + .join('\n\n'); output = output.concat([ chalk.bold(' Example usage:'), @@ -78,21 +77,22 @@ function printHelpInformation() { ]); } - return output.concat([ - '', - '', - ]).join('\n'); + return output.concat(['', '']).join('\n'); } function printUnknownCommand(cmdName) { - console.log([ - '', - cmdName - ? chalk.red(` Unrecognized command '${cmdName}'`) - : chalk.red(' You didn\'t pass any command'), - ` Run ${chalk.cyan('react-native --help')} to see list of all available commands`, - '', - ].join('\n')); + console.log( + [ + '', + cmdName + ? chalk.red(` Unrecognized command '${cmdName}'`) + : chalk.red(" You didn't pass any command"), + ` Run ${chalk.cyan( + 'react-native --help', + )} to see list of all available commands`, + '', + ].join('\n'), + ); } const addCommand = (command: CommandT, cfg: RNConfig) => { @@ -115,17 +115,18 @@ const addCommand = (command: CommandT, cfg: RNConfig) => { .catch(handleError); }); - cmd.helpInformation = printHelpInformation.bind(cmd); - cmd.examples = command.examples; - cmd.pkg = command.pkg; + cmd.helpInformation = printHelpInformation.bind(cmd); + cmd.examples = command.examples; + cmd.pkg = command.pkg; - options - .forEach(opt => cmd.option( + options.forEach(opt => + cmd.option( opt.command, opt.description, opt.parse || defaultOptParser, typeof opt.default === 'function' ? opt.default(cfg) : opt.default, - )); + ), + ); // Placeholder option for --config, which is parsed before any other option, // but needs to be here to avoid "unknown option" errors when specified @@ -143,7 +144,9 @@ function run() { commander.parse(process.argv); - const isValidCommand = commands.find(cmd => cmd.name.split(' ')[0] === process.argv[2]); + const isValidCommand = commands.find( + cmd => cmd.name.split(' ')[0] === process.argv[2], + ); if (!isValidCommand) { printUnknownCommand(process.argv[2]); diff --git a/local-cli/commands.js b/local-cli/commands.js index 1e1a2054738..f75207bd3bc 100644 --- a/local-cli/commands.js +++ b/local-cli/commands.js @@ -4,13 +4,15 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; -const { getProjectCommands } = require('./core'); +const {getProjectCommands} = require('./core'); -import type { RNConfig } from './core'; +import type {RNConfig} from './core'; export type CommandT = { name: string, @@ -58,10 +60,12 @@ const undocumentedCommands = [ { name: 'init', func: () => { - console.log([ - 'Looks like React Native project already exists in the current', - 'folder. Run this command from a different folder or remove node_modules/react-native', - ].join('\n')); + console.log( + [ + 'Looks like React Native project already exists in the current', + 'folder. Run this command from a different folder or remove node_modules/react-native', + ].join('\n'), + ); }, }, ]; diff --git a/local-cli/core/__fixtures__/android.js b/local-cli/core/__fixtures__/android.js index 6e8c9c20d31..2d6447b8756 100644 --- a/local-cli/core/__fixtures__/android.js +++ b/local-cli/core/__fixtures__/android.js @@ -1,8 +1,14 @@ +/** @format */ + const fs = require.requireActual('fs'); const path = require('path'); -const manifest = fs.readFileSync(path.join(__dirname, './files/AndroidManifest.xml')); -const mainJavaClass = fs.readFileSync(path.join(__dirname, './files/Main.java')); +const manifest = fs.readFileSync( + path.join(__dirname, './files/AndroidManifest.xml'), +); +const mainJavaClass = fs.readFileSync( + path.join(__dirname, './files/Main.java'), +); function generateValidFileStructure(classFileName) { return { @@ -13,7 +19,9 @@ function generateValidFileStructure(classFileName) { some: { example: { 'Main.java': mainJavaClass, - [classFileName]: fs.readFileSync(path.join(__dirname, `./files/${classFileName}`)), + [classFileName]: fs.readFileSync( + path.join(__dirname, `./files/${classFileName}`), + ), }, }, }, @@ -34,13 +42,17 @@ exports.userConfigManifest = { some: { example: { 'Main.java': mainJavaClass, - 'ReactPackage.java': fs.readFileSync(path.join(__dirname, './files/ReactPackage.java')), + 'ReactPackage.java': fs.readFileSync( + path.join(__dirname, './files/ReactPackage.java'), + ), }, }, }, }, debug: { - 'AndroidManifest.xml': fs.readFileSync(path.join(__dirname, './files/AndroidManifest-debug.xml')), + 'AndroidManifest.xml': fs.readFileSync( + path.join(__dirname, './files/AndroidManifest-debug.xml'), + ), }, }, }; diff --git a/local-cli/core/__fixtures__/commands.js b/local-cli/core/__fixtures__/commands.js index cbe4193be29..2f98b7ef505 100644 --- a/local-cli/core/__fixtures__/commands.js +++ b/local-cli/core/__fixtures__/commands.js @@ -1,15 +1,20 @@ +/** @format */ + exports.single = { func: () => {}, description: 'Test action', name: 'test', }; -exports.multiple = [{ - func: () => {}, - description: 'Test action #1', - name: 'test1', -}, { - func: () => {}, - description: 'Test action #2', - name: 'test2', -}]; +exports.multiple = [ + { + func: () => {}, + description: 'Test action #1', + name: 'test1', + }, + { + func: () => {}, + description: 'Test action #2', + name: 'test2', + }, +]; diff --git a/local-cli/core/__fixtures__/dependencies.js b/local-cli/core/__fixtures__/dependencies.js index 286064e8fe7..decb08a161c 100644 --- a/local-cli/core/__fixtures__/dependencies.js +++ b/local-cli/core/__fixtures__/dependencies.js @@ -1,3 +1,5 @@ +/** @format */ + const fs = require.requireActual('fs'); const path = require('path'); const android = require('./android'); diff --git a/local-cli/core/__fixtures__/ios.js b/local-cli/core/__fixtures__/ios.js index 92256edcd61..99e84080fba 100644 --- a/local-cli/core/__fixtures__/ios.js +++ b/local-cli/core/__fixtures__/ios.js @@ -1,19 +1,25 @@ +/** @format */ + const fs = require.requireActual('fs'); const path = require('path'); exports.valid = { 'demoProject.xcodeproj': { - 'project.pbxproj': fs.readFileSync(path.join(__dirname, './files/project.pbxproj')), + 'project.pbxproj': fs.readFileSync( + path.join(__dirname, './files/project.pbxproj'), + ), }, - 'TestPod.podspec': 'empty' + 'TestPod.podspec': 'empty', }; exports.validTestName = { 'MyTestProject.xcodeproj': { - 'project.pbxproj': fs.readFileSync(path.join(__dirname, './files/project.pbxproj')), + 'project.pbxproj': fs.readFileSync( + path.join(__dirname, './files/project.pbxproj'), + ), }, }; exports.pod = { - 'TestPod.podspec': 'empty' + 'TestPod.podspec': 'empty', }; diff --git a/local-cli/core/__fixtures__/projects.js b/local-cli/core/__fixtures__/projects.js index a9a74e06e02..28414b3d95a 100644 --- a/local-cli/core/__fixtures__/projects.js +++ b/local-cli/core/__fixtures__/projects.js @@ -1,10 +1,12 @@ +/** @format */ + const android = require('./android'); const ios = require('./ios'); const flat = { android: android.valid, ios: ios.valid, - Podfile: 'empty' + Podfile: 'empty', }; const nested = { @@ -22,7 +24,7 @@ const withExamples = { const withPods = { Podfile: 'content', - ios: ios.pod + ios: ios.pod, }; -module.exports = { flat, nested, withExamples, withPods }; +module.exports = {flat, nested, withExamples, withPods}; diff --git a/local-cli/core/__tests__/ios/findPodfilePath.spec.js b/local-cli/core/__tests__/ios/findPodfilePath.spec.js index a5e97030574..1ada4b658ed 100644 --- a/local-cli/core/__tests__/ios/findPodfilePath.spec.js +++ b/local-cli/core/__tests__/ios/findPodfilePath.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ diff --git a/local-cli/core/__tests__/ios/findPodspecName.spec.js b/local-cli/core/__tests__/ios/findPodspecName.spec.js index 91873779022..7829ab6e34e 100644 --- a/local-cli/core/__tests__/ios/findPodspecName.spec.js +++ b/local-cli/core/__tests__/ios/findPodspecName.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -32,9 +33,9 @@ describe('ios::findPodspecName', () => { user: { PacketName: { 'Another.podspec': 'empty', - 'PacketName.podspec': 'empty' - } - } + 'PacketName.podspec': 'empty', + }, + }, }); expect(findPodspecName('/user/PacketName')).toBe('PacketName'); }); @@ -44,9 +45,9 @@ describe('ios::findPodspecName', () => { user: { packet: { 'Another.podspec': 'empty', - 'PacketName.podspec': 'empty' - } - } + 'PacketName.podspec': 'empty', + }, + }, }); expect(findPodspecName('/user/packet')).toBe('Another'); }); diff --git a/local-cli/core/android/findAndroidAppFolder.js b/local-cli/core/android/findAndroidAppFolder.js index 6eac1dea16c..4eb3416d953 100644 --- a/local-cli/core/android/findAndroidAppFolder.js +++ b/local-cli/core/android/findAndroidAppFolder.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const fs = require('fs'); diff --git a/local-cli/core/android/findManifest.js b/local-cli/core/android/findManifest.js index 481a8a47452..9bacbee4742 100644 --- a/local-cli/core/android/findManifest.js +++ b/local-cli/core/android/findManifest.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const glob = require('glob'); diff --git a/local-cli/core/android/findPackageClassName.js b/local-cli/core/android/findPackageClassName.js index 45e2706a4d2..6fe1d3c359f 100644 --- a/local-cli/core/android/findPackageClassName.js +++ b/local-cli/core/android/findPackageClassName.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const fs = require('fs'); @@ -17,7 +20,7 @@ const path = require('path'); * @param {String} folder Folder to find java/kt files */ module.exports = function getPackageClassName(folder) { - const files = glob.sync('**/+(*.java|*.kt)', { cwd: folder }); + const files = glob.sync('**/+(*.java|*.kt)', {cwd: folder}); const packages = files .map(filePath => fs.readFileSync(path.join(folder, filePath), 'utf8')) diff --git a/local-cli/core/android/index.js b/local-cli/core/android/index.js index c21ca60d8f7..914341a1223 100644 --- a/local-cli/core/android/index.js +++ b/local-cli/core/android/index.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const findAndroidAppFolder = require('./findAndroidAppFolder'); @@ -12,7 +15,7 @@ const findPackageClassName = require('./findPackageClassName'); const path = require('path'); const readManifest = require('./readManifest'); -const getPackageName = (manifest) => manifest.attr.package; +const getPackageName = manifest => manifest.attr.package; /** * Gets android project config by analyzing given folder and taking some @@ -43,33 +46,34 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig) { throw new Error(`Package name not found in ${manifestPath}`); } - const packageFolder = userConfig.packageFolder || - packageName.replace(/\./g, path.sep); + const packageFolder = + userConfig.packageFolder || packageName.replace(/\./g, path.sep); const mainFilePath = path.join( sourceDir, - userConfig.mainFilePath || `src/main/java/${packageFolder}/MainApplication.java` + userConfig.mainFilePath || + `src/main/java/${packageFolder}/MainApplication.java`, ); const stringsPath = path.join( sourceDir, - userConfig.stringsPath || 'src/main/res/values/strings.xml' + userConfig.stringsPath || 'src/main/res/values/strings.xml', ); const settingsGradlePath = path.join( folder, 'android', - userConfig.settingsGradlePath || 'settings.gradle' + userConfig.settingsGradlePath || 'settings.gradle', ); const assetsPath = path.join( sourceDir, - userConfig.assetsPath || 'src/main/assets' + userConfig.assetsPath || 'src/main/assets', ); const buildGradlePath = path.join( sourceDir, - userConfig.buildGradlePath || 'build.gradle' + userConfig.buildGradlePath || 'build.gradle', ); return { @@ -89,7 +93,10 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig) { * Same as projectConfigAndroid except it returns * different config that applies to packages only */ -exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig) { +exports.dependencyConfig = function dependencyConfigAndroid( + folder, + userConfig, +) { const src = userConfig.sourceDir || findAndroidAppFolder(folder); if (!src) { @@ -116,13 +123,14 @@ exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig) return null; } - const packageImportPath = userConfig.packageImportPath || + const packageImportPath = + userConfig.packageImportPath || `import ${packageName}.${packageClassName};`; - const packageInstance = userConfig.packageInstance || - `new ${packageClassName}()`; + const packageInstance = + userConfig.packageInstance || `new ${packageClassName}()`; - return { sourceDir, folder, manifest, packageImportPath, packageInstance }; + return {sourceDir, folder, manifest, packageImportPath, packageInstance}; }; exports.linkConfig = require('../../link/android'); diff --git a/local-cli/core/android/readManifest.js b/local-cli/core/android/readManifest.js index 7215c67b18e..7d61883ca21 100644 --- a/local-cli/core/android/readManifest.js +++ b/local-cli/core/android/readManifest.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const fs = require('fs'); diff --git a/local-cli/core/findAssets.js b/local-cli/core/findAssets.js index 1240f25e7eb..db8b2360031 100644 --- a/local-cli/core/findAssets.js +++ b/local-cli/core/findAssets.js @@ -3,14 +3,17 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const glob = require('glob'); const path = require('path'); -const findAssetsInFolder = (folder) => - glob.sync(path.join(folder, '**'), { nodir: true }); +const findAssetsInFolder = folder => + glob.sync(path.join(folder, '**'), {nodir: true}); /** * Given an array of assets folders, e.g. ['Fonts', 'Images'], @@ -21,8 +24,9 @@ const findAssetsInFolder = (folder) => module.exports = function findAssets(folder, assets) { return (assets || []) .map(assetsFolder => path.join(folder, assetsFolder)) - .reduce((_assets, assetsFolder) => - _assets.concat(findAssetsInFolder(assetsFolder)), - [] + .reduce( + (_assets, assetsFolder) => + _assets.concat(findAssetsInFolder(assetsFolder)), + [], ); }; diff --git a/local-cli/core/findPlugins.js b/local-cli/core/findPlugins.js index fbf3f064f70..595577ba8e8 100644 --- a/local-cli/core/findPlugins.js +++ b/local-cli/core/findPlugins.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const path = require('path'); @@ -16,10 +19,11 @@ const flatten = require('lodash').flatten; * @param {String} dependency Name of the dependency * @return {Boolean} If dependency is a rnpm plugin */ -const isRNPMPlugin = (dependency) => dependency.indexOf('rnpm-plugin-') === 0; -const isReactNativePlugin = (dependency) => dependency.indexOf('react-native-') === 0; +const isRNPMPlugin = dependency => dependency.indexOf('rnpm-plugin-') === 0; +const isReactNativePlugin = dependency => + dependency.indexOf('react-native-') === 0; -const readPackage = (folder) => { +const readPackage = folder => { try { return require(path.join(folder, 'package.json')); } catch (e) { @@ -27,7 +31,7 @@ const readPackage = (folder) => { } }; -const findPluginsInReactNativePackage = (pjson) => { +const findPluginsInReactNativePackage = pjson => { if (!pjson.rnpm || !pjson.rnpm.plugin) { return []; } @@ -35,7 +39,7 @@ const findPluginsInReactNativePackage = (pjson) => { return path.join(pjson.name, pjson.rnpm.plugin); }; -const findPlatformsInPackage = (pjson) => { +const findPlatformsInPackage = pjson => { if (!pjson.rnpm || !pjson.rnpm.platform) { return []; } @@ -43,7 +47,7 @@ const findPlatformsInPackage = (pjson) => { return path.join(pjson.name, pjson.rnpm.platform); }; -const findPluginInFolder = (folder) => { +const findPluginInFolder = folder => { const pjson = readPackage(folder); if (!pjson) { @@ -52,7 +56,7 @@ const findPluginInFolder = (folder) => { const deps = union( Object.keys(pjson.dependencies || {}), - Object.keys(pjson.devDependencies || {}) + Object.keys(pjson.devDependencies || {}), ); return deps.reduce( @@ -71,7 +75,7 @@ const findPluginInFolder = (folder) => { } return {commands: commands, platforms: platforms}; }, - {commands: [], platforms: []} + {commands: [], platforms: []}, ); }; @@ -84,6 +88,6 @@ module.exports = function findPlugins(folders) { const plugins = folders.map(findPluginInFolder); return { commands: uniq(flatten(plugins.map(p => p.commands))), - platforms: uniq(flatten(plugins.map(p => p.platforms))) + platforms: uniq(flatten(plugins.map(p => p.platforms))), }; }; diff --git a/local-cli/core/index.js b/local-cli/core/index.js index 3bb0481421b..d2b3399d177 100644 --- a/local-cli/core/index.js +++ b/local-cli/core/index.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; const android = require('./android'); @@ -48,39 +50,37 @@ export type RNConfig = { getDependencyConfig(pkgName: string): Object, }; -const getRNPMConfig = (folder) => +const getRNPMConfig = folder => // $FlowFixMe non-literal require require(path.join(folder, './package.json')).rnpm || {}; -const attachPackage = (command, pkg) => Array.isArray(command) - ? command.map(cmd => attachPackage(cmd, pkg)) - : { ...command, pkg }; +const attachPackage = (command, pkg) => + Array.isArray(command) + ? command.map(cmd => attachPackage(cmd, pkg)) + : {...command, pkg}; const appRoot = process.cwd(); const plugins = findPlugins([appRoot]); -const pluginPlatforms = plugins - .platforms - .reduce((acc, pathToPlatforms) => { +const pluginPlatforms = plugins.platforms.reduce((acc, pathToPlatforms) => { + return Object.assign( + acc, // $FlowFixMe non-literal require - return Object.assign(acc, require(path.join(appRoot, 'node_modules', pathToPlatforms))); - }, - {}); + require(path.join(appRoot, 'node_modules', pathToPlatforms)), + ); +}, {}); const defaultRNConfig = { - hasteImplModulePath: require.resolve('../../jest/hasteImpl'), getProjectCommands(): Array { - const commands = plugins - .commands - .map(pathToCommands => { - const name = pathToCommands.split(path.sep)[0]; + const commands = plugins.commands.map(pathToCommands => { + const name = pathToCommands.split(path.sep)[0]; - return attachPackage( - require(path.join(appRoot, 'node_modules', pathToCommands)), - require(path.join(appRoot, 'node_modules', name, 'package.json')) - ); - }); + return attachPackage( + require(path.join(appRoot, 'node_modules', pathToCommands)), + require(path.join(appRoot, 'node_modules', name, 'package.json')), + ); + }); return flatten(commands); }, @@ -89,7 +89,7 @@ const defaultRNConfig = { return { ios, android, - ...pluginPlatforms + ...pluginPlatforms, }; }, @@ -113,7 +113,7 @@ const defaultRNConfig = { const platforms = this.getPlatformConfig(); const folder = path.join(process.cwd(), 'node_modules', packageName); const rnpm = getRNPMConfig( - path.join(process.cwd(), 'node_modules', packageName) + path.join(process.cwd(), 'node_modules', packageName), ); let config = Object.assign({}, rnpm, { @@ -135,9 +135,10 @@ const defaultRNConfig = { */ function getCliConfig(): RNConfig { const cliArgs = minimist(process.argv.slice(2)); - const config = cliArgs.config != null - ? Config.load(path.resolve(__dirname, cliArgs.config)) - : Config.findOptional(__dirname); + const config = + cliArgs.config != null + ? Config.load(path.resolve(__dirname, cliArgs.config)) + : Config.findOptional(__dirname); return {...defaultRNConfig, ...config}; } diff --git a/local-cli/core/ios/findPodfilePath.js b/local-cli/core/ios/findPodfilePath.js index 6964a8d1ac7..91efb191d63 100644 --- a/local-cli/core/ios/findPodfilePath.js +++ b/local-cli/core/ios/findPodfilePath.js @@ -1,3 +1,5 @@ +/** @format */ + 'use strict'; const fs = require('fs'); diff --git a/local-cli/core/ios/findPodspecName.js b/local-cli/core/ios/findPodspecName.js index 53a7ca5c3f1..8f43d436053 100644 --- a/local-cli/core/ios/findPodspecName.js +++ b/local-cli/core/ios/findPodspecName.js @@ -1,25 +1,24 @@ +/** @format */ + 'use strict'; const glob = require('glob'); const path = require('path'); module.exports = function findPodspecName(folder) { - const podspecs = glob.sync('*.podspec', { cwd: folder }); + const podspecs = glob.sync('*.podspec', {cwd: folder}); let podspecFile = null; if (podspecs.length === 0) { return null; - } - else if (podspecs.length === 1) { + } else if (podspecs.length === 1) { podspecFile = podspecs[0]; - } - else { + } else { const folderParts = folder.split(path.sep); const currentFolder = folderParts[folderParts.length - 1]; const toSelect = podspecs.indexOf(currentFolder + '.podspec'); if (toSelect === -1) { podspecFile = podspecs[0]; - } - else { + } else { podspecFile = podspecs[toSelect]; } } diff --git a/local-cli/core/ios/findProject.js b/local-cli/core/ios/findProject.js index 05b9e20b9b7..3a6547015af 100644 --- a/local-cli/core/ios/findProject.js +++ b/local-cli/core/ios/findProject.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const glob = require('glob'); diff --git a/local-cli/core/ios/index.js b/local-cli/core/ios/index.js index bb306f47846..f99a270fbc7 100644 --- a/local-cli/core/ios/index.js +++ b/local-cli/core/ios/index.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const findProject = require('./findProject'); @@ -15,7 +18,7 @@ const path = require('path'); * For libraries specified without an extension, add '.tbd' for those that * start with 'lib' and '.framework' to the rest. */ -const mapSharedLibaries = (libraries) => { +const mapSharedLibaries = libraries => { return libraries.map(name => { if (path.extname(name)) { return name; diff --git a/local-cli/core/makeCommand.js b/local-cli/core/makeCommand.js index a386a0fba37..07fe346918e 100644 --- a/local-cli/core/makeCommand.js +++ b/local-cli/core/makeCommand.js @@ -3,15 +3,20 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const spawn = require('child_process').spawn; module.exports = function makeCommand(command) { - return (cb) => { + return cb => { if (!cb) { - throw new Error(`You missed a callback function for the ${command} command`); + throw new Error( + `You missed a callback function for the ${command} command`, + ); } const args = command.split(' '); diff --git a/local-cli/core/wrapCommands.js b/local-cli/core/wrapCommands.js index f47cec26540..b5876a69977 100644 --- a/local-cli/core/wrapCommands.js +++ b/local-cli/core/wrapCommands.js @@ -3,14 +3,17 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const makeCommand = require('./makeCommand'); module.exports = function wrapCommands(commands) { const mappedCommands = {}; - Object.keys(commands || []).forEach((k) => { + Object.keys(commands || []).forEach(k => { mappedCommands[k] = makeCommand(commands[k]); }); return mappedCommands; diff --git a/local-cli/dependencies/dependencies.js b/local-cli/dependencies/dependencies.js index b80f68249de..543e15e21d9 100644 --- a/local-cli/dependencies/dependencies.js +++ b/local-cli/dependencies/dependencies.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const Metro = require('metro'); @@ -17,14 +20,16 @@ const {ASSET_REGISTRY_PATH} = require('../core/Constants'); function dependencies(argv, config, args, packagerInstance) { const rootModuleAbsolutePath = args.entryFile; if (!fs.existsSync(rootModuleAbsolutePath)) { - return Promise.reject(new Error(`File ${rootModuleAbsolutePath} does not exist`)); + return Promise.reject( + new Error(`File ${rootModuleAbsolutePath} does not exist`), + ); } - const transformModulePath = - args.transformer ? path.resolve(args.transformer) : - typeof config.getTransformModulePath === 'function' ? config.getTransformModulePath() : - undefined; - + const transformModulePath = args.transformer + ? path.resolve(args.transformer) + : typeof config.getTransformModulePath === 'function' + ? config.getTransformModulePath() + : undefined; const packageOpts = { assetRegistryPath: ASSET_REGISTRY_PATH, @@ -43,10 +48,7 @@ function dependencies(argv, config, args, packagerInstance) { }; const relativePath = packageOpts.projectRoots.map(root => - path.relative( - root, - rootModuleAbsolutePath - ) + path.relative(root, rootModuleAbsolutePath), )[0]; const options = { @@ -62,18 +64,19 @@ function dependencies(argv, config, args, packagerInstance) { ? fs.createWriteStream(args.output) : process.stdout; - return Promise.resolve((packagerInstance ? - packagerInstance.getOrderedDependencyPaths(options) : - Metro.getOrderedDependencyPaths(packageOpts, options)).then( - deps => { + return Promise.resolve( + (packagerInstance + ? packagerInstance.getOrderedDependencyPaths(options) + : Metro.getOrderedDependencyPaths(packageOpts, options) + ).then(deps => { deps.forEach(modulePath => { // Temporary hack to disable listing dependencies not under this directory. // Long term, we need either // (a) JS code to not depend on anything outside this directory, or // (b) Come up with a way to declare this dependency in Buck. - const isInsideProjectRoots = packageOpts.projectRoots.filter( - root => modulePath.startsWith(root) - ).length > 0; + const isInsideProjectRoots = + packageOpts.projectRoots.filter(root => modulePath.startsWith(root)) + .length > 0; if (isInsideProjectRoots) { outStream.write(modulePath + '\n'); @@ -82,8 +85,8 @@ function dependencies(argv, config, args, packagerInstance) { return writeToFile ? denodeify(outStream.end).bind(outStream)() : Promise.resolve(); - } - )); + }), + ); } module.exports = { @@ -94,27 +97,35 @@ module.exports = { { command: '--entry-file ', description: 'Absolute path to the root JS file', - }, { + }, + { command: '--output [path]', - description: 'File name where to store the output, ex. /tmp/dependencies.txt', - }, { + description: + 'File name where to store the output, ex. /tmp/dependencies.txt', + }, + { command: '--platform [extension]', description: 'The platform extension used for selecting modules', - }, { + }, + { command: '--transformer [path]', - description: 'Specify a custom transformer to be used' - }, { + description: 'Specify a custom transformer to be used', + }, + { command: '--max-workers [number]', - description: 'Specifies the maximum number of workers the worker-pool ' + + description: + 'Specifies the maximum number of workers the worker-pool ' + 'will spawn for transforming files. This defaults to the number of the ' + 'cores available on your machine.', parse: (workers: string) => Number(workers), - }, { + }, + { command: '--dev [boolean]', description: 'If false, skip all dev-only code path', - parse: (val) => val === 'false' ? false : true, + parse: val => (val === 'false' ? false : true), default: true, - }, { + }, + { command: '--verbose', description: 'Enables logging', default: false, diff --git a/local-cli/eject/eject.js b/local-cli/eject/eject.js index 569299018d3..6c18a91fb9b 100644 --- a/local-cli/eject/eject.js +++ b/local-cli/eject/eject.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace'); @@ -22,13 +25,12 @@ const fs = require('fs'); */ function eject() { - const doesIOSExist = fs.existsSync(path.resolve('ios')); const doesAndroidExist = fs.existsSync(path.resolve('android')); if (doesIOSExist && doesAndroidExist) { console.error( 'Both the iOS and Android folders already exist! Please delete `ios` and/or `android` ' + - 'before ejecting.' + 'before ejecting.', ); process.exit(1); } @@ -39,8 +41,10 @@ function eject() { } catch (e) { console.error( 'Eject requires an `app.json` config file to be located at ' + - `${path.resolve('app.json')}, and it must at least specify a \`name\` for the project ` + - 'name, and a `displayName` for the app\'s home screen label.' + `${path.resolve( + 'app.json', + )}, and it must at least specify a \`name\` for the project ` + + "name, and a `displayName` for the app's home screen label.", ); process.exit(1); } @@ -49,7 +53,7 @@ function eject() { if (!appName) { console.error( 'App `name` must be defined in the `app.json` config file to define the project name. ' + - 'It must not contain any spaces or dashes.' + 'It must not contain any spaces or dashes.', ); process.exit(1); } @@ -57,33 +61,46 @@ function eject() { if (!displayName) { console.error( 'App `displayName` must be defined in the `app.json` config file, to define the label ' + - 'of the app on the home screen.' + 'of the app on the home screen.', ); process.exit(1); } - const templateOptions = { displayName }; + const templateOptions = {displayName}; if (!doesIOSExist) { console.log('Generating the iOS folder.'); copyProjectTemplateAndReplace( - path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'ios'), + path.resolve( + 'node_modules', + 'react-native', + 'local-cli', + 'templates', + 'HelloWorld', + 'ios', + ), path.resolve('ios'), appName, - templateOptions + templateOptions, ); } if (!doesAndroidExist) { console.log('Generating the Android folder.'); copyProjectTemplateAndReplace( - path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'android'), + path.resolve( + 'node_modules', + 'react-native', + 'local-cli', + 'templates', + 'HelloWorld', + 'android', + ), path.resolve('android'), appName, - templateOptions + templateOptions, ); } - } module.exports = { diff --git a/local-cli/generator/copyProjectTemplateAndReplace.js b/local-cli/generator/copyProjectTemplateAndReplace.js index 5840e587e7e..607b3b8ed26 100644 --- a/local-cli/generator/copyProjectTemplateAndReplace.js +++ b/local-cli/generator/copyProjectTemplateAndReplace.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const chalk = require('chalk'); @@ -26,24 +29,42 @@ const walk = require('../util/walk'); * ignorePaths: ['template/file/to/ignore.md'], * } */ -function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, options) { - if (!srcPath) { throw new Error('Need a path to copy from'); } - if (!destPath) { throw new Error('Need a path to copy to'); } - if (!newProjectName) { throw new Error('Need a project name'); } +function copyProjectTemplateAndReplace( + srcPath, + destPath, + newProjectName, + options, +) { + if (!srcPath) { + throw new Error('Need a path to copy from'); + } + if (!destPath) { + throw new Error('Need a path to copy to'); + } + if (!newProjectName) { + throw new Error('Need a project name'); + } options = options || {}; walk(srcPath).forEach(absoluteSrcFilePath => { - // 'react-native upgrade' if (options.upgrade) { // Don't upgrade these files const fileName = path.basename(absoluteSrcFilePath); // This also includes __tests__/index.*.js - if (fileName === 'index.ios.js') { return; } - if (fileName === 'index.android.js') { return; } - if (fileName === 'index.js') { return; } - if (fileName === 'App.js') { return; } + if (fileName === 'index.ios.js') { + return; + } + if (fileName === 'index.android.js') { + return; + } + if (fileName === 'index.js') { + return; + } + if (fileName === 'App.js') { + return; + } } const relativeFilePath = path.relative(srcPath, absoluteSrcFilePath); @@ -59,14 +80,16 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option if (!Array.isArray(options.ignorePaths)) { throw new Error('options.ignorePaths must be an array'); } - if (options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath)) { + if ( + options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath) + ) { // Skip copying this file return; } } let contentChangedCallback = null; - if (options.upgrade && (!options.force)) { + if (options.upgrade && !options.force) { contentChangedCallback = (_, contentChanged) => { return upgradeFileContentChangedCallback( absoluteSrcFilePath, @@ -80,8 +103,8 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option path.resolve(destPath, relativeRenamedPath), { 'Hello App Display Name': options.displayName || newProjectName, - 'HelloWorld': newProjectName, - 'helloworld': newProjectName.toLowerCase(), + HelloWorld: newProjectName, + helloworld: newProjectName.toLowerCase(), }, contentChangedCallback, ); @@ -97,7 +120,9 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option * behavior of automatically renaming .gitignore to .npmignore. */ function dotFilePath(path) { - if (!path) {return path;} + if (!path) { + return path; + } return path .replace('_gitignore', '.gitignore') .replace('_gitattributes', '.gitattributes') @@ -110,20 +135,28 @@ function dotFilePath(path) { function upgradeFileContentChangedCallback( absoluteSrcFilePath, relativeDestPath, - contentChanged + contentChanged, ) { if (contentChanged === 'new') { console.log(chalk.bold('new') + ' ' + relativeDestPath); return 'overwrite'; } else if (contentChanged === 'changed') { - console.log(chalk.bold(relativeDestPath) + ' ' + - 'has changed in the new version.\nDo you want to keep your ' + - relativeDestPath + ' or replace it with the ' + - 'latest version?\nIf you ever made any changes ' + - 'to this file, you\'ll probably want to keep it.\n' + - 'You can see the new version here: ' + absoluteSrcFilePath + '\n' + - 'Do you want to replace ' + relativeDestPath + '? ' + - 'Answer y to replace, n to keep your version: '); + console.log( + chalk.bold(relativeDestPath) + + ' ' + + 'has changed in the new version.\nDo you want to keep your ' + + relativeDestPath + + ' or replace it with the ' + + 'latest version?\nIf you ever made any changes ' + + "to this file, you'll probably want to keep it.\n" + + 'You can see the new version here: ' + + absoluteSrcFilePath + + '\n' + + 'Do you want to replace ' + + relativeDestPath + + '? ' + + 'Answer y to replace, n to keep your version: ', + ); const answer = prompt(); if (answer === 'y') { console.log('Replacing ' + relativeDestPath); @@ -135,7 +168,9 @@ function upgradeFileContentChangedCallback( } else if (contentChanged === 'identical') { return 'keep'; } else { - throw new Error(`Unknown file changed state: ${relativeDestPath}, ${contentChanged}`); + throw new Error( + `Unknown file changed state: ${relativeDestPath}, ${contentChanged}`, + ); } } diff --git a/local-cli/generator/printRunInstructions.js b/local-cli/generator/printRunInstructions.js index cc39a61fd3e..eaa8e5cd8b0 100644 --- a/local-cli/generator/printRunInstructions.js +++ b/local-cli/generator/printRunInstructions.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; var chalk = require('chalk'); @@ -12,8 +15,12 @@ var path = require('path'); function printRunInstructions(projectDir, projectName) { const absoluteProjectDir = path.resolve(projectDir); // iOS - const xcodeProjectPath = path.resolve(projectDir, 'ios', projectName) + '.xcodeproj'; - const relativeXcodeProjectPath = path.relative(process.cwd(), xcodeProjectPath); + const xcodeProjectPath = + path.resolve(projectDir, 'ios', projectName) + '.xcodeproj'; + const relativeXcodeProjectPath = path.relative( + process.cwd(), + xcodeProjectPath, + ); console.log(chalk.white.bold('To run your app on iOS:')); console.log(' cd ' + absoluteProjectDir); console.log(' react-native run-ios'); @@ -23,7 +30,9 @@ function printRunInstructions(projectDir, projectName) { // Android console.log(chalk.white.bold('To run your app on Android:')); console.log(' cd ' + absoluteProjectDir); - console.log(' Have an Android emulator running (quickest way to get started), or a device connected'); + console.log( + ' Have an Android emulator running (quickest way to get started), or a device connected', + ); console.log(' react-native run-android'); } diff --git a/local-cli/generator/promptSync.js b/local-cli/generator/promptSync.js index 841af5054b8..636138abf25 100644 --- a/local-cli/generator/promptSync.js +++ b/local-cli/generator/promptSync.js @@ -1,3 +1,5 @@ +/** @format */ + // Simplified version of: // https://github.com/0x00A/prompt-sync/blob/master/index.js @@ -7,11 +9,14 @@ var fs = require('fs'); var term = 13; // carriage return function create() { - return prompt; function prompt(ask, value, opts) { - var insert = 0, savedinsert = 0, res, i, savedstr; + var insert = 0, + savedinsert = 0, + res, + i, + savedstr; opts = opts || {}; if (Object(ask) === ask) { @@ -25,15 +30,20 @@ function create() { var echo = opts.echo; var masked = 'echo' in opts; - var fd = (process.platform === 'win32') ? - process.stdin.fd : - fs.openSync('/dev/tty', 'rs'); + var fd = + process.platform === 'win32' + ? process.stdin.fd + : fs.openSync('/dev/tty', 'rs'); var wasRaw = process.stdin.isRaw; - if (!wasRaw) { process.stdin.setRawMode(true); } + if (!wasRaw) { + process.stdin.setRawMode(true); + } var buf = new Buffer(3); - var str = '', character, read; + var str = '', + character, + read; savedstr = ''; @@ -46,7 +56,8 @@ function create() { while (true) { read = fs.readSync(fd, buf, 0, 3); - if (read > 1) { // received a control sequence + if (read > 1) { + // received a control sequence if (buf.toString()) { str = str + buf.toString(); str = str.replace(/\0/g, ''); @@ -62,7 +73,7 @@ function create() { character = buf[read - 1]; // catch a ^C and return null - if (character == 3){ + if (character == 3) { process.stdout.write('^C\n'); fs.closeSync(fd); process.exit(130); @@ -76,35 +87,49 @@ function create() { break; } - if (character == 127 || (process.platform == 'win32' && character == 8)) { //backspace - if (!insert) {continue;} + if (character == 127 || (process.platform == 'win32' && character == 8)) { + //backspace + if (!insert) { + continue; + } str = str.slice(0, insert - 1) + str.slice(insert); insert--; process.stdout.write('\u001b[2D'); } else { - if ((character < 32 ) || (character > 126)) - {continue;} - str = str.slice(0, insert) + String.fromCharCode(character) + str.slice(insert); + if (character < 32 || character > 126) { + continue; + } + str = + str.slice(0, insert) + + String.fromCharCode(character) + + str.slice(insert); insert++; } if (masked) { - process.stdout.write('\u001b[2K\u001b[0G' + ask + Array(str.length + 1).join(echo)); + process.stdout.write( + '\u001b[2K\u001b[0G' + ask + Array(str.length + 1).join(echo), + ); } else { process.stdout.write('\u001b[s'); if (insert == str.length) { - process.stdout.write('\u001b[2K\u001b[0G' + ask + str); + process.stdout.write('\u001b[2K\u001b[0G' + ask + str); } else { if (ask) { process.stdout.write('\u001b[2K\u001b[0G' + ask + str); } else { - process.stdout.write('\u001b[2K\u001b[0G' + str + '\u001b[' + (str.length - insert) + 'D'); + process.stdout.write( + '\u001b[2K\u001b[0G' + + str + + '\u001b[' + + (str.length - insert) + + 'D', + ); } } process.stdout.write('\u001b[u'); process.stdout.write('\u001b[1C'); } - } process.stdout.write('\n'); diff --git a/local-cli/generator/templates.js b/local-cli/generator/templates.js index 99e63ec2e99..17e4379a72b 100644 --- a/local-cli/generator/templates.js +++ b/local-cli/generator/templates.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const copyProjectTemplateAndReplace = require('./copyProjectTemplateAndReplace'); @@ -29,15 +32,18 @@ function listTemplatesAndExit(newProjectName, options) { // above is defined correctly :) console.log( 'There are no templates available besides ' + - 'the default "Hello World" one.' + 'the default "Hello World" one.', ); } else { console.log( 'The available templates are:\n' + - templateKeys.join('\n') + - '\nYou can use these to create an app based on a template, for example: ' + - 'you could run: ' + - 'react-native init ' + newProjectName + ' --template ' + templateKeys[0] + templateKeys.join('\n') + + '\nYou can use these to create an app based on a template, for example: ' + + 'you could run: ' + + 'react-native init ' + + newProjectName + + ' --template ' + + templateKeys[0], ); } // Exit 'react-native init' @@ -54,12 +60,23 @@ function listTemplatesAndExit(newProjectName, options) { * @param yarnVersion Version of yarn available on the system, or null if * yarn is not available. For example '0.18.1'. */ -function createProjectFromTemplate(destPath, newProjectName, template, yarnVersion) { +function createProjectFromTemplate( + destPath, + newProjectName, + template, + yarnVersion, +) { // Expand the basic 'HelloWorld' template copyProjectTemplateAndReplace( - path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld'), + path.resolve( + 'node_modules', + 'react-native', + 'local-cli', + 'templates', + 'HelloWorld', + ), destPath, - newProjectName + newProjectName, ); if (template === undefined) { @@ -79,7 +96,12 @@ function createProjectFromTemplate(destPath, newProjectName, template, yarnVersi if (builtInTemplateName) { // template is e.g. 'navigation', // use the built-in local-cli/templates/HelloNavigation folder - createFromBuiltInTemplate(builtInTemplateName, destPath, newProjectName, yarnVersion); + createFromBuiltInTemplate( + builtInTemplateName, + destPath, + newProjectName, + yarnVersion, + ); } else { // template is e.g. 'ignite', // use the template react-native-template-ignite from npm @@ -89,15 +111,20 @@ function createProjectFromTemplate(destPath, newProjectName, template, yarnVersi // (We might want to get rid of built-in templates in the future - // publish them to npm and install from there.) -function createFromBuiltInTemplate(templateName, destPath, newProjectName, yarnVersion) { +function createFromBuiltInTemplate( + templateName, + destPath, + newProjectName, + yarnVersion, +) { const templatePath = path.resolve( - 'node_modules', 'react-native', 'local-cli', 'templates', templateName - ); - copyProjectTemplateAndReplace( - templatePath, - destPath, - newProjectName, + 'node_modules', + 'react-native', + 'local-cli', + 'templates', + templateName, ); + copyProjectTemplateAndReplace(templatePath, destPath, newProjectName); installTemplateDependencies(templatePath, yarnVersion); installTemplateDevDependencies(templatePath, yarnVersion); } @@ -107,13 +134,18 @@ function createFromBuiltInTemplate(templateName, destPath, newProjectName, yarnV * - 'demo' -> Fetch the package react-native-template-demo from npm * - git://..., http://..., file://... or any other URL supported by npm */ -function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersion) { +function createFromRemoteTemplate( + template, + destPath, + newProjectName, + yarnVersion, +) { let installPackage; let templateName; if (template.includes('://')) { - // URL, e.g. git://, file:// - installPackage = template; - templateName = template.substr(template.lastIndexOf('/') + 1); + // URL, e.g. git://, file:// + installPackage = template; + templateName = template.substr(template.lastIndexOf('/') + 1); } else { // e.g 'demo' installPackage = 'react-native-template-' + template; @@ -124,25 +156,23 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio console.log(`Fetching template ${installPackage}...`); try { if (yarnVersion) { - execSync(`yarn add ${installPackage} --ignore-scripts`, {stdio: 'inherit'}); + execSync(`yarn add ${installPackage} --ignore-scripts`, { + stdio: 'inherit', + }); } else { - execSync(`npm install ${installPackage} --save --save-exact --ignore-scripts`, {stdio: 'inherit'}); + execSync( + `npm install ${installPackage} --save --save-exact --ignore-scripts`, + {stdio: 'inherit'}, + ); } - const templatePath = path.resolve( - 'node_modules', templateName - ); - copyProjectTemplateAndReplace( - templatePath, - destPath, - newProjectName, - { - // Every template contains a dummy package.json file included - // only for publishing the template to npm. - // We want to ignore this dummy file, otherwise it would overwrite - // our project's package.json file. - ignorePaths: ['package.json', 'dependencies.json'], - } - ); + const templatePath = path.resolve('node_modules', templateName); + copyProjectTemplateAndReplace(templatePath, destPath, newProjectName, { + // Every template contains a dummy package.json file included + // only for publishing the template to npm. + // We want to ignore this dummy file, otherwise it would overwrite + // our project's package.json file. + ignorePaths: ['package.json', 'dependencies.json'], + }); installTemplateDependencies(templatePath, yarnVersion); installTemplateDevDependencies(templatePath, yarnVersion); } finally { @@ -158,7 +188,7 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio // if this the clean up fails. console.warn( `Failed to clean up template temp files in node_modules/${templateName}. ` + - 'This is not a critical error, you can work on your app.' + 'This is not a critical error, you can work on your app.', ); } } @@ -167,9 +197,7 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio function installTemplateDependencies(templatePath, yarnVersion) { // dependencies.json is a special file that lists additional dependencies // that are required by this template - const dependenciesJsonPath = path.resolve( - templatePath, 'dependencies.json' - ); + const dependenciesJsonPath = path.resolve(templatePath, 'dependencies.json'); console.log('Adding dependencies for the project...'); if (!fs.existsSync(dependenciesJsonPath)) { console.log('No additional dependencies.'); @@ -181,7 +209,7 @@ function installTemplateDependencies(templatePath, yarnVersion) { dependencies = JSON.parse(fs.readFileSync(dependenciesJsonPath)); } catch (err) { throw new Error( - 'Could not parse the template\'s dependencies.json: ' + err.message + "Could not parse the template's dependencies.json: " + err.message, ); } for (let depName in dependencies) { @@ -191,10 +219,12 @@ function installTemplateDependencies(templatePath, yarnVersion) { if (yarnVersion) { execSync(`yarn add ${depToInstall}`, {stdio: 'inherit'}); } else { - execSync(`npm install ${depToInstall} --save --save-exact`, {stdio: 'inherit'}); + execSync(`npm install ${depToInstall} --save --save-exact`, { + stdio: 'inherit', + }); } } - console.log('Linking native dependencies into the project\'s build files...'); + console.log("Linking native dependencies into the project's build files..."); execSync('react-native link', {stdio: 'inherit'}); } @@ -202,7 +232,8 @@ function installTemplateDevDependencies(templatePath, yarnVersion) { // devDependencies.json is a special file that lists additional develop dependencies // that are required by this template const devDependenciesJsonPath = path.resolve( - templatePath, 'devDependencies.json' + templatePath, + 'devDependencies.json', ); console.log('Adding develop dependencies for the project...'); if (!fs.existsSync(devDependenciesJsonPath)) { @@ -215,7 +246,7 @@ function installTemplateDevDependencies(templatePath, yarnVersion) { dependencies = JSON.parse(fs.readFileSync(devDependenciesJsonPath)); } catch (err) { throw new Error( - 'Could not parse the template\'s devDependencies.json: ' + err.message + "Could not parse the template's devDependencies.json: " + err.message, ); } for (let depName in dependencies) { @@ -225,7 +256,9 @@ function installTemplateDevDependencies(templatePath, yarnVersion) { if (yarnVersion) { execSync(`yarn add ${depToInstall} -D`, {stdio: 'inherit'}); } else { - execSync(`npm install ${depToInstall} --save-dev --save-exact`, {stdio: 'inherit'}); + execSync(`npm install ${depToInstall} --save-dev --save-exact`, { + stdio: 'inherit', + }); } } } diff --git a/local-cli/info/info.js b/local-cli/info/info.js index d5e4284fe0b..0164c0acde5 100644 --- a/local-cli/info/info.js +++ b/local-cli/info/info.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const envinfo = require('envinfo'); @@ -13,7 +16,10 @@ const info = function() { try { envinfo.print({ - packages: typeof args.packages === 'string' ? ['react', 'react-native'].concat(args.packages.split(',')) : args.packages + packages: + typeof args.packages === 'string' + ? ['react', 'react-native'].concat(args.packages.split(',')) + : args.packages, }); } catch (error) { console.log('Error: unable to print environment info'); @@ -27,8 +33,9 @@ module.exports = { options: [ { command: '--packages [string]', - description: 'Which packages from your package.json to include, in addition to the default React Native and React versions.', - default: ['react', 'react-native'] + description: + 'Which packages from your package.json to include, in addition to the default React Native and React versions.', + default: ['react', 'react-native'], }, ], examples: [ @@ -39,7 +46,7 @@ module.exports = { { desc: 'Get standard version info & specified package versions', cmd: 'react-native info --packages jest,eslint,babel-polyfill', - } + }, ], func: info, }; diff --git a/local-cli/init/init.js b/local-cli/init/init.js index d0233b1ab81..17273f9881d 100644 --- a/local-cli/init/init.js +++ b/local-cli/init/init.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const { @@ -58,42 +61,53 @@ function init(projectDir, argsOrName) { */ function generateProject(destinationRoot, newProjectName, options) { var reactNativePackageJson = require('../../package.json'); - var { peerDependencies } = reactNativePackageJson; + var {peerDependencies} = reactNativePackageJson; if (!peerDependencies) { - console.error('Missing React peer dependency in React Native\'s package.json. Aborting.'); + console.error( + "Missing React peer dependency in React Native's package.json. Aborting.", + ); return; } var reactVersion = peerDependencies.react; if (!reactVersion) { - console.error('Missing React peer dependency in React Native\'s package.json. Aborting.'); + console.error( + "Missing React peer dependency in React Native's package.json. Aborting.", + ); return; } const yarnVersion = - (!options.npm) && + !options.npm && yarn.getYarnVersionIfAvailable() && yarn.isGlobalCliUsingYarn(destinationRoot); - createProjectFromTemplate(destinationRoot, newProjectName, options.template, yarnVersion); + createProjectFromTemplate( + destinationRoot, + newProjectName, + options.template, + yarnVersion, + ); if (yarnVersion) { console.log('Adding React...'); execSync(`yarn add react@${reactVersion}`, {stdio: 'inherit'}); } else { console.log('Installing React...'); - execSync(`npm install react@${reactVersion} --save --save-exact`, {stdio: 'inherit'}); + execSync(`npm install react@${reactVersion} --save --save-exact`, { + stdio: 'inherit', + }); } if (!options['skip-jest']) { - const jestDeps = ( - `jest babel-jest babel-preset-react-native react-test-renderer@${reactVersion}` - ); + const jestDeps = `jest babel-jest babel-preset-react-native react-test-renderer@${reactVersion}`; if (yarnVersion) { console.log('Adding Jest...'); execSync(`yarn add ${jestDeps} --dev --exact`, {stdio: 'inherit'}); } else { console.log('Installing Jest...'); - execSync(`npm install ${jestDeps} --save-dev --save-exact`, {stdio: 'inherit'}); + execSync(`npm install ${jestDeps} --save-dev --save-exact`, { + stdio: 'inherit', + }); } addJestToPackageJson(destinationRoot); } @@ -109,7 +123,7 @@ function addJestToPackageJson(destinationRoot) { packageJSON.scripts.test = 'jest'; packageJSON.jest = { - preset: 'react-native' + preset: 'react-native', }; fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2)); } diff --git a/local-cli/install/install.js b/local-cli/install/install.js index 2efc64978d0..5a0a7afc67e 100644 --- a/local-cli/install/install.js +++ b/local-cli/install/install.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const spawnSync = require('child_process').spawnSync; diff --git a/local-cli/install/uninstall.js b/local-cli/install/uninstall.js index 0d6fc5ed755..6a71100677d 100644 --- a/local-cli/install/uninstall.js +++ b/local-cli/install/uninstall.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const spawnSync = require('child_process').spawnSync; diff --git a/local-cli/library/library.js b/local-cli/library/library.js index 14afd6a4059..4dcc81cbfcd 100644 --- a/local-cli/library/library.js +++ b/local-cli/library/library.js @@ -1,9 +1,12 @@ - /** +/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const copyAndReplace = require('../util/copyAndReplace'); @@ -18,36 +21,47 @@ const walk = require('../util/walk'); function library(argv, config, args) { if (!isValidPackageName(args.name)) { return Promise.reject( - args.name + ' is not a valid name for a project. Please use a valid ' + - 'identifier name (alphanumeric).' + args.name + + ' is not a valid name for a project. Please use a valid ' + + 'identifier name (alphanumeric).', ); } const root = process.cwd(); const libraries = path.resolve(root, 'Libraries'); const libraryDest = path.resolve(libraries, args.name); - const source = path.resolve('node_modules', 'react-native', 'Libraries', 'Sample'); + const source = path.resolve( + 'node_modules', + 'react-native', + 'Libraries', + 'Sample', + ); if (!fs.existsSync(libraries)) { fs.mkdirSync(libraries); } if (fs.existsSync(libraryDest)) { - return Promise.reject(new Error(`Library already exists in ${libraryDest}`)); + return Promise.reject( + new Error(`Library already exists in ${libraryDest}`), + ); } walk(source).forEach(f => { - if (f.indexOf('project.xcworkspace') !== -1 || - f.indexOf('.xcodeproj/xcuserdata') !== -1) { + if ( + f.indexOf('project.xcworkspace') !== -1 || + f.indexOf('.xcodeproj/xcuserdata') !== -1 + ) { return; } - const dest = path.relative(source, f.replace(/Sample/g, args.name).replace(/^_/, '.')); - copyAndReplace( - path.resolve(source, f), - path.resolve(libraryDest, dest), - {'Sample': args.name} + const dest = path.relative( + source, + f.replace(/Sample/g, args.name).replace(/^_/, '.'), ); + copyAndReplace(path.resolve(source, f), path.resolve(libraryDest, dest), { + Sample: args.name, + }); }); console.log('Created library in', libraryDest); @@ -55,7 +69,7 @@ function library(argv, config, args) { console.log(' Link your library in Xcode:'); console.log( ' https://facebook.github.io/react-native/docs/' + - 'linking-libraries-ios.html#content\n' + 'linking-libraries-ios.html#content\n', ); } @@ -63,9 +77,11 @@ module.exports = { name: 'new-library', func: library, description: 'generates a native library bridge', - options: [{ - command: '--name ', - description: 'name of the library to generate', - default: null, - }], + options: [ + { + command: '--name ', + description: 'name of the library to generate', + default: null, + }, + ], }; diff --git a/local-cli/link/__tests__/android/applyPatch.spec.js b/local-cli/link/__tests__/android/applyPatch.spec.js index b1213dbf315..79b67f68974 100644 --- a/local-cli/link/__tests__/android/applyPatch.spec.js +++ b/local-cli/link/__tests__/android/applyPatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -13,14 +14,12 @@ const applyParams = require('../../android/patches/applyParams'); describe('applyParams', () => { it('apply params to the string', () => { - expect( - applyParams('${foo}', {foo: 'foo'}, 'react-native') - ).toEqual('getResources().getString(R.string.reactNative_foo)'); + expect(applyParams('${foo}', {foo: 'foo'}, 'react-native')).toEqual( + 'getResources().getString(R.string.reactNative_foo)', + ); }); it('use null if no params provided', () => { - expect( - applyParams('${foo}', {}, 'react-native') - ).toEqual('null'); + expect(applyParams('${foo}', {}, 'react-native')).toEqual('null'); }); }); diff --git a/local-cli/link/__tests__/android/isInstalled.spec.js b/local-cli/link/__tests__/android/isInstalled.spec.js index 131d753731a..a90649f0339 100644 --- a/local-cli/link/__tests__/android/isInstalled.spec.js +++ b/local-cli/link/__tests__/android/isInstalled.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -13,7 +14,10 @@ const path = require('path'); const isInstalled = require('../../android/isInstalled'); const projectConfig = { - buildGradlePath: path.join(__dirname, '../../__fixtures__/android/patchedBuild.gradle'), + buildGradlePath: path.join( + __dirname, + '../../__fixtures__/android/patchedBuild.gradle', + ), }; describe('android::isInstalled', () => { @@ -23,6 +27,5 @@ describe('android::isInstalled', () => { }); it('should return false when project is not in build.gradle', () => - expect(isInstalled(projectConfig, 'test3')).toBeFalsy() - ); + expect(isInstalled(projectConfig, 'test3')).toBeFalsy()); }); diff --git a/local-cli/link/__tests__/android/makeBuildPatch.spec.js b/local-cli/link/__tests__/android/makeBuildPatch.spec.js index fdcdad0453b..51873daf1d0 100644 --- a/local-cli/link/__tests__/android/makeBuildPatch.spec.js +++ b/local-cli/link/__tests__/android/makeBuildPatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -18,8 +19,9 @@ const normalizedScopedName = normalizeProjectName('@scoped/test'); describe('makeBuildPatch', () => { it('should build a patch function', () => { - expect(Object.prototype.toString(makeBuildPatch(name))) - .toBe('[object Object]'); + expect(Object.prototype.toString(makeBuildPatch(name))).toBe( + '[object Object]', + ); }); it('should make a correct patch', () => { @@ -34,7 +36,6 @@ describe('makeBuildPatch', () => { }); }); - describe('makeBuildPatchWithScopedPackage', () => { it('should make a correct patch', () => { const {patch} = makeBuildPatch(scopedName); diff --git a/local-cli/link/__tests__/android/makeImportPatch.spec.js b/local-cli/link/__tests__/android/makeImportPatch.spec.js index d02eb668985..e00977a0961 100644 --- a/local-cli/link/__tests__/android/makeImportPatch.spec.js +++ b/local-cli/link/__tests__/android/makeImportPatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -15,8 +16,9 @@ const packageImportPath = 'import some.example.project'; describe('makeImportPatch', () => { it('should build a patch', () => { - expect(Object.prototype.toString(makeImportPatch(packageImportPath))) - .toBe('[object Object]'); + expect(Object.prototype.toString(makeImportPatch(packageImportPath))).toBe( + '[object Object]', + ); }); it('MainActivity contains a correct import patch', () => { diff --git a/local-cli/link/__tests__/android/makePackagePatch.spec.js b/local-cli/link/__tests__/android/makePackagePatch.spec.js index c7e55c7e90f..48e7a3c30f5 100644 --- a/local-cli/link/__tests__/android/makePackagePatch.spec.js +++ b/local-cli/link/__tests__/android/makePackagePatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -12,7 +13,7 @@ const makePackagePatch = require('../../android/patches/makePackagePatch'); const applyParams = require('../../android/patches/applyParams'); -const packageInstance = 'new SomeLibrary(${foo}, ${bar}, \'something\')'; +const packageInstance = "new SomeLibrary(${foo}, ${bar}, 'something')"; const name = 'some-library'; const params = { foo: 'foo', @@ -22,8 +23,7 @@ const params = { describe('makePackagePatch@0.20', () => { it('should build a patch', () => { const packagePatch = makePackagePatch(packageInstance, params, name); - expect(Object.prototype.toString(packagePatch)) - .toBe('[object Object]'); + expect(Object.prototype.toString(packagePatch)).toBe('[object Object]'); }); it('MainActivity contains a correct 0.20 import patch', () => { diff --git a/local-cli/link/__tests__/android/makeSettingsPatch.spec.js b/local-cli/link/__tests__/android/makeSettingsPatch.spec.js index 63954af8155..80b2be70343 100644 --- a/local-cli/link/__tests__/android/makeSettingsPatch.spec.js +++ b/local-cli/link/__tests__/android/makeSettingsPatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -29,48 +30,54 @@ const scopedDependencyConfig = { describe('makeSettingsPatch', () => { it('should build a patch function', () => { - expect(Object.prototype.toString( - makeSettingsPatch(name, dependencyConfig, projectConfig) - )).toBe('[object Object]'); + expect( + Object.prototype.toString( + makeSettingsPatch(name, dependencyConfig, projectConfig), + ), + ).toBe('[object Object]'); }); it('should make a correct patch', () => { const projectDir = path.relative( path.dirname(projectConfig.settingsGradlePath), - dependencyConfig.sourceDir + dependencyConfig.sourceDir, ); const {patch} = makeSettingsPatch(name, dependencyConfig, projectConfig); - expect(patch) - .toBe( - `include ':${name}'\n` + + expect(patch).toBe( + `include ':${name}'\n` + `project(':${name}').projectDir = ` + - `new File(rootProject.projectDir, '${projectDir}')\n` - ); + `new File(rootProject.projectDir, '${projectDir}')\n`, + ); }); }); describe('makeSettingsPatchWithScopedPackage', () => { it('should build a patch function', () => { - expect(Object.prototype.toString( - makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig) - )).toBe('[object Object]'); + expect( + Object.prototype.toString( + makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig), + ), + ).toBe('[object Object]'); }); it('should make a correct patch', () => { const projectDir = path.relative( path.dirname(projectConfig.settingsGradlePath), - scopedDependencyConfig.sourceDir + scopedDependencyConfig.sourceDir, ); - const {patch} = makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig); + const {patch} = makeSettingsPatch( + scopedName, + scopedDependencyConfig, + projectConfig, + ); - expect(patch) - .toBe( - `include ':${normalizedScopedName}'\n` + + expect(patch).toBe( + `include ':${normalizedScopedName}'\n` + `project(':${normalizedScopedName}').projectDir = ` + - `new File(rootProject.projectDir, '${projectDir}')\n` - ); + `new File(rootProject.projectDir, '${projectDir}')\n`, + ); }); }); diff --git a/local-cli/link/__tests__/android/makeStringsPatch.spec.js b/local-cli/link/__tests__/android/makeStringsPatch.spec.js index 3015f15b340..f8b6c07ed94 100644 --- a/local-cli/link/__tests__/android/makeStringsPatch.spec.js +++ b/local-cli/link/__tests__/android/makeStringsPatch.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -17,8 +18,9 @@ describe('makeStringsPatch', () => { keyA: 'valueA', }; - expect(makeStringsPatch(params, 'module').patch) - .toContain('valueA'); + expect(makeStringsPatch(params, 'module').patch).toContain( + 'valueA', + ); }); it('should export an empty patch if no params given', () => { diff --git a/local-cli/link/__tests__/android/normalizeProjectName.spec.js b/local-cli/link/__tests__/android/normalizeProjectName.spec.js index e4e236aca42..2a69e2e0984 100644 --- a/local-cli/link/__tests__/android/normalizeProjectName.spec.js +++ b/local-cli/link/__tests__/android/normalizeProjectName.spec.js @@ -6,21 +6,20 @@ * * All rights reserved. * + * @format * @emails oncall+javascript_foundation */ - 'use strict'; +'use strict'; const normalizeProjectName = require('../../android/patches/normalizeProjectName'); const name = 'test'; const scopedName = '@scoped/test'; - describe('normalizeProjectName', () => { +describe('normalizeProjectName', () => { it('should replace slashes with underscores', () => { - expect(normalizeProjectName(name)) - .toBe('test'); - expect(normalizeProjectName(scopedName)) - .toBe('@scoped_test'); + expect(normalizeProjectName(name)).toBe('test'); + expect(normalizeProjectName(scopedName)).toBe('@scoped_test'); }); }); diff --git a/local-cli/link/__tests__/getDependencyConfig.spec.js b/local-cli/link/__tests__/getDependencyConfig.spec.js index 30db06d537f..dda764853ee 100644 --- a/local-cli/link/__tests__/getDependencyConfig.spec.js +++ b/local-cli/link/__tests__/getDependencyConfig.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -13,7 +14,7 @@ const getDependencyConfig = require('../getDependencyConfig'); const sinon = require('sinon'); describe('getDependencyConfig', () => { - it('should return an array of dependencies\' rnpm config', () => { + it("should return an array of dependencies' rnpm config", () => { const config = { getDependencyConfig: sinon.stub(), }; diff --git a/local-cli/link/__tests__/getProjectDependencies.spec.js b/local-cli/link/__tests__/getProjectDependencies.spec.js index fc7dd3cd91d..974f128191e 100644 --- a/local-cli/link/__tests__/getProjectDependencies.spec.js +++ b/local-cli/link/__tests__/getProjectDependencies.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -17,10 +18,9 @@ describe('getProjectDependencies', () => { jest.resetModules(); }); it('should return an array of project dependencies', () => { - jest.setMock( - path.join(process.cwd(), './package.json'), - { dependencies: { lodash: '^6.0.0', 'react-native': '^16.0.0' }} - ); + jest.setMock(path.join(process.cwd(), './package.json'), { + dependencies: {lodash: '^6.0.0', 'react-native': '^16.0.0'}, + }); expect(getProjectDependencies()).toEqual(['lodash']); }); diff --git a/local-cli/link/__tests__/groupFilesByType.spec.js b/local-cli/link/__tests__/groupFilesByType.spec.js index a96ff6e24d3..d4c4e959886 100644 --- a/local-cli/link/__tests__/groupFilesByType.spec.js +++ b/local-cli/link/__tests__/groupFilesByType.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -12,21 +13,13 @@ const groupFilesByType = require('../groupFilesByType'); describe('groupFilesByType', () => { - it('should group files by its type', () => { - const fonts = [ - 'fonts/a.ttf', - 'fonts/b.ttf', - ]; - const images = [ - 'images/a.jpg', - 'images/c.jpeg', - ]; + const fonts = ['fonts/a.ttf', 'fonts/b.ttf']; + const images = ['images/a.jpg', 'images/c.jpeg']; const groupedFiles = groupFilesByType(fonts.concat(images)); expect(groupedFiles.font).toEqual(fonts); expect(groupedFiles.image).toEqual(images); }); - }); diff --git a/local-cli/link/__tests__/ios/addFileToProject.spec.js b/local-cli/link/__tests__/ios/addFileToProject.spec.js index ca32c867090..1b6d3ab6954 100644 --- a/local-cli/link/__tests__/ios/addFileToProject.spec.js +++ b/local-cli/link/__tests__/ios/addFileToProject.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -15,7 +16,7 @@ const addFileToProject = require('../../ios/addFileToProject'); const _ = require('lodash'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::addFileToProject', () => { @@ -27,8 +28,9 @@ describe('ios::addFileToProject', () => { expect( _.includes( Object.keys(project.pbxFileReferenceSection()), - addFileToProject(project, '../../__fixtures__/linearGradient.pbxproj').fileRef - ) + addFileToProject(project, '../../__fixtures__/linearGradient.pbxproj') + .fileRef, + ), ).toBeTruthy(); }); }); diff --git a/local-cli/link/__tests__/ios/addProjectToLibraries.spec.js b/local-cli/link/__tests__/ios/addProjectToLibraries.spec.js index 4d20621e0af..6caac1636a6 100644 --- a/local-cli/link/__tests__/ios/addProjectToLibraries.spec.js +++ b/local-cli/link/__tests__/ios/addProjectToLibraries.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -16,7 +17,7 @@ const addProjectToLibraries = require('../../ios/addProjectToLibraries'); const last = require('lodash').last; const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::addProjectToLibraries', () => { diff --git a/local-cli/link/__tests__/ios/addSharedLibraries.spec.js b/local-cli/link/__tests__/ios/addSharedLibraries.spec.js index 36343a89ce6..4a645bc3fe3 100644 --- a/local-cli/link/__tests__/ios/addSharedLibraries.spec.js +++ b/local-cli/link/__tests__/ios/addSharedLibraries.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -15,11 +16,10 @@ const addSharedLibraries = require('../../ios/addSharedLibraries'); const getGroup = require('../../ios/getGroup'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::addSharedLibraries', () => { - beforeEach(() => { project.parseSync(); }); @@ -48,5 +48,4 @@ describe('ios::addSharedLibraries', () => { const frameworksGroup = getGroup(project, 'Frameworks'); expect(frameworksGroup.children.length).toEqual(1); }); - }); diff --git a/local-cli/link/__tests__/ios/createGroup.spec.js b/local-cli/link/__tests__/ios/createGroup.spec.js index b3fbf67a1a1..cee24213f62 100644 --- a/local-cli/link/__tests__/ios/createGroup.spec.js +++ b/local-cli/link/__tests__/ios/createGroup.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -16,7 +17,7 @@ const getGroup = require('../../ios/getGroup'); const last = require('lodash').last; const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::createGroup', () => { @@ -33,18 +34,14 @@ describe('ios::createGroup', () => { const createdGroup = createGroup(project, 'Resources'); const mainGroup = getGroup(project); - expect( - last(mainGroup.children).comment - ).toBe(createdGroup.name); + expect(last(mainGroup.children).comment).toBe(createdGroup.name); }); it('should create a nested group with given path', () => { const createdGroup = createGroup(project, 'NewGroup/NewNestedGroup'); const outerGroup = getGroup(project, 'NewGroup'); - expect( - last(outerGroup.children).comment - ).toBe(createdGroup.name); + expect(last(outerGroup.children).comment).toBe(createdGroup.name); }); it('should-not create already created groups', () => { @@ -53,10 +50,7 @@ describe('ios::createGroup', () => { const mainGroup = getGroup(project); expect( - mainGroup - .children - .filter(group => group.comment === 'Libraries') - .length + mainGroup.children.filter(group => group.comment === 'Libraries').length, ).toBe(1); expect(last(outerGroup.children).comment).toBe(createdGroup.name); }); diff --git a/local-cli/link/__tests__/ios/getBuildProperty.spec.js b/local-cli/link/__tests__/ios/getBuildProperty.spec.js index 831944bbb94..991c43dfe8f 100644 --- a/local-cli/link/__tests__/ios/getBuildProperty.spec.js +++ b/local-cli/link/__tests__/ios/getBuildProperty.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const path = require('path'); const getBuildProperty = require('../../ios/getBuildProperty'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getBuildProperty', () => { diff --git a/local-cli/link/__tests__/ios/getGroup.spec.js b/local-cli/link/__tests__/ios/getGroup.spec.js index f46cc31ebd7..eb6716af7d4 100644 --- a/local-cli/link/__tests__/ios/getGroup.spec.js +++ b/local-cli/link/__tests__/ios/getGroup.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const getGroup = require('../../ios/getGroup'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getGroup', () => { diff --git a/local-cli/link/__tests__/ios/getHeaderSearchPath.spec.js b/local-cli/link/__tests__/ios/getHeaderSearchPath.spec.js index 7e96a20b0ed..bc1669e59d8 100644 --- a/local-cli/link/__tests__/ios/getHeaderSearchPath.spec.js +++ b/local-cli/link/__tests__/ios/getHeaderSearchPath.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -20,14 +21,19 @@ describe('ios::getHeaderSearchPath', () => { */ it('should return correct path when all headers are in root folder', () => { const files = [ - path.join('react-native-project', 'node_modules', 'package', 'Gradient.h'), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'Gradient.h', + ), path.join('react-native-project', 'node_modules', 'package', 'Manager.h'), ]; const searchPath = getHeaderSearchPath(SRC_DIR, files); expect(searchPath).toBe( - `"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"` + `"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"`, ); }); @@ -36,14 +42,30 @@ describe('ios::getHeaderSearchPath', () => { */ it('should return correct path when headers are in multiple folders', () => { const files = [ - path.join('react-native-project', 'node_modules', 'package', 'src', 'folderA', 'Gradient.h'), - path.join('react-native-project', 'node_modules', 'package', 'src', 'folderB', 'Manager.h'), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'src', + 'folderA', + 'Gradient.h', + ), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'src', + 'folderB', + 'Manager.h', + ), ]; const searchPath = getHeaderSearchPath(SRC_DIR, files); expect(searchPath).toBe( - `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(path.sep)}/**"` + `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join( + path.sep, + )}/**"`, ); }); @@ -52,15 +74,37 @@ describe('ios::getHeaderSearchPath', () => { */ it('should return correct path when headers are in root and nested folders', () => { const files = [ - path.join('react-native-project', 'node_modules', 'package', 'src', 'folderA', 'Gradient.h'), - path.join('react-native-project', 'node_modules', 'package', 'src', 'folderB', 'Manager.h'), - path.join('react-native-project', 'node_modules', 'package', 'src', 'Manager.h'), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'src', + 'folderA', + 'Gradient.h', + ), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'src', + 'folderB', + 'Manager.h', + ), + path.join( + 'react-native-project', + 'node_modules', + 'package', + 'src', + 'Manager.h', + ), ]; const searchPath = getHeaderSearchPath(SRC_DIR, files); expect(searchPath).toBe( - `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(path.sep)}/**"` + `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join( + path.sep, + )}/**"`, ); }); }); diff --git a/local-cli/link/__tests__/ios/getHeadersInFolder.spec.js b/local-cli/link/__tests__/ios/getHeadersInFolder.spec.js index ff106865791..1793755d979 100644 --- a/local-cli/link/__tests__/ios/getHeadersInFolder.spec.js +++ b/local-cli/link/__tests__/ios/getHeadersInFolder.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ diff --git a/local-cli/link/__tests__/ios/getPlist.spec.js b/local-cli/link/__tests__/ios/getPlist.spec.js index 156320079b8..10e1315dd98 100644 --- a/local-cli/link/__tests__/ios/getPlist.spec.js +++ b/local-cli/link/__tests__/ios/getPlist.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const getPlist = require('../../ios/getPlist'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getPlist', () => { diff --git a/local-cli/link/__tests__/ios/getPlistPath.spec.js b/local-cli/link/__tests__/ios/getPlistPath.spec.js index bf7c922edc8..9cbce096ea1 100644 --- a/local-cli/link/__tests__/ios/getPlistPath.spec.js +++ b/local-cli/link/__tests__/ios/getPlistPath.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const getPlistPath = require('../../ios/getPlistPath'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getPlistPath', () => { diff --git a/local-cli/link/__tests__/ios/getProducts.spec.js b/local-cli/link/__tests__/ios/getProducts.spec.js index 26bee69fca0..88c7515d767 100644 --- a/local-cli/link/__tests__/ios/getProducts.spec.js +++ b/local-cli/link/__tests__/ios/getProducts.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const getProducts = require('../../ios/getProducts'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getProducts', () => { diff --git a/local-cli/link/__tests__/ios/getTargets.spec.js b/local-cli/link/__tests__/ios/getTargets.spec.js index 99f3f370215..7acf9df43ed 100644 --- a/local-cli/link/__tests__/ios/getTargets.spec.js +++ b/local-cli/link/__tests__/ios/getTargets.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const getTargets = require('../../ios/getTargets'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::getTargets', () => { diff --git a/local-cli/link/__tests__/ios/hasLibraryImported.spec.js b/local-cli/link/__tests__/ios/hasLibraryImported.spec.js index 6d9d1723f90..a74e7b59388 100644 --- a/local-cli/link/__tests__/ios/hasLibraryImported.spec.js +++ b/local-cli/link/__tests__/ios/hasLibraryImported.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const hasLibraryImported = require('../../ios/hasLibraryImported'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::hasLibraryImported', () => { diff --git a/local-cli/link/__tests__/ios/isInstalled.spec.js b/local-cli/link/__tests__/ios/isInstalled.spec.js index bc291d79df3..3946677c353 100644 --- a/local-cli/link/__tests__/ios/isInstalled.spec.js +++ b/local-cli/link/__tests__/ios/isInstalled.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -19,18 +20,20 @@ const baseProjectConfig = { describe('ios::isInstalled', () => { it('should return true when .xcodeproj in Libraries', () => { - const dependencyConfig = { projectName: 'React.xcodeproj' }; + const dependencyConfig = {projectName: 'React.xcodeproj'}; expect(isInstalled(baseProjectConfig, dependencyConfig)).toBeTruthy(); }); it('should return false when .xcodeproj not in Libraries', () => { - const dependencyConfig = { projectName: 'Missing.xcodeproj' }; + const dependencyConfig = {projectName: 'Missing.xcodeproj'}; expect(isInstalled(baseProjectConfig, dependencyConfig)).toBeFalsy(); }); it('should return false when `LibraryFolder` is missing', () => { - const dependencyConfig = { projectName: 'React.xcodeproj' }; - const projectConfig = Object.assign({}, baseProjectConfig, { libraryFolder: 'Missing' }); + const dependencyConfig = {projectName: 'React.xcodeproj'}; + const projectConfig = Object.assign({}, baseProjectConfig, { + libraryFolder: 'Missing', + }); expect(isInstalled(projectConfig, dependencyConfig)).toBeFalsy(); }); }); diff --git a/local-cli/link/__tests__/ios/mapHeaderSearchPaths.spec.js b/local-cli/link/__tests__/ios/mapHeaderSearchPaths.spec.js index e834b32da8c..785e6bdd73f 100644 --- a/local-cli/link/__tests__/ios/mapHeaderSearchPaths.spec.js +++ b/local-cli/link/__tests__/ios/mapHeaderSearchPaths.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ const mapHeaderSearchPaths = require('../../ios/mapHeaderSearchPaths'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::mapHeaderSearchPaths', () => { diff --git a/local-cli/link/__tests__/ios/removeProjectFromLibraries.js b/local-cli/link/__tests__/ios/removeProjectFromLibraries.js index 262d61b11e8..2c882be27d5 100644 --- a/local-cli/link/__tests__/ios/removeProjectFromLibraries.js +++ b/local-cli/link/__tests__/ios/removeProjectFromLibraries.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -17,7 +18,7 @@ const last = require('lodash').last; const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::removeProjectFromLibraries', () => { @@ -26,7 +27,7 @@ describe('ios::removeProjectFromLibraries', () => { addProjectToLibraries( project.pbxGroupByName('Libraries'), - new PbxFile('fakePath') + new PbxFile('fakePath'), ); }); diff --git a/local-cli/link/__tests__/ios/removeProjectFromProject.spec.js b/local-cli/link/__tests__/ios/removeProjectFromProject.spec.js index 54a3e07cd7a..16dc3b374e4 100644 --- a/local-cli/link/__tests__/ios/removeProjectFromProject.spec.js +++ b/local-cli/link/__tests__/ios/removeProjectFromProject.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -16,7 +17,7 @@ const removeProjectFromProject = require('../../ios/removeProjectFromProject'); const path = require('path'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); const filePath = '../../__fixtures__/linearGradient.pbxproj'; @@ -27,8 +28,9 @@ describe('ios::addFileToProject', () => { }); it('should return removed file', () => { - expect(removeProjectFromProject(project, filePath) instanceof pbxFile) - .toBeTruthy(); + expect( + removeProjectFromProject(project, filePath) instanceof pbxFile, + ).toBeTruthy(); }); it('should remove file from a project', () => { diff --git a/local-cli/link/__tests__/ios/removeSharedLibrary.spec.js b/local-cli/link/__tests__/ios/removeSharedLibrary.spec.js index 601f0f7aa57..ee69b5c6adf 100644 --- a/local-cli/link/__tests__/ios/removeSharedLibrary.spec.js +++ b/local-cli/link/__tests__/ios/removeSharedLibrary.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -16,11 +17,10 @@ const removeSharedLibraries = require('../../ios/removeSharedLibraries'); const getGroup = require('../../ios/getGroup'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj') + path.join(__dirname, '../../__fixtures__/project.pbxproj'), ); describe('ios::removeSharedLibraries', () => { - beforeEach(() => { project.parseSync(); addSharedLibraries(project, ['libc++.tbd', 'libz.tbd']); @@ -40,5 +40,4 @@ describe('ios::removeSharedLibraries', () => { const frameworksGroup = getGroup(project, 'Frameworks'); expect(frameworksGroup.children.length).toEqual(2); }); - }); diff --git a/local-cli/link/__tests__/ios/writePlist.spec.js b/local-cli/link/__tests__/ios/writePlist.spec.js index 7e32b72aacc..40a7e549255 100644 --- a/local-cli/link/__tests__/ios/writePlist.spec.js +++ b/local-cli/link/__tests__/ios/writePlist.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,7 +15,7 @@ jest.mock('fs'); let plistPath = null; jest.mock('../../ios/getPlistPath', () => () => plistPath); -const { readFileSync } = require.requireActual('fs'); +const {readFileSync} = require.requireActual('fs'); const fs = require('fs'); const xcode = require('xcode'); @@ -33,9 +34,7 @@ const project = xcode.project('/Basic/project.pbxproj'); const plist = { CFBundleDevelopmentRegion: 'en', - UISupportedInterfaceOrientations: [ - 'UIInterfaceOrientationPortrait' - ] + UISupportedInterfaceOrientations: ['UIInterfaceOrientationPortrait'], }; describe('ios::writePlist', () => { diff --git a/local-cli/link/__tests__/link.spec.js b/local-cli/link/__tests__/link.spec.js index 5ff3ab73a19..7e658eb7d20 100644 --- a/local-cli/link/__tests__/link.spec.js +++ b/local-cli/link/__tests__/link.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -12,10 +13,7 @@ const sinon = require('sinon'); const log = require('npmlog'); const path = require('path'); -jest.setMock( - 'chalk', - { grey: (str) => str, } -); +jest.setMock('chalk', {grey: str => str}); describe('link', () => { beforeEach(() => { @@ -24,7 +22,7 @@ describe('link', () => { log.level = 'silent'; }); - it('should reject when run in a folder without package.json', (done) => { + it('should reject when run in a folder without package.json', done => { const config = { getProjectConfig: () => { throw new Error('No package.json found'); @@ -35,77 +33,65 @@ describe('link', () => { link([], config).catch(() => done()); }); - it('should accept a name of a dependency to link', (done) => { + it('should accept a name of a dependency to link', done => { const config = { getPlatformConfig: () => ({ios: {}, android: {}}), - getProjectConfig: () => ({ assets: [] }), - getDependencyConfig: sinon.stub().returns({ assets: [], commands: {} }), + getProjectConfig: () => ({assets: []}), + getDependencyConfig: sinon.stub().returns({assets: [], commands: {}}), }; const link = require('../link').func; link(['react-native-gradient'], config).then(() => { expect( - config.getDependencyConfig.calledWith('react-native-gradient') + config.getDependencyConfig.calledWith('react-native-gradient'), ).toBeTruthy(); done(); }); }); - it('should read dependencies from package.json when name not provided', (done) => { + it('should read dependencies from package.json when name not provided', done => { const config = { getPlatformConfig: () => ({ios: {}, android: {}}), - getProjectConfig: () => ({ assets: [] }), - getDependencyConfig: sinon.stub().returns({ assets: [], commands: {} }), + getProjectConfig: () => ({assets: []}), + getDependencyConfig: sinon.stub().returns({assets: [], commands: {}}), }; - jest.setMock( - path.join(process.cwd(), 'package.json'), - { - dependencies: { - 'react-native-test': '*', - }, - } - ); + jest.setMock(path.join(process.cwd(), 'package.json'), { + dependencies: { + 'react-native-test': '*', + }, + }); const link = require('../link').func; link([], config).then(() => { expect( - config.getDependencyConfig.calledWith('react-native-test') + config.getDependencyConfig.calledWith('react-native-test'), ).toBeTruthy(); done(); }); }); - it('should register native module when android/ios projects are present', (done) => { + it('should register native module when android/ios projects are present', done => { const registerNativeModule = sinon.stub(); const dependencyConfig = {android: {}, ios: {}, assets: [], commands: {}}; const androidLinkConfig = require('../android'); const iosLinkConfig = require('../ios'); const config = { - getPlatformConfig: () => ({ios: { linkConfig: iosLinkConfig }, android: { linkConfig: androidLinkConfig }}), + getPlatformConfig: () => ({ + ios: {linkConfig: iosLinkConfig}, + android: {linkConfig: androidLinkConfig}, + }), getProjectConfig: () => ({android: {}, ios: {}, assets: []}), getDependencyConfig: sinon.stub().returns(dependencyConfig), }; - jest.setMock( - '../android/isInstalled.js', - sinon.stub().returns(false) - ); + jest.setMock('../android/isInstalled.js', sinon.stub().returns(false)); - jest.setMock( - '../android/registerNativeModule.js', - registerNativeModule - ); + jest.setMock('../android/registerNativeModule.js', registerNativeModule); - jest.setMock( - '../ios/isInstalled.js', - sinon.stub().returns(false) - ); + jest.setMock('../ios/isInstalled.js', sinon.stub().returns(false)); - jest.setMock( - '../ios/registerNativeModule.js', - registerNativeModule - ); + jest.setMock('../ios/registerNativeModule.js', registerNativeModule); const link = require('../link').func; @@ -115,34 +101,22 @@ describe('link', () => { }); }); - it('should not register modules when they are already installed', (done) => { + it('should not register modules when they are already installed', done => { const registerNativeModule = sinon.stub(); const dependencyConfig = {ios: {}, android: {}, assets: [], commands: {}}; const config = { getPlatformConfig: () => ({ios: {}, android: {}}), - getProjectConfig: () => ({ ios: {}, android: {}, assets: [] }), + getProjectConfig: () => ({ios: {}, android: {}, assets: []}), getDependencyConfig: sinon.stub().returns(dependencyConfig), }; - jest.setMock( - '../ios/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true)); - jest.setMock( - '../android/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../android/isInstalled.js', sinon.stub().returns(true)); - jest.setMock( - '../ios/registerNativeModule.js', - registerNativeModule - ); + jest.setMock('../ios/registerNativeModule.js', registerNativeModule); - jest.setMock( - '../android/registerNativeModule.js', - registerNativeModule - ); + jest.setMock('../android/registerNativeModule.js', registerNativeModule); const link = require('../link').func; @@ -152,25 +126,32 @@ describe('link', () => { }); }); - it('should register native modules for plugins', (done) => { + it('should register native modules for plugins', done => { const registerNativeModule = sinon.stub(); - const dependencyConfig = {ios: {}, android: {}, test: {}, assets: [], commands: {}}; - const linkPluginConfig = { isInstalled: () => false, register: registerNativeModule }; + const dependencyConfig = { + ios: {}, + android: {}, + test: {}, + assets: [], + commands: {}, + }; + const linkPluginConfig = { + isInstalled: () => false, + register: registerNativeModule, + }; const config = { - getPlatformConfig: () => ({ ios: {}, android: {}, test: { linkConfig: () => linkPluginConfig }}), - getProjectConfig: () => ({ ios: {}, android: {}, test: {}, assets: [] }), + getPlatformConfig: () => ({ + ios: {}, + android: {}, + test: {linkConfig: () => linkPluginConfig}, + }), + getProjectConfig: () => ({ios: {}, android: {}, test: {}, assets: []}), getDependencyConfig: sinon.stub().returns(dependencyConfig), }; - jest.setMock( - '../ios/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true)); - jest.setMock( - '../android/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../android/isInstalled.js', sinon.stub().returns(true)); const link = require('../link').func; @@ -180,25 +161,32 @@ describe('link', () => { }); }); - it('should not register native modules for plugins when already installed', (done) => { + it('should not register native modules for plugins when already installed', done => { const registerNativeModule = sinon.stub(); - const dependencyConfig = {ios: {}, android: {}, test: {}, assets: [], commands: {}}; - const linkPluginConfig = { isInstalled: () => true, register: registerNativeModule}; + const dependencyConfig = { + ios: {}, + android: {}, + test: {}, + assets: [], + commands: {}, + }; + const linkPluginConfig = { + isInstalled: () => true, + register: registerNativeModule, + }; const config = { - getPlatformConfig: () => ({ ios: {}, android: {}, test: { linkConfig: () => linkPluginConfig }}), - getProjectConfig: () => ({ ios: {}, android: {}, test: {}, assets: [] }), + getPlatformConfig: () => ({ + ios: {}, + android: {}, + test: {linkConfig: () => linkPluginConfig}, + }), + getProjectConfig: () => ({ios: {}, android: {}, test: {}, assets: []}), getDependencyConfig: sinon.stub().returns(dependencyConfig), }; - jest.setMock( - '../ios/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true)); - jest.setMock( - '../android/isInstalled.js', - sinon.stub().returns(true) - ); + jest.setMock('../android/isInstalled.js', sinon.stub().returns(true)); const link = require('../link').func; @@ -208,27 +196,23 @@ describe('link', () => { }); }); - it('should run prelink and postlink commands at the appropriate times', (done) => { + it('should run prelink and postlink commands at the appropriate times', done => { const registerNativeModule = sinon.stub(); const prelink = sinon.stub().yieldsAsync(); const postlink = sinon.stub().yieldsAsync(); - jest.setMock( - '../ios/registerNativeModule.js', - registerNativeModule - ); + jest.setMock('../ios/registerNativeModule.js', registerNativeModule); - jest.setMock( - '../ios/isInstalled.js', - sinon.stub().returns(false) - ); + jest.setMock('../ios/isInstalled.js', sinon.stub().returns(false)); const linkConfig = require('../ios'); const config = { - getPlatformConfig: () => ({ ios: { linkConfig: linkConfig }}), - getProjectConfig: () => ({ ios: {}, assets: [] }), + getPlatformConfig: () => ({ios: {linkConfig: linkConfig}}), + getProjectConfig: () => ({ios: {}, assets: []}), getDependencyConfig: sinon.stub().returns({ - ios: {}, assets: [], commands: { prelink, postlink }, + ios: {}, + assets: [], + commands: {prelink, postlink}, }), }; @@ -241,21 +225,18 @@ describe('link', () => { }); }); - it('should copy assets from both project and dependencies projects', (done) => { + it('should copy assets from both project and dependencies projects', done => { const dependencyAssets = ['Fonts/Font.ttf']; const dependencyConfig = {assets: dependencyAssets, ios: {}, commands: {}}; const projectAssets = ['Fonts/FontC.ttf']; const copyAssets = sinon.stub(); - jest.setMock( - '../ios/copyAssets.js', - copyAssets - ); + jest.setMock('../ios/copyAssets.js', copyAssets); const linkConfig = require('../ios'); const config = { - getPlatformConfig: () => ({ ios: { linkConfig: linkConfig } }), - getProjectConfig: () => ({ ios: {}, assets: projectAssets }), + getPlatformConfig: () => ({ios: {linkConfig: linkConfig}}), + getProjectConfig: () => ({ios: {}, assets: projectAssets}), getDependencyConfig: sinon.stub().returns(dependencyConfig), }; @@ -264,7 +245,7 @@ describe('link', () => { link(['react-native-blur'], config).then(() => { expect(copyAssets.calledOnce).toBeTruthy(); expect(copyAssets.getCall(0).args[0]).toEqual( - projectAssets.concat(dependencyAssets) + projectAssets.concat(dependencyAssets), ); done(); }); diff --git a/local-cli/link/__tests__/pods/findLineToAddPod.spec.js b/local-cli/link/__tests__/pods/findLineToAddPod.spec.js index e065fd406ff..e0b179a8f94 100644 --- a/local-cli/link/__tests__/pods/findLineToAddPod.spec.js +++ b/local-cli/link/__tests__/pods/findLineToAddPod.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -19,21 +20,31 @@ const LINE_AFTER_TARGET_IN_TEST_PODFILE = 4; describe('pods::findLineToAddPod', () => { it('returns null if file is not Podfile', () => { const podfile = readPodfile(path.join(PODFILES_PATH, '../Info.plist')); - expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toBeNull(); + expect( + findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toBeNull(); }); it('returns correct line number for Simple Podfile', () => { const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple')); - expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 7, indentation: 2 }); + expect( + findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toEqual({line: 7, indentation: 2}); }); it('returns correct line number for Podfile with target', () => { const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithTarget')); - expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 21, indentation: 2 }); + expect( + findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toEqual({line: 21, indentation: 2}); }); it('returns correct line number for Podfile with function', () => { - const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithFunction')); - expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 26, indentation: 2 }); + const podfile = readPodfile( + path.join(PODFILES_PATH, 'PodfileWithFunction'), + ); + expect( + findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toEqual({line: 26, indentation: 2}); }); }); diff --git a/local-cli/link/__tests__/pods/findMarkedLinesInPodfile.spec.js b/local-cli/link/__tests__/pods/findMarkedLinesInPodfile.spec.js index f3b6880949f..7dd2b77af93 100644 --- a/local-cli/link/__tests__/pods/findMarkedLinesInPodfile.spec.js +++ b/local-cli/link/__tests__/pods/findMarkedLinesInPodfile.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -24,12 +25,19 @@ describe('pods::findMarkedLinesInPodfile', () => { it('returns empty array for Simple Podfile', () => { const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple')); - expect(findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual([]); + expect( + findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toEqual([]); }); it('returns correct line numbers for Podfile with marker', () => { const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithMarkers')); - const expectedObject = [{ line: 18, indentation: 2 }, { line: 31, indentation: 4 }]; - expect(findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual(expectedObject); + const expectedObject = [ + {line: 18, indentation: 2}, + {line: 31, indentation: 4}, + ]; + expect( + findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + ).toEqual(expectedObject); }); }); diff --git a/local-cli/link/__tests__/pods/findPodTargetLine.spec.js b/local-cli/link/__tests__/pods/findPodTargetLine.spec.js index d64a2513c7c..04b142856f8 100644 --- a/local-cli/link/__tests__/pods/findPodTargetLine.spec.js +++ b/local-cli/link/__tests__/pods/findPodTargetLine.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ diff --git a/local-cli/link/__tests__/pods/isInstalled.spec.js b/local-cli/link/__tests__/pods/isInstalled.spec.js index abda0fbe32d..ba9b3f03753 100644 --- a/local-cli/link/__tests__/pods/isInstalled.spec.js +++ b/local-cli/link/__tests__/pods/isInstalled.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -16,26 +17,26 @@ const PODFILES_PATH = path.join(__dirname, '../../__fixtures__/pods'); describe('pods::isInstalled', () => { it('returns false if pod is missing', () => { - const project = { podfile: path.join(PODFILES_PATH, 'PodfileSimple') }; - const podspecName = { podspec: 'NotExisting' }; + const project = {podfile: path.join(PODFILES_PATH, 'PodfileSimple')}; + const podspecName = {podspec: 'NotExisting'}; expect(isInstalled(project, podspecName)).toBe(false); }); it('returns true for existing pod with version number', () => { - const project = { podfile: path.join(PODFILES_PATH, 'PodfileSimple') }; - const podspecName = { podspec: 'TestPod' }; + const project = {podfile: path.join(PODFILES_PATH, 'PodfileSimple')}; + const podspecName = {podspec: 'TestPod'}; expect(isInstalled(project, podspecName)).toBe(true); }); it('returns true for existing pod with path', () => { - const project = { podfile: path.join(PODFILES_PATH, 'PodfileWithTarget') }; - const podspecName = { podspec: 'Yoga' }; + const project = {podfile: path.join(PODFILES_PATH, 'PodfileWithTarget')}; + const podspecName = {podspec: 'Yoga'}; expect(isInstalled(project, podspecName)).toBe(true); }); it('returns true for existing pod with multiline definition', () => { - const project = { podfile: path.join(PODFILES_PATH, 'PodfileWithFunction') }; - const podspecName = { podspec: 'React' }; + const project = {podfile: path.join(PODFILES_PATH, 'PodfileWithFunction')}; + const podspecName = {podspec: 'React'}; expect(isInstalled(project, podspecName)).toBe(true); }); }); diff --git a/local-cli/link/__tests__/pods/removePodEntry.spec.js b/local-cli/link/__tests__/pods/removePodEntry.spec.js index 5c2f4a951f0..576664970ba 100644 --- a/local-cli/link/__tests__/pods/removePodEntry.spec.js +++ b/local-cli/link/__tests__/pods/removePodEntry.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -17,21 +18,25 @@ const PODFILES_PATH = path.join(__dirname, '../../__fixtures__/pods'); describe('pods::removePodEntry', () => { it('should remove one line from Podfile with TestPod', () => { - const { podfileContent, podLinesCount } = readTestPodFile('PodfileSimple'); + const {podfileContent, podLinesCount} = readTestPodFile('PodfileSimple'); const podFileWithRemoved = removePodEntry(podfileContent, 'TestPod'); const newLineCount = podFileWithRemoved.split('\n').length; expect(newLineCount).toBe(podLinesCount - 1); }); it('should remove one line from Podfile with Yoga', () => { - const { podfileContent, podLinesCount } = readTestPodFile('PodfileWithTarget'); + const {podfileContent, podLinesCount} = readTestPodFile( + 'PodfileWithTarget', + ); const podFileWithRemoved = removePodEntry(podfileContent, 'Yoga'); const newLineCount = podFileWithRemoved.split('\n').length; expect(newLineCount).toBe(podLinesCount - 1); }); it('should remove whole reference to React pod from Podfile', () => { - const { podfileContent, podLinesCount } = readTestPodFile('PodfileWithTarget'); + const {podfileContent, podLinesCount} = readTestPodFile( + 'PodfileWithTarget', + ); const podFileWithRemoved = removePodEntry(podfileContent, 'React'); const newLineCount = podFileWithRemoved.split('\n').length; expect(newLineCount).toBe(podLinesCount - 9); @@ -40,5 +45,8 @@ describe('pods::removePodEntry', () => { function readTestPodFile(fileName) { const podfileLines = readPodfile(path.join(PODFILES_PATH, fileName)); - return { podfileContent: podfileLines.join('\n'), podLinesCount: podfileLines.length }; + return { + podfileContent: podfileLines.join('\n'), + podLinesCount: podfileLines.length, + }; } diff --git a/local-cli/link/__tests__/promiseWaterfall.spec.js b/local-cli/link/__tests__/promiseWaterfall.spec.js index d34aa650217..3f9adc55a2c 100644 --- a/local-cli/link/__tests__/promiseWaterfall.spec.js +++ b/local-cli/link/__tests__/promiseWaterfall.spec.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -13,8 +14,7 @@ const sinon = require('sinon'); const promiseWaterfall = require('../promiseWaterfall'); describe('promiseWaterfall', () => { - - it('should run promises in a sequence', (done) => { + it('should run promises in a sequence', done => { const tasks = [sinon.stub(), sinon.stub()]; promiseWaterfall(tasks).then(() => { @@ -23,7 +23,7 @@ describe('promiseWaterfall', () => { }); }); - it('should resolve with last promise value', (done) => { + it('should resolve with last promise value', done => { const tasks = [sinon.stub().returns(1), sinon.stub().returns(2)]; promiseWaterfall(tasks).then(value => { @@ -32,7 +32,7 @@ describe('promiseWaterfall', () => { }); }); - it('should stop the sequence when one of promises is rejected', (done) => { + it('should stop the sequence when one of promises is rejected', done => { const error = new Error(); const tasks = [sinon.stub().throws(error), sinon.stub().returns(2)]; @@ -42,5 +42,4 @@ describe('promiseWaterfall', () => { done(); }); }); - }); diff --git a/local-cli/link/android/copyAssets.js b/local-cli/link/android/copyAssets.js index f4bd67ff6a1..dbaeaa24e93 100644 --- a/local-cli/link/android/copyAssets.js +++ b/local-cli/link/android/copyAssets.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs-extra'); @@ -19,6 +21,9 @@ module.exports = function copyAssetsAndroid(files, project) { const assets = groupFilesByType(files); (assets.font || []).forEach(asset => - fs.copySync(asset, path.join(project.assetsPath, 'fonts', path.basename(asset))) + fs.copySync( + asset, + path.join(project.assetsPath, 'fonts', path.basename(asset)), + ), ); }; diff --git a/local-cli/link/android/fs.js b/local-cli/link/android/fs.js index 9ace2aba924..51ee62136b4 100644 --- a/local-cli/link/android/fs.js +++ b/local-cli/link/android/fs.js @@ -3,13 +3,15 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs-extra'); -exports.readFile = (file) => - () => fs.readFileSync(file, 'utf8'); +exports.readFile = file => () => fs.readFileSync(file, 'utf8'); -exports.writeFile = (file, content) => content ? - fs.writeFileSync(file, content, 'utf8') : - (c) => fs.writeFileSync(file, c, 'utf8'); +exports.writeFile = (file, content) => + content + ? fs.writeFileSync(file, content, 'utf8') + : c => fs.writeFileSync(file, c, 'utf8'); diff --git a/local-cli/link/android/index.js b/local-cli/link/android/index.js index 986ec59450b..3eacc417502 100644 --- a/local-cli/link/android/index.js +++ b/local-cli/link/android/index.js @@ -1,9 +1,11 @@ +/** @format */ + module.exports = function() { return { isInstalled: require('./isInstalled'), register: require('./registerNativeModule'), unregister: require('./unregisterNativeModule'), copyAssets: require('./copyAssets'), - unlinkAssets: require('./unlinkAssets') + unlinkAssets: require('./unlinkAssets'), }; }; diff --git a/local-cli/link/android/isInstalled.js b/local-cli/link/android/isInstalled.js index 2accb2a0160..43a53396e92 100644 --- a/local-cli/link/android/isInstalled.js +++ b/local-cli/link/android/isInstalled.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs'); diff --git a/local-cli/link/android/patches/applyParams.js b/local-cli/link/android/patches/applyParams.js index 5f57f3cb8fa..2fd193ad685 100644 --- a/local-cli/link/android/patches/applyParams.js +++ b/local-cli/link/android/patches/applyParams.js @@ -3,19 +3,16 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const toCamelCase = require('lodash').camelCase; module.exports = function applyParams(str, params, prefix) { - return str.replace( - /\$\{(\w+)\}/g, - (pattern, param) => { - const name = toCamelCase(prefix) + '_' + param; + return str.replace(/\$\{(\w+)\}/g, (pattern, param) => { + const name = toCamelCase(prefix) + '_' + param; - return params[param] - ? `getResources().getString(R.string.${name})` - : null; - } - ); + return params[param] ? `getResources().getString(R.string.${name})` : null; + }); }; diff --git a/local-cli/link/android/patches/applyPatch.js b/local-cli/link/android/patches/applyPatch.js index df9680c5072..05393a89472 100644 --- a/local-cli/link/android/patches/applyPatch.js +++ b/local-cli/link/android/patches/applyPatch.js @@ -3,13 +3,17 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs'); module.exports = function applyPatch(file, patch) { - fs.writeFileSync(file, fs - .readFileSync(file, 'utf8') - .replace(patch.pattern, match => `${match}${patch.patch}`) + fs.writeFileSync( + file, + fs + .readFileSync(file, 'utf8') + .replace(patch.pattern, match => `${match}${patch.patch}`), ); }; diff --git a/local-cli/link/android/patches/makeBuildPatch.js b/local-cli/link/android/patches/makeBuildPatch.js index 3c4969af22d..58512183fb1 100644 --- a/local-cli/link/android/patches/makeBuildPatch.js +++ b/local-cli/link/android/patches/makeBuildPatch.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const normalizeProjectName = require('./normalizeProjectName'); @@ -10,12 +12,12 @@ const normalizeProjectName = require('./normalizeProjectName'); module.exports = function makeBuildPatch(name) { const normalizedProjectName = normalizeProjectName(name); const installPattern = new RegExp( - `\\s{4}(compile)(\\(|\\s)(project)\\(\\\':${normalizedProjectName}\\\'\\)(\\)|\\s)` + `\\s{4}(compile)(\\(|\\s)(project)\\(\\\':${normalizedProjectName}\\\'\\)(\\)|\\s)`, ); return { installPattern, pattern: /[^ \t]dependencies {\n/, - patch: ` compile project(':${normalizedProjectName}')\n` + patch: ` compile project(':${normalizedProjectName}')\n`, }; }; diff --git a/local-cli/link/android/patches/makeImportPatch.js b/local-cli/link/android/patches/makeImportPatch.js index 9cb9aaddc99..90bd0f50326 100644 --- a/local-cli/link/android/patches/makeImportPatch.js +++ b/local-cli/link/android/patches/makeImportPatch.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ module.exports = function makeImportPatch(packageImportPath) { diff --git a/local-cli/link/android/patches/makePackagePatch.js b/local-cli/link/android/patches/makePackagePatch.js index 054c2ac5649..29c01b76bb8 100644 --- a/local-cli/link/android/patches/makePackagePatch.js +++ b/local-cli/link/android/patches/makePackagePatch.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const applyParams = require('./applyParams'); diff --git a/local-cli/link/android/patches/makeSettingsPatch.js b/local-cli/link/android/patches/makeSettingsPatch.js index a39de2be17d..76885f70660 100644 --- a/local-cli/link/android/patches/makeSettingsPatch.js +++ b/local-cli/link/android/patches/makeSettingsPatch.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const path = require('path'); @@ -10,14 +12,17 @@ const normalizeProjectName = require('./normalizeProjectName'); const isWin = process.platform === 'win32'; -module.exports = function makeSettingsPatch(name, androidConfig, projectConfig) { +module.exports = function makeSettingsPatch( + name, + androidConfig, + projectConfig, +) { var projectDir = path.relative( path.dirname(projectConfig.settingsGradlePath), - androidConfig.sourceDir + androidConfig.sourceDir, ); const normalizedProjectName = normalizeProjectName(name); - /* * Fix for Windows * Backslashes is the escape character and will result in @@ -30,7 +35,8 @@ module.exports = function makeSettingsPatch(name, androidConfig, projectConfig) return { pattern: '\n', - patch: `include ':${normalizedProjectName}'\n` + + patch: + `include ':${normalizedProjectName}'\n` + `project(':${normalizedProjectName}').projectDir = ` + `new File(rootProject.projectDir, '${projectDir}')\n`, }; diff --git a/local-cli/link/android/patches/makeStringsPatch.js b/local-cli/link/android/patches/makeStringsPatch.js index 281582afb97..a6b40e46f2c 100644 --- a/local-cli/link/android/patches/makeStringsPatch.js +++ b/local-cli/link/android/patches/makeStringsPatch.js @@ -3,21 +3,22 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const toCamelCase = require('lodash').camelCase; module.exports = function makeStringsPatch(params, prefix) { - const values = Object.keys(params) - .map(param => { - const name = toCamelCase(prefix) + '_' + param; - return ' ' + - `${params[param]}`; - }); + const values = Object.keys(params).map(param => { + const name = toCamelCase(prefix) + '_' + param; + return ( + ' ' + + `${params[param]}` + ); + }); - const patch = values.length > 0 - ? values.join('\n') + '\n' - : ''; + const patch = values.length > 0 ? values.join('\n') + '\n' : ''; return { pattern: '\n', diff --git a/local-cli/link/android/patches/normalizeProjectName.js b/local-cli/link/android/patches/normalizeProjectName.js index fd52d1bb108..97dae55eded 100644 --- a/local-cli/link/android/patches/normalizeProjectName.js +++ b/local-cli/link/android/patches/normalizeProjectName.js @@ -1,3 +1,4 @@ +/** @format */ module.exports = function normalizeProjectName(name) { return name.replace(/\//g, '_'); diff --git a/local-cli/link/android/patches/revokePatch.js b/local-cli/link/android/patches/revokePatch.js index 9437e56cb08..14972e46ed9 100644 --- a/local-cli/link/android/patches/revokePatch.js +++ b/local-cli/link/android/patches/revokePatch.js @@ -3,13 +3,15 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs'); module.exports = function revokePatch(file, patch) { - fs.writeFileSync(file, fs - .readFileSync(file, 'utf8') - .replace(patch.patch, '') + fs.writeFileSync( + file, + fs.readFileSync(file, 'utf8').replace(patch.patch, ''), ); }; diff --git a/local-cli/link/android/registerNativeModule.js b/local-cli/link/android/registerNativeModule.js index 0ce77c4e6ed..f73932c0235 100644 --- a/local-cli/link/android/registerNativeModule.js +++ b/local-cli/link/android/registerNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const applyPatch = require('./patches/applyPatch'); @@ -16,13 +18,13 @@ module.exports = function registerNativeAndroidModule( name, androidConfig, params, - projectConfig + projectConfig, ) { const buildPatch = makeBuildPatch(name); applyPatch( projectConfig.settingsGradlePath, - makeSettingsPatch(name, androidConfig, projectConfig) + makeSettingsPatch(name, androidConfig, projectConfig), ); applyPatch(projectConfig.buildGradlePath, buildPatch); @@ -30,11 +32,11 @@ module.exports = function registerNativeAndroidModule( applyPatch( projectConfig.mainFilePath, - makePackagePatch(androidConfig.packageInstance, params, name) + makePackagePatch(androidConfig.packageInstance, params, name), ); applyPatch( projectConfig.mainFilePath, - makeImportPatch(androidConfig.packageImportPath) + makeImportPatch(androidConfig.packageImportPath), ); }; diff --git a/local-cli/link/android/unlinkAssets.js b/local-cli/link/android/unlinkAssets.js index b0eeefed93c..81e90c5e71a 100644 --- a/local-cli/link/android/unlinkAssets.js +++ b/local-cli/link/android/unlinkAssets.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs-extra'); @@ -18,8 +20,12 @@ const groupFilesByType = require('../groupFilesByType'); module.exports = function unlinkAssetsAndroid(files, project) { const assets = groupFilesByType(files); - (assets.font || []).forEach((file) => { - const filePath = path.join(project.assetsPath, 'fonts', path.basename(file)); + (assets.font || []).forEach(file => { + const filePath = path.join( + project.assetsPath, + 'fonts', + path.basename(file), + ); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } diff --git a/local-cli/link/android/unregisterNativeModule.js b/local-cli/link/android/unregisterNativeModule.js index b6b8d166531..880070afa50 100644 --- a/local-cli/link/android/unregisterNativeModule.js +++ b/local-cli/link/android/unregisterNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs'); @@ -18,7 +20,7 @@ const makePackagePatch = require('./patches/makePackagePatch'); module.exports = function unregisterNativeAndroidModule( name, androidConfig, - projectConfig + projectConfig, ) { const buildPatch = makeBuildPatch(name); const strings = fs.readFileSync(projectConfig.stringsPath, 'utf8'); @@ -28,12 +30,12 @@ module.exports = function unregisterNativeAndroidModule( /moduleConfig="true" name="(\w+)">(.*) { params[param.slice(toCamelCase(name).length + 1)] = value; - } + }, ); revokePatch( projectConfig.settingsGradlePath, - makeSettingsPatch(name, androidConfig, projectConfig) + makeSettingsPatch(name, androidConfig, projectConfig), ); revokePatch(projectConfig.buildGradlePath, buildPatch); @@ -41,11 +43,11 @@ module.exports = function unregisterNativeAndroidModule( revokePatch( projectConfig.mainFilePath, - makePackagePatch(androidConfig.packageInstance, params, name) + makePackagePatch(androidConfig.packageInstance, params, name), ); revokePatch( projectConfig.mainFilePath, - makeImportPatch(androidConfig.packageImportPath) + makeImportPatch(androidConfig.packageImportPath), ); }; diff --git a/local-cli/link/commandStub.js b/local-cli/link/commandStub.js index 13078bd3404..768a94f98d3 100644 --- a/local-cli/link/commandStub.js +++ b/local-cli/link/commandStub.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ -module.exports = (cb) => cb(); +module.exports = cb => cb(); diff --git a/local-cli/link/getDependencyConfig.js b/local-cli/link/getDependencyConfig.js index 71ce2659090..19c54324e77 100644 --- a/local-cli/link/getDependencyConfig.js +++ b/local-cli/link/getDependencyConfig.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** diff --git a/local-cli/link/getProjectDependencies.js b/local-cli/link/getProjectDependencies.js index 1d5b0781a9b..c078aab1a37 100644 --- a/local-cli/link/getProjectDependencies.js +++ b/local-cli/link/getProjectDependencies.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const path = require('path'); @@ -12,5 +14,7 @@ const path = require('path'); */ module.exports = function getProjectDependencies() { const pjson = require(path.join(process.cwd(), './package.json')); - return Object.keys(pjson.dependencies || {}).filter(name => name !== 'react-native'); + return Object.keys(pjson.dependencies || {}).filter( + name => name !== 'react-native', + ); }; diff --git a/local-cli/link/groupFilesByType.js b/local-cli/link/groupFilesByType.js index 786c71532e9..47aa7f6b52e 100644 --- a/local-cli/link/groupFilesByType.js +++ b/local-cli/link/groupFilesByType.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const groupBy = require('lodash').groupBy; diff --git a/local-cli/link/ios/addFileToProject.js b/local-cli/link/ios/addFileToProject.js index 168220f8038..d3a560529c0 100644 --- a/local-cli/link/ios/addFileToProject.js +++ b/local-cli/link/ios/addFileToProject.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const PbxFile = require('xcode/lib/pbxFile'); diff --git a/local-cli/link/ios/addProjectToLibraries.js b/local-cli/link/ios/addProjectToLibraries.js index 045697dec1f..e15c8baf410 100644 --- a/local-cli/link/ios/addProjectToLibraries.js +++ b/local-cli/link/ios/addProjectToLibraries.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** diff --git a/local-cli/link/ios/addSharedLibraries.js b/local-cli/link/ios/addSharedLibraries.js index a0c6f16e649..e12d913ba23 100644 --- a/local-cli/link/ios/addSharedLibraries.js +++ b/local-cli/link/ios/addSharedLibraries.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const createGroupWithMessage = require('./createGroupWithMessage'); @@ -18,6 +20,6 @@ module.exports = function addSharedLibraries(project, libraries) { const target = project.getFirstTarget().uuid; for (var name of libraries) { - project.addFramework(name, { target }); + project.addFramework(name, {target}); } }; diff --git a/local-cli/link/ios/addToHeaderSearchPaths.js b/local-cli/link/ios/addToHeaderSearchPaths.js index 579007ecf81..dd3923451b3 100644 --- a/local-cli/link/ios/addToHeaderSearchPaths.js +++ b/local-cli/link/ios/addToHeaderSearchPaths.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); diff --git a/local-cli/link/ios/common/isInstalled.js b/local-cli/link/ios/common/isInstalled.js index 69bcd8bdf32..71af956bdcf 100644 --- a/local-cli/link/ios/common/isInstalled.js +++ b/local-cli/link/ios/common/isInstalled.js @@ -1,6 +1,11 @@ +/** @format */ + const isInstalledIOS = require('../isInstalled'); const isInstalledPods = require('../../pods/isInstalled'); module.exports = function isInstalled(projectConfig, name, dependencyConfig) { - return isInstalledIOS(projectConfig, dependencyConfig) || isInstalledPods(projectConfig, dependencyConfig); + return ( + isInstalledIOS(projectConfig, dependencyConfig) || + isInstalledPods(projectConfig, dependencyConfig) + ); }; diff --git a/local-cli/link/ios/common/registerNativeModule.js b/local-cli/link/ios/common/registerNativeModule.js index 38ce5960698..72057712fe0 100644 --- a/local-cli/link/ios/common/registerNativeModule.js +++ b/local-cli/link/ios/common/registerNativeModule.js @@ -1,3 +1,5 @@ +/** @format */ + const registerDependencyIOS = require('../registerNativeModule'); const registerDependencyPods = require('../../pods/registerNativeModule'); @@ -5,12 +7,11 @@ module.exports = function registerNativeModule( name, dependencyConfig, params, - projectConfig + projectConfig, ) { if (projectConfig.podfile && dependencyConfig.podspec) { registerDependencyPods(name, dependencyConfig, projectConfig); - } - else { + } else { registerDependencyIOS(dependencyConfig, projectConfig); } }; diff --git a/local-cli/link/ios/common/unregisterNativeModule.js b/local-cli/link/ios/common/unregisterNativeModule.js index e6d34ada4cc..dbf7bc4147d 100644 --- a/local-cli/link/ios/common/unregisterNativeModule.js +++ b/local-cli/link/ios/common/unregisterNativeModule.js @@ -1,3 +1,5 @@ +/** @format */ + const compact = require('lodash').compact; const isInstalledIOS = require('../isInstalled'); const isInstalledPods = require('../../pods/isInstalled'); @@ -8,15 +10,14 @@ module.exports = function unregisterNativeModule( name, dependencyConfig, projectConfig, - otherDependencies + otherDependencies, ) { const isIosInstalled = isInstalledIOS(projectConfig, dependencyConfig); const isPodInstalled = isInstalledPods(projectConfig, dependencyConfig); if (isIosInstalled) { const iOSDependencies = compact(otherDependencies.map(d => d.config.ios)); unregisterDependencyIOS(dependencyConfig, projectConfig, iOSDependencies); - } - else if (isPodInstalled) { + } else if (isPodInstalled) { unregisterDependencyPods(dependencyConfig, projectConfig); } }; diff --git a/local-cli/link/ios/copyAssets.js b/local-cli/link/ios/copyAssets.js index 8f6d2b86eb1..0510569900e 100644 --- a/local-cli/link/ios/copyAssets.js +++ b/local-cli/link/ios/copyAssets.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs-extra'); @@ -28,12 +30,11 @@ module.exports = function linkAssetsIOS(files, projectConfig) { function addResourceFile(f) { return (f || []) .map(asset => - project.addResourceFile( - path.relative(projectConfig.sourceDir, asset), - { target: project.getFirstTarget().uuid } - ) + project.addResourceFile(path.relative(projectConfig.sourceDir, asset), { + target: project.getFirstTarget().uuid, + }), ) - .filter(file => file) // xcode returns false if file is already there + .filter(file => file) // xcode returns false if file is already there .map(file => file.basename); } @@ -41,14 +42,11 @@ module.exports = function linkAssetsIOS(files, projectConfig) { const fonts = addResourceFile(assets.font); - const existingFonts = (plist.UIAppFonts || []); + const existingFonts = plist.UIAppFonts || []; const allFonts = [...existingFonts, ...fonts]; plist.UIAppFonts = Array.from(new Set(allFonts)); // use Set to dedupe w/existing - fs.writeFileSync( - projectConfig.pbxprojPath, - project.writeSync() - ); + fs.writeFileSync(projectConfig.pbxprojPath, project.writeSync()); writePlist(project, projectConfig.sourceDir, plist); }; diff --git a/local-cli/link/ios/createGroup.js b/local-cli/link/ios/createGroup.js index 62f79e1c974..4e9cbccc418 100644 --- a/local-cli/link/ios/createGroup.js +++ b/local-cli/link/ios/createGroup.js @@ -3,11 +3,14 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const getGroup = require('./getGroup'); -const hasGroup = (pbxGroup, name) => pbxGroup.children.find(group => group.comment === name); +const hasGroup = (pbxGroup, name) => + pbxGroup.children.find(group => group.comment === name); /** * Given project and path of the group, it deeply creates a given group @@ -16,19 +19,16 @@ const hasGroup = (pbxGroup, name) => pbxGroup.children.find(group => group.comme * Returns newly created group */ module.exports = function createGroup(project, path) { - return path.split('/').reduce( - (group, name) => { - if (!hasGroup(group, name)) { - const uuid = project.pbxCreateGroup(name, '""'); + return path.split('/').reduce((group, name) => { + if (!hasGroup(group, name)) { + const uuid = project.pbxCreateGroup(name, '""'); - group.children.push({ - value: uuid, - comment: name, - }); - } + group.children.push({ + value: uuid, + comment: name, + }); + } - return project.pbxGroupByName(name); - }, - getGroup(project) - ); + return project.pbxGroupByName(name); + }, getGroup(project)); }; diff --git a/local-cli/link/ios/createGroupWithMessage.js b/local-cli/link/ios/createGroupWithMessage.js index 4b598940da9..7d9f1aaa05d 100644 --- a/local-cli/link/ios/createGroupWithMessage.js +++ b/local-cli/link/ios/createGroupWithMessage.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const log = require('npmlog'); @@ -24,7 +26,7 @@ module.exports = function createGroupWithMessage(project, path) { log.warn( 'ERRGROUP', - `Group '${path}' does not exist in your Xcode project. We have created it automatically for you.` + `Group '${path}' does not exist in your Xcode project. We have created it automatically for you.`, ); } diff --git a/local-cli/link/ios/getBuildProperty.js b/local-cli/link/ios/getBuildProperty.js index bb1c7b78b88..074e37816e9 100644 --- a/local-cli/link/ios/getBuildProperty.js +++ b/local-cli/link/ios/getBuildProperty.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -18,8 +20,12 @@ */ module.exports = function getBuildProperty(project, prop) { const target = project.getFirstTarget().firstTarget; - const config = project.pbxXCConfigurationList()[target.buildConfigurationList]; - const buildSection = project.pbxXCBuildConfigurationSection()[config.buildConfigurations[0].value]; + const config = project.pbxXCConfigurationList()[ + target.buildConfigurationList + ]; + const buildSection = project.pbxXCBuildConfigurationSection()[ + config.buildConfigurations[0].value + ]; return buildSection.buildSettings[prop]; }; diff --git a/local-cli/link/ios/getGroup.js b/local-cli/link/ios/getGroup.js index c66205be011..fcbfbf16da8 100644 --- a/local-cli/link/ios/getGroup.js +++ b/local-cli/link/ios/getGroup.js @@ -3,11 +3,14 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ -const getFirstProject = (project) => project.getFirstProject().firstProject; +const getFirstProject = project => project.getFirstProject().firstProject; -const findGroup = (group, name) => group.children.find(group => group.comment === name); +const findGroup = (group, name) => + group.children.find(group => group.comment === name); /** * Returns group from .xcodeproj if one exists, null otherwise diff --git a/local-cli/link/ios/getHeaderSearchPath.js b/local-cli/link/ios/getHeaderSearchPath.js index c5f2572c622..74246abafb6 100644 --- a/local-cli/link/ios/getHeaderSearchPath.js +++ b/local-cli/link/ios/getHeaderSearchPath.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const path = require('path'); @@ -19,19 +21,19 @@ const last = require('lodash').last; * * Check `getHeaderSearchPath.spec.js` for more use-cases. */ -const getOuterDirectory = (directories) => +const getOuterDirectory = directories => directories.reduce((topDir, currentDir) => { const currentFolders = currentDir.split(path.sep); const topMostFolders = topDir.split(path.sep); - if (currentFolders.length === topMostFolders.length - && last(currentFolders) !== last(topMostFolders)) { + if ( + currentFolders.length === topMostFolders.length && + last(currentFolders) !== last(topMostFolders) + ) { return currentFolders.slice(0, -1).join(path.sep); } - return currentFolders.length < topMostFolders.length - ? currentDir - : topDir; + return currentFolders.length < topMostFolders.length ? currentDir : topDir; }); /** @@ -49,11 +51,12 @@ const getOuterDirectory = (directories) => * every folder of it to locate correct headers. */ module.exports = function getHeaderSearchPath(sourceDir, headers) { - const directories = union( - headers.map(path.dirname) - ); + const directories = union(headers.map(path.dirname)); return directories.length === 1 ? `"$(SRCROOT)${path.sep}${path.relative(sourceDir, directories[0])}"` - : `"$(SRCROOT)${path.sep}${path.relative(sourceDir, getOuterDirectory(directories))}/**"`; + : `"$(SRCROOT)${path.sep}${path.relative( + sourceDir, + getOuterDirectory(directories), + )}/**"`; }; diff --git a/local-cli/link/ios/getHeadersInFolder.js b/local-cli/link/ios/getHeadersInFolder.js index a4c2250ab47..c63c450c767 100644 --- a/local-cli/link/ios/getHeadersInFolder.js +++ b/local-cli/link/ios/getHeadersInFolder.js @@ -3,12 +3,19 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const glob = require('glob'); const path = require('path'); -const GLOB_EXCLUDE_PATTERN = ['node_modules/**', 'Pods/**', 'Examples/**', 'examples/**']; +const GLOB_EXCLUDE_PATTERN = [ + 'node_modules/**', + 'Pods/**', + 'Examples/**', + 'examples/**', +]; /** * Given folder, it returns an array of all header files diff --git a/local-cli/link/ios/getPlist.js b/local-cli/link/ios/getPlist.js index 61c877258e9..3948e8d5ec7 100644 --- a/local-cli/link/ios/getPlist.js +++ b/local-cli/link/ios/getPlist.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const plistParser = require('plist'); @@ -21,7 +23,5 @@ module.exports = function getPlist(project, sourceDir) { return null; } - return plistParser.parse( - fs.readFileSync(plistPath, 'utf-8') - ); + return plistParser.parse(fs.readFileSync(plistPath, 'utf-8')); }; diff --git a/local-cli/link/ios/getPlistPath.js b/local-cli/link/ios/getPlistPath.js index 0609f5f581f..72c6be75d17 100644 --- a/local-cli/link/ios/getPlistPath.js +++ b/local-cli/link/ios/getPlistPath.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const path = require('path'); @@ -17,6 +19,6 @@ module.exports = function getPlistPath(project, sourceDir) { return path.join( sourceDir, - plistFile.replace(/"/g, '').replace('$(SRCROOT)', '') + plistFile.replace(/"/g, '').replace('$(SRCROOT)', ''), ); }; diff --git a/local-cli/link/ios/getProducts.js b/local-cli/link/ios/getProducts.js index 7e24f15826b..dd0b0431938 100644 --- a/local-cli/link/ios/getProducts.js +++ b/local-cli/link/ios/getProducts.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -13,7 +15,6 @@ module.exports = function getProducts(project) { return project .pbxGroupByName('Products') - .children - .map(c => c.comment) + .children.map(c => c.comment) .filter(c => c.indexOf('.a') > -1); }; diff --git a/local-cli/link/ios/getTargets.js b/local-cli/link/ios/getTargets.js index 784eed2177f..b81145a5e98 100644 --- a/local-cli/link/ios/getTargets.js +++ b/local-cli/link/ios/getTargets.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -13,15 +15,23 @@ module.exports = function getTargets(project) { let nativeTargetSection = project.pbxNativeTargetSection(); return targets.map(function(target) { let key = target.value; - let configurationListId = project.pbxNativeTargetSection()[key].buildConfigurationList; - let configurationList = project.pbxXCConfigurationList()[configurationListId]; + let configurationListId = project.pbxNativeTargetSection()[key] + .buildConfigurationList; + let configurationList = project.pbxXCConfigurationList()[ + configurationListId + ]; let buildConfigurationId = configurationList.buildConfigurations[0].value; - let buildConfiguration = project.pbxXCBuildConfigurationSection()[buildConfigurationId]; + let buildConfiguration = project.pbxXCBuildConfigurationSection()[ + buildConfigurationId + ]; return { uuid: key, target: nativeTargetSection[key], - name: nativeTargetSection[key].productReference_comment, - isTVOS: (buildConfiguration.buildSettings.SDKROOT && (buildConfiguration.buildSettings.SDKROOT.indexOf('appletv') !== -1)) || false + name: nativeTargetSection[key].productReference_comment, + isTVOS: + (buildConfiguration.buildSettings.SDKROOT && + buildConfiguration.buildSettings.SDKROOT.indexOf('appletv') !== -1) || + false, }; }); }; diff --git a/local-cli/link/ios/hasLibraryImported.js b/local-cli/link/ios/hasLibraryImported.js index 0372f0b4b92..eed9c6e1cb2 100644 --- a/local-cli/link/ios/hasLibraryImported.js +++ b/local-cli/link/ios/hasLibraryImported.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -11,7 +13,8 @@ * or not */ module.exports = function hasLibraryImported(libraries, packageName) { - return libraries.children - .filter(library => library.comment === packageName) - .length > 0; + return ( + libraries.children.filter(library => library.comment === packageName) + .length > 0 + ); }; diff --git a/local-cli/link/ios/index.js b/local-cli/link/ios/index.js index 9653b3be80a..bf6b57b2618 100644 --- a/local-cli/link/ios/index.js +++ b/local-cli/link/ios/index.js @@ -1,9 +1,11 @@ +/** @format */ + module.exports = function() { return { isInstalled: require('./common/isInstalled'), register: require('./common/registerNativeModule'), unregister: require('./common/unregisterNativeModule'), copyAssets: require('./copyAssets'), - unlinkAssets: require('./unlinkAssets') + unlinkAssets: require('./unlinkAssets'), }; }; diff --git a/local-cli/link/ios/isInstalled.js b/local-cli/link/ios/isInstalled.js index 7b0e4a94672..084c8addda6 100644 --- a/local-cli/link/ios/isInstalled.js +++ b/local-cli/link/ios/isInstalled.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const xcode = require('xcode'); diff --git a/local-cli/link/ios/mapHeaderSearchPaths.js b/local-cli/link/ios/mapHeaderSearchPaths.js index cb2a583f25f..64a8f6560ca 100644 --- a/local-cli/link/ios/mapHeaderSearchPaths.js +++ b/local-cli/link/ios/mapHeaderSearchPaths.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -25,22 +27,20 @@ const defaultHeaderPaths = ['"$(inherited)"']; module.exports = function headerSearchPathIter(project, func) { const config = project.pbxXCBuildConfigurationSection(); - Object - .keys(config) + Object.keys(config) .filter(ref => ref.indexOf('_comment') === -1) .forEach(ref => { const buildSettings = config[ref].buildSettings; - const shouldVisitBuildSettings = ( - Array.isArray(buildSettings.OTHER_LDFLAGS) ? - buildSettings.OTHER_LDFLAGS : - [] - ) - .indexOf('"-lc++"') >= 0; + const shouldVisitBuildSettings = + (Array.isArray(buildSettings.OTHER_LDFLAGS) + ? buildSettings.OTHER_LDFLAGS + : [] + ).indexOf('"-lc++"') >= 0; if (shouldVisitBuildSettings) { - const searchPaths = buildSettings.HEADER_SEARCH_PATHS ? - [].concat(buildSettings.HEADER_SEARCH_PATHS) : - defaultHeaderPaths; + const searchPaths = buildSettings.HEADER_SEARCH_PATHS + ? [].concat(buildSettings.HEADER_SEARCH_PATHS) + : defaultHeaderPaths; buildSettings.HEADER_SEARCH_PATHS = func(searchPaths); } diff --git a/local-cli/link/ios/registerNativeModule.js b/local-cli/link/ios/registerNativeModule.js index fed2b0bb2cf..41cca896709 100644 --- a/local-cli/link/ios/registerNativeModule.js +++ b/local-cli/link/ios/registerNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const xcode = require('xcode'); @@ -29,14 +31,22 @@ const getGroup = require('./getGroup'); * * If library is already linked, this action is a no-op. */ -module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfig) { +module.exports = function registerNativeModuleIOS( + dependencyConfig, + projectConfig, +) { const project = xcode.project(projectConfig.pbxprojPath).parseSync(); - const dependencyProject = xcode.project(dependencyConfig.pbxprojPath).parseSync(); + const dependencyProject = xcode + .project(dependencyConfig.pbxprojPath) + .parseSync(); - const libraries = createGroupWithMessage(project, projectConfig.libraryFolder); + const libraries = createGroupWithMessage( + project, + projectConfig.libraryFolder, + ); const file = addFileToProject( project, - path.relative(projectConfig.sourceDir, dependencyConfig.projectPath) + path.relative(projectConfig.sourceDir, dependencyConfig.projectPath), ); const targets = getTargets(project); @@ -49,7 +59,7 @@ module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfi for (i = 0; i < targets.length; i++) { if (!targets[i].isTVOS) { project.addStaticLibrary(product.name, { - target: targets[i].uuid + target: targets[i].uuid, }); } } @@ -59,7 +69,7 @@ module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfi for (i = 0; i < targets.length; i++) { if (targets[i].isTVOS) { project.addStaticLibrary(product.name, { - target: targets[i].uuid + target: targets[i].uuid, }); } } @@ -72,12 +82,9 @@ module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfi if (!isEmpty(headers)) { addToHeaderSearchPaths( project, - getHeaderSearchPath(projectConfig.sourceDir, headers) + getHeaderSearchPath(projectConfig.sourceDir, headers), ); } - fs.writeFileSync( - projectConfig.pbxprojPath, - project.writeSync() - ); + fs.writeFileSync(projectConfig.pbxprojPath, project.writeSync()); }; diff --git a/local-cli/link/ios/removeFromHeaderSearchPaths.js b/local-cli/link/ios/removeFromHeaderSearchPaths.js index f662991210c..ac9ead94c65 100644 --- a/local-cli/link/ios/removeFromHeaderSearchPaths.js +++ b/local-cli/link/ios/removeFromHeaderSearchPaths.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); @@ -11,7 +13,7 @@ const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); * Given Xcode project and absolute path, it makes sure there are no headers referring to it */ module.exports = function addToHeaderSearchPaths(project, path) { - mapHeaderSearchPaths(project, - searchPaths => searchPaths.filter(searchPath => searchPath !== path) + mapHeaderSearchPaths(project, searchPaths => + searchPaths.filter(searchPath => searchPath !== path), ); }; diff --git a/local-cli/link/ios/removeFromPbxItemContainerProxySection.js b/local-cli/link/ios/removeFromPbxItemContainerProxySection.js index 44a3fb2db83..d7e8f05f166 100644 --- a/local-cli/link/ios/removeFromPbxItemContainerProxySection.js +++ b/local-cli/link/ios/removeFromPbxItemContainerProxySection.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -10,7 +12,10 @@ * a new PBXItemContainerProxy is created that contains `containerPortal` value * which equals to xcodeproj file.uuid from PBXFileReference section. */ -module.exports = function removeFromPbxItemContainerProxySection(project, file) { +module.exports = function removeFromPbxItemContainerProxySection( + project, + file, +) { const section = project.hash.project.objects.PBXContainerItemProxy; for (var key of Object.keys(section)) { diff --git a/local-cli/link/ios/removeFromPbxReferenceProxySection.js b/local-cli/link/ios/removeFromPbxReferenceProxySection.js index ba3626b796c..05346ccabff 100644 --- a/local-cli/link/ios/removeFromPbxReferenceProxySection.js +++ b/local-cli/link/ios/removeFromPbxReferenceProxySection.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** diff --git a/local-cli/link/ios/removeFromProjectReferences.js b/local-cli/link/ios/removeFromProjectReferences.js index 5edc858807f..4eafe81e841 100644 --- a/local-cli/link/ios/removeFromProjectReferences.js +++ b/local-cli/link/ios/removeFromProjectReferences.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -18,7 +20,9 @@ module.exports = function removeFromProjectReferences(project, file) { const firstProject = project.getFirstProject().firstProject; - const projectRef = firstProject.projectReferences.find(item => item.ProjectRef === file.uuid); + const projectRef = firstProject.projectReferences.find( + item => item.ProjectRef === file.uuid, + ); if (!projectRef) { return null; @@ -26,7 +30,7 @@ module.exports = function removeFromProjectReferences(project, file) { firstProject.projectReferences.splice( firstProject.projectReferences.indexOf(projectRef), - 1 + 1, ); return projectRef; diff --git a/local-cli/link/ios/removeFromStaticLibraries.js b/local-cli/link/ios/removeFromStaticLibraries.js index 391088c1570..1fa674331a8 100644 --- a/local-cli/link/ios/removeFromStaticLibraries.js +++ b/local-cli/link/ios/removeFromStaticLibraries.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const PbxFile = require('xcode/lib/pbxFile'); diff --git a/local-cli/link/ios/removeProductGroup.js b/local-cli/link/ios/removeProductGroup.js index 888f2a44200..a15fd9d750f 100644 --- a/local-cli/link/ios/removeProductGroup.js +++ b/local-cli/link/ios/removeProductGroup.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ module.exports = function removeProductGroup(project, productGroupId) { diff --git a/local-cli/link/ios/removeProjectFromLibraries.js b/local-cli/link/ios/removeProjectFromLibraries.js index 9eaee4758bf..5dc572b9ef5 100644 --- a/local-cli/link/ios/removeProjectFromLibraries.js +++ b/local-cli/link/ios/removeProjectFromLibraries.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -13,7 +15,7 @@ * It's mainly due to limitations of `xcode` library. */ module.exports = function removeProjectFromLibraries(libraries, file) { - libraries.children = libraries.children.filter(library => - library.comment !== file.basename + libraries.children = libraries.children.filter( + library => library.comment !== file.basename, ); }; diff --git a/local-cli/link/ios/removeProjectFromProject.js b/local-cli/link/ios/removeProjectFromProject.js index cb7c1711497..76e9348184e 100644 --- a/local-cli/link/ios/removeProjectFromProject.js +++ b/local-cli/link/ios/removeProjectFromProject.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const PbxFile = require('xcode/lib/pbxFile'); diff --git a/local-cli/link/ios/removeSharedLibraries.js b/local-cli/link/ios/removeSharedLibraries.js index dd2629ebb03..e0306d28b0c 100644 --- a/local-cli/link/ios/removeSharedLibraries.js +++ b/local-cli/link/ios/removeSharedLibraries.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ module.exports = function removeSharedLibraries(project, libraries) { @@ -13,6 +15,6 @@ module.exports = function removeSharedLibraries(project, libraries) { const target = project.getFirstTarget().uuid; for (var name of libraries) { - project.removeFramework(name, { target }); + project.removeFramework(name, {target}); } }; diff --git a/local-cli/link/ios/unlinkAssets.js b/local-cli/link/ios/unlinkAssets.js index a7c38446f4c..67f91cf6c61 100644 --- a/local-cli/link/ios/unlinkAssets.js +++ b/local-cli/link/ios/unlinkAssets.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const fs = require('fs-extra'); @@ -26,24 +28,24 @@ module.exports = function unlinkAssetsIOS(files, projectConfig) { if (!plist) { return log.error( 'ERRPLIST', - 'Could not locate Info.plist file. Check if your project has \'INFOPLIST_FILE\' set properly' + "Could not locate Info.plist file. Check if your project has 'INFOPLIST_FILE' set properly", ); } if (!project.pbxGroupByName('Resources')) { return log.error( 'ERRGROUP', - 'Group \'Resources\' does not exist in your Xcode project. There is nothing to unlink.' + "Group 'Resources' does not exist in your Xcode project. There is nothing to unlink.", ); } - const removeResourceFile = function (f) { + const removeResourceFile = function(f) { (f || []) .map(asset => project.removeResourceFile( path.relative(projectConfig.sourceDir, asset), - { target: project.getFirstTarget().uuid } - ) + {target: project.getFirstTarget().uuid}, + ), ) .map(file => file.basename); }; @@ -54,10 +56,7 @@ module.exports = function unlinkAssetsIOS(files, projectConfig) { plist.UIAppFonts = difference(plist.UIAppFonts || [], fonts); - fs.writeFileSync( - projectConfig.pbxprojPath, - project.writeSync() - ); + fs.writeFileSync(projectConfig.pbxprojPath, project.writeSync()); writePlist(project, projectConfig.sourceDir, plist); }; diff --git a/local-cli/link/ios/unregisterNativeModule.js b/local-cli/link/ios/unregisterNativeModule.js index b35a6c31aef..c686b8c4969 100644 --- a/local-cli/link/ios/unregisterNativeModule.js +++ b/local-cli/link/ios/unregisterNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const xcode = require('xcode'); @@ -27,15 +29,21 @@ const removeSharedLibraries = require('./removeSharedLibraries'); * * If library is already unlinked, this action is a no-op. */ -module.exports = function unregisterNativeModule(dependencyConfig, projectConfig, iOSDependencies) { +module.exports = function unregisterNativeModule( + dependencyConfig, + projectConfig, + iOSDependencies, +) { const project = xcode.project(projectConfig.pbxprojPath).parseSync(); - const dependencyProject = xcode.project(dependencyConfig.pbxprojPath).parseSync(); + const dependencyProject = xcode + .project(dependencyConfig.pbxprojPath) + .parseSync(); const libraries = getGroup(project, projectConfig.libraryFolder); const file = removeProjectFromProject( project, - path.relative(projectConfig.sourceDir, dependencyConfig.projectPath) + path.relative(projectConfig.sourceDir, dependencyConfig.projectPath), ); removeProjectFromLibraries(libraries, file); @@ -50,8 +58,8 @@ module.exports = function unregisterNativeModule(dependencyConfig, projectConfig dependencyConfig.sharedLibraries, iOSDependencies.reduce( (libs, dependency) => libs.concat(dependency.sharedLibraries), - projectConfig.sharedLibraries - ) + projectConfig.sharedLibraries, + ), ); removeSharedLibraries(project, sharedLibraries); @@ -60,12 +68,9 @@ module.exports = function unregisterNativeModule(dependencyConfig, projectConfig if (!isEmpty(headers)) { removeFromHeaderSearchPaths( project, - getHeaderSearchPath(projectConfig.sourceDir, headers) + getHeaderSearchPath(projectConfig.sourceDir, headers), ); } - fs.writeFileSync( - projectConfig.pbxprojPath, - project.writeSync() - ); + fs.writeFileSync(projectConfig.pbxprojPath, project.writeSync()); }; diff --git a/local-cli/link/ios/writePlist.js b/local-cli/link/ios/writePlist.js index 0c025d2e9d2..b2ea1ae1efc 100644 --- a/local-cli/link/ios/writePlist.js +++ b/local-cli/link/ios/writePlist.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const plistParser = require('plist'); @@ -26,6 +28,6 @@ module.exports = function writePlist(project, sourceDir, plist) { // Ref: https://github.com/facebook/react-native/issues/11668 return fs.writeFileSync( plistPath, - plistParser.build(plist, { indent: '\t', offset: -1 }) + '\n' + plistParser.build(plist, {indent: '\t', offset: -1}) + '\n', ); }; diff --git a/local-cli/link/link.js b/local-cli/link/link.js index 66e9efbf563..892e4f71063 100644 --- a/local-cli/link/link.js +++ b/local-cli/link/link.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -35,40 +36,54 @@ import type {RNConfig} from '../core'; log.heading = 'rnpm-link'; -const dedupeAssets = (assets) => uniqBy(assets, asset => path.basename(asset)); +const dedupeAssets = assets => uniqBy(assets, asset => path.basename(asset)); const linkDependency = async (platforms, project, dependency) => { const params = await pollParams(dependency.config.params); - Object.keys(platforms || {}) - .forEach(platform => { - if (!project[platform] || !dependency.config[platform]) { - return null; - } + Object.keys(platforms || {}).forEach(platform => { + if (!project[platform] || !dependency.config[platform]) { + return null; + } - const linkConfig = platforms[platform] && platforms[platform].linkConfig && platforms[platform].linkConfig(); - if (!linkConfig || !linkConfig.isInstalled || !linkConfig.register) { - return null; - } + const linkConfig = + platforms[platform] && + platforms[platform].linkConfig && + platforms[platform].linkConfig(); + if (!linkConfig || !linkConfig.isInstalled || !linkConfig.register) { + return null; + } - const isInstalled = linkConfig.isInstalled(project[platform], dependency.name, dependency.config[platform]); + const isInstalled = linkConfig.isInstalled( + project[platform], + dependency.name, + dependency.config[platform], + ); - if (isInstalled) { - log.info(chalk.grey(`Platform '${platform}' module ${dependency.name} is already linked`)); - return null; - } - - log.info(`Linking ${dependency.name} ${platform} dependency`); - - linkConfig.register( - dependency.name, - dependency.config[platform], - params, - project[platform] + if (isInstalled) { + log.info( + chalk.grey( + `Platform '${platform}' module ${dependency.name} is already linked`, + ), ); + return null; + } - log.info(`Platform '${platform}' module ${dependency.name} has been successfully linked`); - }); + log.info(`Linking ${dependency.name} ${platform} dependency`); + + linkConfig.register( + dependency.name, + dependency.config[platform], + params, + project[platform], + ); + + log.info( + `Platform '${platform}' module ${ + dependency.name + } has been successfully linked`, + ); + }); }; const linkAssets = (platforms, project, assets) => { @@ -76,16 +91,18 @@ const linkAssets = (platforms, project, assets) => { return; } - Object.keys(platforms || {}) - .forEach(platform => { - const linkConfig = platforms[platform] && platforms[platform].linkConfig && platforms[platform].linkConfig(); - if (!linkConfig || !linkConfig.copyAssets) { - return; - } + Object.keys(platforms || {}).forEach(platform => { + const linkConfig = + platforms[platform] && + platforms[platform].linkConfig && + platforms[platform].linkConfig(); + if (!linkConfig || !linkConfig.copyAssets) { + return; + } - log.info(`Linking assets to ${platform} project`); - linkConfig.copyAssets(assets, project[platform]); - }); + log.info(`Linking assets to ${platform} project`); + linkConfig.copyAssets(assets, project[platform]); + }); log.info('Assets have been successfully linked to your project'); }; @@ -106,19 +123,22 @@ function link(args: Array, config: RNConfig) { } catch (err) { log.error( 'ERRPACKAGEJSON', - 'No package found. Are you sure this is a React Native project?' + 'No package found. Are you sure this is a React Native project?', ); return Promise.reject(err); } - const hasProjectConfig = Object.keys(platforms).reduce((acc, key) => acc || key in project, false); + const hasProjectConfig = Object.keys(platforms).reduce( + (acc, key) => acc || key in project, + false, + ); if (!hasProjectConfig && findReactNativeScripts()) { throw new Error( '`react-native link` can not be used in Create React Native App projects. ' + - 'If you need to include a library that relies on custom native code, ' + - 'you might have to eject first. ' + - 'See https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md ' + - 'for more information.' + 'If you need to include a library that relies on custom native code, ' + + 'you might have to eject first. ' + + 'See https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md ' + + 'for more information.', ); } @@ -130,26 +150,30 @@ function link(args: Array, config: RNConfig) { const dependencies = getDependencyConfig( config, - packageName ? [packageName] : getProjectDependencies() + packageName ? [packageName] : getProjectDependencies(), ); - const assets = dedupeAssets(dependencies.reduce( - (acc, dependency) => acc.concat(dependency.config.assets), - project.assets - )); + const assets = dedupeAssets( + dependencies.reduce( + (acc, dependency) => acc.concat(dependency.config.assets), + project.assets, + ), + ); - const tasks = flatten(dependencies.map(dependency => [ - () => promisify(dependency.config.commands.prelink || commandStub), - () => linkDependency(platforms, project, dependency), - () => promisify(dependency.config.commands.postlink || commandStub), - ])); + const tasks = flatten( + dependencies.map(dependency => [ + () => promisify(dependency.config.commands.prelink || commandStub), + () => linkDependency(platforms, project, dependency), + () => promisify(dependency.config.commands.postlink || commandStub), + ]), + ); tasks.push(() => linkAssets(platforms, project, assets)); return promiseWaterfall(tasks).catch(err => { log.error( `Something went wrong while linking. Error: ${err.message} \n` + - 'Please file an issue here: https://github.com/facebook/react-native/issues' + 'Please file an issue here: https://github.com/facebook/react-native/issues', ); throw err; }); diff --git a/local-cli/link/pods/addPodEntry.js b/local-cli/link/pods/addPodEntry.js index ea921862367..8ce5654ea4a 100644 --- a/local-cli/link/pods/addPodEntry.js +++ b/local-cli/link/pods/addPodEntry.js @@ -3,21 +3,28 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; -module.exports = function addPodEntry(podLines, linesToAddEntry, podName, nodePath) { +module.exports = function addPodEntry( + podLines, + linesToAddEntry, + podName, + nodePath, +) { const newEntry = `pod '${podName}', :path => '../node_modules/${nodePath}'\n`; if (!linesToAddEntry) { return; } else if (Array.isArray(linesToAddEntry)) { - linesToAddEntry.map(({ line, indentation }, idx) => - podLines.splice(line + idx, 0, getLineToAdd(newEntry, indentation)) + linesToAddEntry.map(({line, indentation}, idx) => + podLines.splice(line + idx, 0, getLineToAdd(newEntry, indentation)), ); } else { - const { line, indentation } = linesToAddEntry; + const {line, indentation} = linesToAddEntry; podLines.splice(line, 0, getLineToAdd(newEntry, indentation)); } }; diff --git a/local-cli/link/pods/findLineToAddPod.js b/local-cli/link/pods/findLineToAddPod.js index dca2e391cc4..629296e9f66 100644 --- a/local-cli/link/pods/findLineToAddPod.js +++ b/local-cli/link/pods/findLineToAddPod.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -16,14 +18,15 @@ module.exports = function findLineToAddPod(podLines, firstTargetLine) { const functionDefinition = /^\s*[a-z_]+\s+do(\s+\|[a-z]+\|)?/g; for (let i = firstTargetLine, len = podLines.length; i < len; i++) { - const matchNextConstruct = podLines[i].match(nextTarget) || podLines[i].match(functionDefinition); + const matchNextConstruct = + podLines[i].match(nextTarget) || podLines[i].match(functionDefinition); const matchEnd = podLines[i].match(endOfCurrentTarget); if (matchNextConstruct || matchEnd) { const firstNonSpaceCharacter = podLines[i].search(/\S/); return { indentation: firstNonSpaceCharacter + (matchEnd ? 2 : 0), - line: i + line: i, }; } } diff --git a/local-cli/link/pods/findMarkedLinesInPodfile.js b/local-cli/link/pods/findMarkedLinesInPodfile.js index 42ef7c8bedd..b58a0d48679 100644 --- a/local-cli/link/pods/findMarkedLinesInPodfile.js +++ b/local-cli/link/pods/findMarkedLinesInPodfile.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -12,7 +14,7 @@ module.exports = function findMarkedLinesInPodfile(podLines) { const result = []; for (let i = 0, len = podLines.length; i < len; i++) { if (podLines[i].includes(MARKER_TEXT)) { - result.push({ line: i + 1, indentation: podLines[i].indexOf('#') }); + result.push({line: i + 1, indentation: podLines[i].indexOf('#')}); } } return result; diff --git a/local-cli/link/pods/findPodTargetLine.js b/local-cli/link/pods/findPodTargetLine.js index d5a8c97fb2b..10617584aff 100644 --- a/local-cli/link/pods/findPodTargetLine.js +++ b/local-cli/link/pods/findPodTargetLine.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -10,7 +12,10 @@ module.exports = function findPodTargetLine(podLines, projectName) { const targetName = projectName.replace('.xcodeproj', ''); //match first target definition in file: target 'target_name' do - const targetRegex = new RegExp('target (\'|\")' + targetName + '(\'|\") do', 'g'); + const targetRegex = new RegExp( + 'target (\'|")' + targetName + '(\'|") do', + 'g', + ); for (let i = 0, len = podLines.length; i < len; i++) { const match = podLines[i].match(targetRegex); if (match) { diff --git a/local-cli/link/pods/isInstalled.js b/local-cli/link/pods/isInstalled.js index 251376541d1..7f5d773d8a8 100644 --- a/local-cli/link/pods/isInstalled.js +++ b/local-cli/link/pods/isInstalled.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -14,7 +16,10 @@ module.exports = function isInstalled(iOSProject, dependencyConfig) { return false; } // match line with pod declaration: pod 'dependencyPodName' (other possible parameters of pod are ignored) - const dependencyRegExp = new RegExp('pod\\s+(\'|\")' + dependencyConfig.podspec + '(\'|\")', 'g'); + const dependencyRegExp = new RegExp( + 'pod\\s+(\'|")' + dependencyConfig.podspec + '(\'|")', + 'g', + ); const podLines = readPodfile(iOSProject.podfile); for (let i = 0, len = podLines.length; i < len; i++) { const match = podLines[i].match(dependencyRegExp); diff --git a/local-cli/link/pods/readPodfile.js b/local-cli/link/pods/readPodfile.js index 85ac7ed9bf3..f70609628f2 100644 --- a/local-cli/link/pods/readPodfile.js +++ b/local-cli/link/pods/readPodfile.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; diff --git a/local-cli/link/pods/registerNativeModule.js b/local-cli/link/pods/registerNativeModule.js index b00d93c6f2d..8ae16a30598 100644 --- a/local-cli/link/pods/registerNativeModule.js +++ b/local-cli/link/pods/registerNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -14,14 +16,18 @@ const findMarkedLinesInPodfile = require('./findMarkedLinesInPodfile'); const addPodEntry = require('./addPodEntry'); const savePodFile = require('./savePodFile'); -module.exports = function registerNativeModulePods(name, dependencyConfig, iOSProject) { +module.exports = function registerNativeModulePods( + name, + dependencyConfig, + iOSProject, +) { const podLines = readPodfile(iOSProject.podfile); const linesToAddEntry = getLinesToAddEntry(podLines, iOSProject); addPodEntry(podLines, linesToAddEntry, dependencyConfig.podspec, name); savePodFile(iOSProject.podfile, podLines); }; -function getLinesToAddEntry(podLines, { projectName }) { +function getLinesToAddEntry(podLines, {projectName}) { const linesToAddPodWithMarker = findMarkedLinesInPodfile(podLines); if (linesToAddPodWithMarker.length > 0) { return linesToAddPodWithMarker; diff --git a/local-cli/link/pods/removePodEntry.js b/local-cli/link/pods/removePodEntry.js index 8af044734d3..83f063ad289 100644 --- a/local-cli/link/pods/removePodEntry.js +++ b/local-cli/link/pods/removePodEntry.js @@ -3,12 +3,19 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; module.exports = function removePodEntry(podfileContent, podName) { // this regex should catch line(s) with full pod definition, like: pod 'podname', :path => '../node_modules/podname', :subspecs => ['Sub2', 'Sub1'] - const podRegex = new RegExp("\\n( |\\t)*pod\\s+(\"|')" + podName + "(\"|')(,\\s*(:[a-z]+\\s*=>)?\\s*((\"|').*?(\"|')|\\[[\\s\\S]*?\\]))*\\n", 'g'); + const podRegex = new RegExp( + '\\n( |\\t)*pod\\s+("|\')' + + podName + + '("|\')(,\\s*(:[a-z]+\\s*=>)?\\s*(("|\').*?("|\')|\\[[\\s\\S]*?\\]))*\\n', + 'g', + ); return podfileContent.replace(podRegex, '\n'); }; diff --git a/local-cli/link/pods/savePodFile.js b/local-cli/link/pods/savePodFile.js index 5572311105d..e050c822c05 100644 --- a/local-cli/link/pods/savePodFile.js +++ b/local-cli/link/pods/savePodFile.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; diff --git a/local-cli/link/pods/unregisterNativeModule.js b/local-cli/link/pods/unregisterNativeModule.js index 3b2408bf992..539e0389a5d 100644 --- a/local-cli/link/pods/unregisterNativeModule.js +++ b/local-cli/link/pods/unregisterNativeModule.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; @@ -14,7 +16,7 @@ const removePodEntry = require('./removePodEntry'); * Unregister native module IOS with CocoaPods */ module.exports = function unregisterNativeModule(dependencyConfig, iOSProject) { - const podContent = fs.readFileSync(iOSProject.podfile, 'utf8'); - const removed = removePodEntry(podContent, dependencyConfig.podspec); - fs.writeFileSync(iOSProject.podfile, removed); + const podContent = fs.readFileSync(iOSProject.podfile, 'utf8'); + const removed = removePodEntry(podContent, dependencyConfig.podspec); + fs.writeFileSync(iOSProject.podfile, removed); }; diff --git a/local-cli/link/pollParams.js b/local-cli/link/pollParams.js index 4c084a6d3ff..66aa53e9682 100644 --- a/local-cli/link/pollParams.js +++ b/local-cli/link/pollParams.js @@ -3,14 +3,17 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ var inquirer = require('inquirer'); -module.exports = (questions) => new Promise((resolve, reject) => { - if (!questions) { - return resolve({}); - } +module.exports = questions => + new Promise((resolve, reject) => { + if (!questions) { + return resolve({}); + } - inquirer.prompt(questions).then(resolve, reject); -}); + inquirer.prompt(questions).then(resolve, reject); + }); diff --git a/local-cli/link/promiseWaterfall.js b/local-cli/link/promiseWaterfall.js index fa8b621a9f5..9b6177d6903 100644 --- a/local-cli/link/promiseWaterfall.js +++ b/local-cli/link/promiseWaterfall.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /** @@ -16,6 +18,6 @@ module.exports = function promiseWaterfall(tasks) { return tasks.reduce( (prevTaskPromise, task) => prevTaskPromise.then(task), - Promise.resolve() + Promise.resolve(), ); }; diff --git a/local-cli/link/promisify.js b/local-cli/link/promisify.js index 665b640f216..b99f2f43a0f 100644 --- a/local-cli/link/promisify.js +++ b/local-cli/link/promisify.js @@ -3,8 +3,11 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ -module.exports = (func) => new Promise((resolve, reject) => - func((err, res) => err ? reject(err) : resolve(res)) -); +module.exports = func => + new Promise((resolve, reject) => + func((err, res) => (err ? reject(err) : resolve(res))), + ); diff --git a/local-cli/link/unlink.js b/local-cli/link/unlink.js index 91c89ab7ec0..c886c4f46b7 100644 --- a/local-cli/link/unlink.js +++ b/local-cli/link/unlink.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ const log = require('npmlog'); @@ -19,37 +21,52 @@ const promisify = require('./promisify'); log.heading = 'rnpm-link'; -const unlinkDependency = (platforms, project, dependency, packageName, otherDependencies) => { +const unlinkDependency = ( + platforms, + project, + dependency, + packageName, + otherDependencies, +) => { + Object.keys(platforms || {}).forEach(platform => { + if (!project[platform] || !dependency[platform]) { + return; + } - Object.keys(platforms || {}) - .forEach(platform => { - if (!project[platform] || !dependency[platform]) { - return; - } + const linkConfig = + platforms[platform] && + platforms[platform].linkConfig && + platforms[platform].linkConfig(); + if (!linkConfig || !linkConfig.isInstalled || !linkConfig.unregister) { + return; + } - const linkConfig = platforms[platform] && platforms[platform].linkConfig && platforms[platform].linkConfig(); - if (!linkConfig || !linkConfig.isInstalled || !linkConfig.unregister) { - return; - } + const isInstalled = linkConfig.isInstalled( + project[platform], + packageName, + dependency[platform], + ); - const isInstalled = linkConfig.isInstalled(project[platform], packageName, dependency[platform]); + if (!isInstalled) { + log.info(`Platform '${platform}' module ${packageName} is not installed`); + return; + } - if (!isInstalled) { - log.info(`Platform '${platform}' module ${packageName} is not installed`); - return; - } + log.info(`Unlinking ${packageName} ${platform} dependency`); - log.info(`Unlinking ${packageName} ${platform} dependency`); + linkConfig.unregister( + packageName, + dependency[platform], + project[platform], + otherDependencies, + ); - linkConfig.unregister( - packageName, - dependency[platform], - project[platform], - otherDependencies - ); - - log.info(`Platform '${platform}' module ${dependency.name} has been successfully unlinked`); - }); + log.info( + `Platform '${platform}' module ${ + dependency.name + } has been successfully unlinked`, + ); + }); }; /** @@ -71,7 +88,7 @@ function unlink(args, config) { } catch (err) { log.error( 'ERRPACKAGEJSON', - 'No package found. Are you sure it\'s a React Native project?' + "No package found. Are you sure it's a React Native project?", ); return Promise.reject(err); } @@ -81,18 +98,28 @@ function unlink(args, config) { } catch (err) { log.warn( 'ERRINVALIDPROJ', - `Project ${packageName} is not a react-native library` + `Project ${packageName} is not a react-native library`, ); return Promise.reject(err); } const allDependencies = getDependencyConfig(config, getProjectDependencies()); - const otherDependencies = filter(allDependencies, d => d.name !== packageName); + const otherDependencies = filter( + allDependencies, + d => d.name !== packageName, + ); const tasks = [ () => promisify(dependency.commands.preunlink || commandStub), - () => unlinkDependency(platforms, project, dependency, packageName, otherDependencies), - () => promisify(dependency.commands.postunlink || commandStub) + () => + unlinkDependency( + platforms, + project, + dependency, + packageName, + otherDependencies, + ), + () => promisify(dependency.commands.postunlink || commandStub), ]; return promiseWaterfall(tasks) @@ -101,31 +128,33 @@ function unlink(args, config) { // link const assets = difference( dependency.assets, - flatten(allDependencies, d => d.assets) + flatten(allDependencies, d => d.assets), ); if (isEmpty(assets)) { return Promise.resolve(); } - Object.keys(platforms || {}) - .forEach(platform => { - const linkConfig = platforms[platform] && platforms[platform].linkConfig && platforms[platform].linkConfig(); - if (!linkConfig || !linkConfig.unlinkAssets) { - return; - } + Object.keys(platforms || {}).forEach(platform => { + const linkConfig = + platforms[platform] && + platforms[platform].linkConfig && + platforms[platform].linkConfig(); + if (!linkConfig || !linkConfig.unlinkAssets) { + return; + } - log.info(`Unlinking assets from ${platform} project`); - linkConfig.unlinkAssets(assets, project[platform]); - }); + log.info(`Unlinking assets from ${platform} project`); + linkConfig.unlinkAssets(assets, project[platform]); + }); log.info( - `${packageName} assets has been successfully unlinked from your project` + `${packageName} assets has been successfully unlinked from your project`, ); }) .catch(err => { log.error( - `It seems something went wrong while unlinking. Error: ${err.message}` + `It seems something went wrong while unlinking. Error: ${err.message}`, ); throw err; }); diff --git a/local-cli/logAndroid/logAndroid.js b/local-cli/logAndroid/logAndroid.js index 7a1aace4bf7..b8608e96e40 100644 --- a/local-cli/logAndroid/logAndroid.js +++ b/local-cli/logAndroid/logAndroid.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const chalk = require('chalk'); @@ -26,20 +29,19 @@ function _logAndroid() { const adbArgs = ['logcat', '*:S', 'ReactNative:V', 'ReactNativeJS:V']; - console.log(chalk.bold( - `Starting the logger (${adbPath} ${adbArgs.join(' ')})...` - )); + console.log( + chalk.bold(`Starting the logger (${adbPath} ${adbArgs.join(' ')})...`), + ); const log = child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'}); if (log.error !== null) { throw log.error; } - } catch (e) { - console.log(chalk.red( - 'adb invocation failed. Do you have adb in your PATH?' - )); + console.log( + chalk.red('adb invocation failed. Do you have adb in your PATH?'), + ); return Promise.reject(); } } diff --git a/local-cli/logIOS/logIOS.js b/local-cli/logIOS/logIOS.js index 3e7b1ffb7c2..272dc038260 100644 --- a/local-cli/logIOS/logIOS.js +++ b/local-cli/logIOS/logIOS.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const chalk = require('chalk'); @@ -25,22 +28,24 @@ function _logIOS() { try { rawDevices = child_process.execFileSync( - 'xcrun', ['simctl', 'list', 'devices', '--json'], {encoding: 'utf8'} + 'xcrun', + ['simctl', 'list', 'devices', '--json'], + {encoding: 'utf8'}, ); } catch (e) { - console.log(chalk.red( - 'xcrun invocation failed. Please check that Xcode is installed.' - )); + console.log( + chalk.red( + 'xcrun invocation failed. Please check that Xcode is installed.', + ), + ); return Promise.reject(e); } - const { devices } = JSON.parse(rawDevices); + const {devices} = JSON.parse(rawDevices); const device = _findAvailableDevice(devices); if (device === undefined) { - console.log(chalk.red( - 'No active iOS device found' - )); + console.log(chalk.red('No active iOS device found')); return Promise.reject(); } @@ -67,13 +72,14 @@ function tailDeviceLogs(udid) { 'asl', ); - const log = - child_process.spawnSync('syslog', ['-w', '-F', 'std', '-d', logDir], {stdio: 'inherit'}); + const log = child_process.spawnSync( + 'syslog', + ['-w', '-F', 'std', '-d', logDir], + {stdio: 'inherit'}, + ); if (log.error !== null) { - console.log(chalk.red( - 'syslog invocation failed.' - )); + console.log(chalk.red('syslog invocation failed.')); return Promise.reject(log.error); } } diff --git a/local-cli/runAndroid/adb.js b/local-cli/runAndroid/adb.js index 8206093e3fa..3c6b980d210 100644 --- a/local-cli/runAndroid/adb.js +++ b/local-cli/runAndroid/adb.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -21,7 +22,7 @@ function parseDevicesResult(result: string): Array { const lines = result.trim().split(/\r?\n/); for (let i = 0; i < lines.length; i++) { - let words = lines[i].split(/[ ,\t]+/).filter((w) => w !== ''); + let words = lines[i].split(/[ ,\t]+/).filter(w => w !== ''); if (words[1] === 'device') { devices.push(words[0]); @@ -40,11 +41,9 @@ function getDevices(): Array { } catch (e) { return []; } - - } module.exports = { parseDevicesResult: parseDevicesResult, - getDevices: getDevices + getDevices: getDevices, }; diff --git a/local-cli/runAndroid/runAndroid.js b/local-cli/runAndroid/runAndroid.js index eb17d38210e..234530c1041 100644 --- a/local-cli/runAndroid/runAndroid.js +++ b/local-cli/runAndroid/runAndroid.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const adb = require('./adb'); @@ -31,10 +34,14 @@ function runAndroid(argv, config, args) { child_process.spawnSync( reactNativeScriptsPath, ['android'].concat(process.argv.slice(1)), - {stdio: 'inherit'} + {stdio: 'inherit'}, ); } else { - console.log(chalk.red('Android project not found. Maybe run react-native android first?')); + console.log( + chalk.red( + 'Android project not found. Maybe run react-native android first?', + ), + ); } return; } @@ -47,7 +54,9 @@ function runAndroid(argv, config, args) { if (result === 'running') { console.log(chalk.bold('JS server already running.')); } else if (result === 'unrecognized') { - console.warn(chalk.yellow('JS server not recognized, continuing with build...')); + console.warn( + chalk.yellow('JS server not recognized, continuing with build...'), + ); } else { // result == 'not_running' console.log(chalk.bold('Starting JS server...')); @@ -74,9 +83,7 @@ function tryRunAdbReverse(packagerPort, device) { adbArgs.unshift('-s', device); } - console.log(chalk.bold( - `Running ${adbPath} ${adbArgs.join(' ')}` - )); + console.log(chalk.bold(`Running ${adbPath} ${adbArgs.join(' ')}`)); child_process.execFileSync(adbPath, adbArgs, { stdio: [process.stdin, process.stdout, process.stderr], @@ -99,21 +106,28 @@ function getPackageNameWithSuffix(appId, appIdSuffix, packageName) { // Builds the app and runs it on a connected emulator / device. function buildAndRun(args) { process.chdir(path.join(args.root, 'android')); - const cmd = process.platform.startsWith('win') - ? 'gradlew.bat' - : './gradlew'; + const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew'; - const packageName = fs.readFileSync( - `${args.appFolder}/src/main/AndroidManifest.xml`, - 'utf8' - ).match(/package="(.+?)"/)[1]; + const packageName = fs + .readFileSync(`${args.appFolder}/src/main/AndroidManifest.xml`, 'utf8') + .match(/package="(.+?)"/)[1]; - const packageNameWithSuffix = getPackageNameWithSuffix(args.appId, args.appIdSuffix, packageName); + const packageNameWithSuffix = getPackageNameWithSuffix( + args.appId, + args.appIdSuffix, + packageName, + ); const adbPath = getAdbPath(); if (args.deviceId) { if (isString(args.deviceId)) { - runOnSpecificDevice(args, cmd, packageNameWithSuffix, packageName, adbPath); + runOnSpecificDevice( + args, + cmd, + packageNameWithSuffix, + packageName, + adbPath, + ); } else { console.log(chalk.red('Argument missing for parameter --deviceId')); } @@ -122,14 +136,28 @@ function buildAndRun(args) { } } -function runOnSpecificDevice(args, gradlew, packageNameWithSuffix, packageName, adbPath) { +function runOnSpecificDevice( + args, + gradlew, + packageNameWithSuffix, + packageName, + adbPath, +) { let devices = adb.getDevices(); if (devices && devices.length > 0) { if (devices.indexOf(args.deviceId) !== -1) { buildApk(gradlew); - installAndLaunchOnDevice(args, args.deviceId, packageNameWithSuffix, packageName, adbPath); + installAndLaunchOnDevice( + args, + args.deviceId, + packageNameWithSuffix, + packageName, + adbPath, + ); } else { - console.log('Could not find device with the id: "' + args.deviceId + '".'); + console.log( + 'Could not find device with the id: "' + args.deviceId + '".', + ); console.log('Choose one of the following:'); console.log(devices); } @@ -147,62 +175,104 @@ function buildApk(gradlew) { stdio: [process.stdin, process.stdout, process.stderr], }); } catch (e) { - console.log(chalk.red('Could not build the app, read the error above for details.\n')); + console.log( + chalk.red('Could not build the app, read the error above for details.\n'), + ); } } function tryInstallAppOnDevice(args, device) { try { - const pathToApk = `${args.appFolder}/build/outputs/apk/${args.appFolder}-debug.apk`; + const pathToApk = `${args.appFolder}/build/outputs/apk/${ + args.appFolder + }-debug.apk`; const adbPath = getAdbPath(); const adbArgs = ['-s', device, 'install', pathToApk]; - console.log(chalk.bold( - `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}` - )); + console.log( + chalk.bold( + `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`, + ), + ); child_process.execFileSync(adbPath, adbArgs, { stdio: [process.stdin, process.stdout, process.stderr], }); } catch (e) { console.log(e.message); - console.log(chalk.red( - 'Could not install the app on the device, read the error above for details.\n' - )); + console.log( + chalk.red( + 'Could not install the app on the device, read the error above for details.\n', + ), + ); } } -function tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, mainActivity) { +function tryLaunchAppOnDevice( + device, + packageNameWithSuffix, + packageName, + adbPath, + mainActivity, +) { try { - const adbArgs = ['-s', device, 'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.' + mainActivity]; - console.log(chalk.bold( - `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...` - )); + const adbArgs = [ + '-s', + device, + 'shell', + 'am', + 'start', + '-n', + packageNameWithSuffix + '/' + packageName + '.' + mainActivity, + ]; + console.log( + chalk.bold( + `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`, + ), + ); child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'}); } catch (e) { - console.log(chalk.red( - 'adb invocation failed. Do you have adb in your PATH?' - )); + console.log( + chalk.red('adb invocation failed. Do you have adb in your PATH?'), + ); } } -function installAndLaunchOnDevice(args, selectedDevice, packageNameWithSuffix, packageName, adbPath) { +function installAndLaunchOnDevice( + args, + selectedDevice, + packageNameWithSuffix, + packageName, + adbPath, +) { tryRunAdbReverse(args.port, selectedDevice); tryInstallAppOnDevice(args, selectedDevice); - tryLaunchAppOnDevice(selectedDevice, packageNameWithSuffix, packageName, adbPath, args.mainActivity); + tryLaunchAppOnDevice( + selectedDevice, + packageNameWithSuffix, + packageName, + adbPath, + args.mainActivity, + ); } -function runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath){ +function runOnAllDevices( + args, + cmd, + packageNameWithSuffix, + packageName, + adbPath, +) { try { const gradleArgs = []; if (args.variant) { - gradleArgs.push('install' + - args.variant[0].toUpperCase() + args.variant.slice(1) + gradleArgs.push( + 'install' + args.variant[0].toUpperCase() + args.variant.slice(1), ); } else if (args.flavor) { - console.warn(chalk.yellow( - '--flavor has been deprecated. Use --variant instead' - )); - gradleArgs.push('install' + - args.flavor[0].toUpperCase() + args.flavor.slice(1) + console.warn( + chalk.yellow('--flavor has been deprecated. Use --variant instead'), + ); + gradleArgs.push( + 'install' + args.flavor[0].toUpperCase() + args.flavor.slice(1), ); } else { gradleArgs.push('installDebug'); @@ -212,132 +282,186 @@ function runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath) gradleArgs.push(args.installDebug); } - console.log(chalk.bold( - `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join(' ')})...` - )); + console.log( + chalk.bold( + `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join( + ' ', + )})...`, + ), + ); child_process.execFileSync(cmd, gradleArgs, { stdio: [process.stdin, process.stdout, process.stderr], }); } catch (e) { - console.log(chalk.red( - 'Could not install the app on the device, read the error above for details.\n' + - 'Make sure you have an Android emulator running or a device connected and have\n' + - 'set up your Android development environment:\n' + - 'https://facebook.github.io/react-native/docs/getting-started.html' - )); + console.log( + chalk.red( + 'Could not install the app on the device, read the error above for details.\n' + + 'Make sure you have an Android emulator running or a device connected and have\n' + + 'set up your Android development environment:\n' + + 'https://facebook.github.io/react-native/docs/getting-started.html', + ), + ); // stderr is automatically piped from the gradle process, so the user // should see the error already, there is no need to do // `console.log(e.stderr)` return Promise.reject(); } - const devices = adb.getDevices(); - if (devices && devices.length > 0) { - devices.forEach((device) => { - tryRunAdbReverse(args.port, device); - tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, args.mainActivity); - }); - } else { - try { - // If we cannot execute based on adb devices output, fall back to - // shell am start - const fallbackAdbArgs = [ - 'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.MainActivity' - ]; - console.log(chalk.bold( - `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...` - )); - child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'}); - } catch (e) { - console.log(chalk.red( - 'adb invocation failed. Do you have adb in your PATH?' - )); - // stderr is automatically piped from the gradle process, so the user - // should see the error already, there is no need to do - // `console.log(e.stderr)` - return Promise.reject(); - } + const devices = adb.getDevices(); + if (devices && devices.length > 0) { + devices.forEach(device => { + tryRunAdbReverse(args.port, device); + tryLaunchAppOnDevice( + device, + packageNameWithSuffix, + packageName, + adbPath, + args.mainActivity, + ); + }); + } else { + try { + // If we cannot execute based on adb devices output, fall back to + // shell am start + const fallbackAdbArgs = [ + 'shell', + 'am', + 'start', + '-n', + packageNameWithSuffix + '/' + packageName + '.MainActivity', + ]; + console.log( + chalk.bold( + `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`, + ), + ); + child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'}); + } catch (e) { + console.log( + chalk.red('adb invocation failed. Do you have adb in your PATH?'), + ); + // stderr is automatically piped from the gradle process, so the user + // should see the error already, there is no need to do + // `console.log(e.stderr)` + return Promise.reject(); } + } } function startServerInNewWindow(port) { - const scriptFile = /^win/.test(process.platform) ? - 'launchPackager.bat' : - 'launchPackager.command'; + const scriptFile = /^win/.test(process.platform) + ? 'launchPackager.bat' + : 'launchPackager.command'; const scriptsDir = path.resolve(__dirname, '..', '..', 'scripts'); const launchPackagerScript = path.resolve(scriptsDir, scriptFile); const procConfig = {cwd: scriptsDir}; const terminal = process.env.REACT_TERMINAL; // setup the .packager.env file to ensure the packager starts on the right port - const packagerEnvFile = path.join(__dirname, '..', '..', 'scripts', '.packager.env'); + const packagerEnvFile = path.join( + __dirname, + '..', + '..', + 'scripts', + '.packager.env', + ); const content = `export RCT_METRO_PORT=${port}`; // ensure we overwrite file by passing the 'w' flag fs.writeFileSync(packagerEnvFile, content, {encoding: 'utf8', flag: 'w'}); if (process.platform === 'darwin') { if (terminal) { - return child_process.spawnSync('open', ['-a', terminal, launchPackagerScript], procConfig); + return child_process.spawnSync( + 'open', + ['-a', terminal, launchPackagerScript], + procConfig, + ); } return child_process.spawnSync('open', [launchPackagerScript], procConfig); - } else if (process.platform === 'linux') { procConfig.detached = true; - if (terminal){ - return child_process.spawn(terminal, ['-e', 'sh ' + launchPackagerScript], procConfig); + if (terminal) { + return child_process.spawn( + terminal, + ['-e', 'sh ' + launchPackagerScript], + procConfig, + ); } return child_process.spawn('sh', [launchPackagerScript], procConfig); - } else if (/^win/.test(process.platform)) { procConfig.detached = true; procConfig.stdio = 'ignore'; - return child_process.spawn('cmd.exe', ['/C', launchPackagerScript], procConfig); + return child_process.spawn( + 'cmd.exe', + ['/C', launchPackagerScript], + procConfig, + ); } else { - console.log(chalk.red(`Cannot start the packager. Unknown platform ${process.platform}`)); + console.log( + chalk.red( + `Cannot start the packager. Unknown platform ${process.platform}`, + ), + ); } } module.exports = { name: 'run-android', - description: 'builds your app and starts it on a connected Android emulator or device', + description: + 'builds your app and starts it on a connected Android emulator or device', func: runAndroid, - options: [{ - command: '--install-debug', - }, { - command: '--root [string]', - description: 'Override the root directory for the android build (which contains the android directory)', - default: '', - }, { - command: '--flavor [string]', - description: '--flavor has been deprecated. Use --variant instead', - }, { - command: '--variant [string]', - }, { - command: '--appFolder [string]', - description: 'Specify a different application folder name for the android source.', - default: 'app', - }, { - command: '--appId [string]', - description: 'Specify an applicationId to launch after build.', - default: '', - }, { - command: '--appIdSuffix [string]', - description: 'Specify an applicationIdSuffix to launch after build.', - default: '', - }, { - command: '--main-activity [string]', - description: 'Name of the activity to start', - default: 'MainActivity', - }, { - command: '--deviceId [string]', - description: 'builds your app and starts it on a specific device/simulator with the ' + - 'given device id (listed by running "adb devices" on the command line).', - }, { - command: '--no-packager', - description: 'Do not launch packager while building', - }, { - command: '--port [number]', - default: process.env.RCT_METRO_PORT || 8081, - parse: (val: string) => Number(val), - }], + options: [ + { + command: '--install-debug', + }, + { + command: '--root [string]', + description: + 'Override the root directory for the android build (which contains the android directory)', + default: '', + }, + { + command: '--flavor [string]', + description: '--flavor has been deprecated. Use --variant instead', + }, + { + command: '--variant [string]', + }, + { + command: '--appFolder [string]', + description: + 'Specify a different application folder name for the android source.', + default: 'app', + }, + { + command: '--appId [string]', + description: 'Specify an applicationId to launch after build.', + default: '', + }, + { + command: '--appIdSuffix [string]', + description: 'Specify an applicationIdSuffix to launch after build.', + default: '', + }, + { + command: '--main-activity [string]', + description: 'Name of the activity to start', + default: 'MainActivity', + }, + { + command: '--deviceId [string]', + description: + 'builds your app and starts it on a specific device/simulator with the ' + + 'given device id (listed by running "adb devices" on the command line).', + }, + { + command: '--no-packager', + description: 'Do not launch packager while building', + }, + { + command: '--port [number]', + default: process.env.RCT_METRO_PORT || 8081, + parse: (val: string) => Number(val), + }, + ], }; diff --git a/local-cli/runIOS/__tests__/findMatchingSimulator-test.js b/local-cli/runIOS/__tests__/findMatchingSimulator-test.js index fb3ffddcbe8..3c59b06839a 100644 --- a/local-cli/runIOS/__tests__/findMatchingSimulator-test.js +++ b/local-cli/runIOS/__tests__/findMatchingSimulator-test.js @@ -5,8 +5,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ + 'use strict'; jest.dontMock('../findMatchingSimulator'); @@ -15,481 +17,510 @@ const findMatchingSimulator = require('../findMatchingSimulator'); describe('findMatchingSimulator', () => { it('should find simulator', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ] - } - }, - 'iPhone 6' - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + }, + }, + 'iPhone 6', + ), + ).toEqual({ udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', name: 'iPhone 6', booted: false, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return null if no simulators available', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ] - } - }, - 'iPhone 6' - )).toEqual(null); + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + }, + }, + 'iPhone 6', + ), + ).toEqual(null); }); it('should return null if an odd input', () => { - expect(findMatchingSimulator('random string input', 'iPhone 6')).toEqual(null); + expect(findMatchingSimulator('random string input', 'iPhone 6')).toEqual( + null, + ); }); it('should return the first simulator in list if none is defined', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ] - } - }, - null - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + }, + }, + null, + ), + ).toEqual({ udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', name: 'iPhone 5', booted: false, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return the first simulator in list if none is defined', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ], - 'iOS 10.0': [ - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 7', - 'udid': '3A409DC5-5188-42A6-8598-3AA6F34607A5' - } - ] - } - }, - null - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + 'iOS 10.0': [ + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 7', + udid: '3A409DC5-5188-42A6-8598-3AA6F34607A5', + }, + ], + }, + }, + null, + ), + ).toEqual({ udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', name: 'iPhone 5', booted: false, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return the booted simulator in list if none is defined', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Booted', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ] - } - }, - null - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Booted', + availability: '(available)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + }, + }, + null, + ), + ).toEqual({ udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', name: 'iPhone 6s', booted: true, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return the defined simulator in list even if another device is booted', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Booted', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ] - } - }, - 'iPhone 6' - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Booted', + availability: '(available)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + }, + }, + 'iPhone 6', + ), + ).toEqual({ udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', name: 'iPhone 6', booted: false, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return the booted simulator in list if none is defined (multi ios versions)', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ], - 'iOS 10.0': [ - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22' - }, - { - 'state': 'Booted', - 'availability': '(available)', - 'name': 'iPhone 7', - 'udid': '3A409DC5-5188-42A6-8598-3AA6F34607A5' - } - ] - } - }, - null - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + 'iOS 10.0': [ + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22', + }, + { + state: 'Booted', + availability: '(available)', + name: 'iPhone 7', + udid: '3A409DC5-5188-42A6-8598-3AA6F34607A5', + }, + ], + }, + }, + null, + ), + ).toEqual({ udid: '3A409DC5-5188-42A6-8598-3AA6F34607A5', name: 'iPhone 7', booted: true, - version: 'iOS 10.0' + version: 'iOS 10.0', }); }); it('should return the defined simulator in list even if another device is booted (multi ios versions)', () => { - expect(findMatchingSimulator({ - 'devices': { - 'iOS 9.2': [ - { - 'state': 'Shutdown', - 'availability': '(unavailable, runtime profile not found)', - 'name': 'iPhone 4s', - 'udid': 'B9B5E161-416B-43C4-A78F-729CB96CC8C6' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 5', - 'udid': '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': 'BA0D93BD-07E6-4182-9B0A-F60A2474139C' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '9564ABEE-9EC2-4B4A-B443-D3710929A45A' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'D0F29BE7-CC3C-4976-888D-C739B4F50508' - } - ], - 'iOS 10.0': [ - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6', - 'udid': '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6 (Plus)', - 'udid': '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC' - }, - { - 'state': 'Shutdown', - 'availability': '(available)', - 'name': 'iPhone 6s', - 'udid': 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22' - }, - { - 'state': 'Booted', - 'availability': '(available)', - 'name': 'iPhone 7', - 'udid': '3A409DC5-5188-42A6-8598-3AA6F34607A5' - } - ] - } - }, - 'iPhone 6s' - )).toEqual({ + expect( + findMatchingSimulator( + { + devices: { + 'iOS 9.2': [ + { + state: 'Shutdown', + availability: '(unavailable, runtime profile not found)', + name: 'iPhone 4s', + udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 5', + udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', + }, + ], + 'iOS 10.0': [ + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6', + udid: '2FF48AE5-CC3B-4C80-8D25-48966A6BE2C0', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6 (Plus)', + udid: '841E33FE-E8A1-4B65-9FF8-6EAA6442A3FC', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'iPhone 6s', + udid: 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22', + }, + { + state: 'Booted', + availability: '(available)', + name: 'iPhone 7', + udid: '3A409DC5-5188-42A6-8598-3AA6F34607A5', + }, + ], + }, + }, + 'iPhone 6s', + ), + ).toEqual({ udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', name: 'iPhone 6s', booted: false, - version: 'iOS 9.2' + version: 'iOS 9.2', }); }); it('should return AppleTV devices if in the list', () => { - expect(findMatchingSimulator({ - 'devices': { - 'tvOS 11.2' : [ - { - 'state' : 'Booted', - 'availability' : '(available)', - 'name' : 'Apple TV', - 'udid' : '816C30EA-38EA-41AC-BFDA-96FB632D522E' + expect( + findMatchingSimulator( + { + devices: { + 'tvOS 11.2': [ + { + state: 'Booted', + availability: '(available)', + name: 'Apple TV', + udid: '816C30EA-38EA-41AC-BFDA-96FB632D522E', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'Apple TV 4K', + udid: 'BCBB7E4B-D872-4D61-BC61-7C9805551075', + }, + { + state: 'Shutdown', + availability: '(available)', + name: 'Apple TV 4K (at 1080p)', + udid: '1DE12308-1C14-4F0F-991E-A3ADC41BDFFC', + }, + ], }, - { - 'state' : 'Shutdown', - 'availability' : '(available)', - 'name' : 'Apple TV 4K', - 'udid' : 'BCBB7E4B-D872-4D61-BC61-7C9805551075' - }, - { - 'state' : 'Shutdown', - 'availability' : '(available)', - 'name' : 'Apple TV 4K (at 1080p)', - 'udid' : '1DE12308-1C14-4F0F-991E-A3ADC41BDFFC' - } - ] - } - }, - 'Apple TV' - )).toEqual({ - udid: '816C30EA-38EA-41AC-BFDA-96FB632D522E', - name: 'Apple TV', - booted: true, - version: 'tvOS 11.2' - }); + }, + 'Apple TV', + ), + ).toEqual({ + udid: '816C30EA-38EA-41AC-BFDA-96FB632D522E', + name: 'Apple TV', + booted: true, + version: 'tvOS 11.2', + }); }); }); diff --git a/local-cli/runIOS/__tests__/findXcodeProject-test.js b/local-cli/runIOS/__tests__/findXcodeProject-test.js index 305605feab2..7e63560b2b2 100644 --- a/local-cli/runIOS/__tests__/findXcodeProject-test.js +++ b/local-cli/runIOS/__tests__/findXcodeProject-test.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ + 'use strict'; jest.dontMock('../findXcodeProject'); @@ -14,44 +16,50 @@ const findXcodeProject = require('../findXcodeProject'); describe('findXcodeProject', () => { it('should find *.xcodeproj file', () => { - expect(findXcodeProject([ - '.DS_Store', - 'AwesomeApp', - 'AwesomeApp.xcodeproj', - 'AwesomeAppTests', - 'PodFile', - 'Podfile.lock', - 'Pods' - ])).toEqual({ + expect( + findXcodeProject([ + '.DS_Store', + 'AwesomeApp', + 'AwesomeApp.xcodeproj', + 'AwesomeAppTests', + 'PodFile', + 'Podfile.lock', + 'Pods', + ]), + ).toEqual({ name: 'AwesomeApp.xcodeproj', isWorkspace: false, }); }); it('should prefer *.xcworkspace', () => { - expect(findXcodeProject([ - '.DS_Store', - 'AwesomeApp', - 'AwesomeApp.xcodeproj', - 'AwesomeApp.xcworkspace', - 'AwesomeAppTests', - 'PodFile', - 'Podfile.lock', - 'Pods' - ])).toEqual({ + expect( + findXcodeProject([ + '.DS_Store', + 'AwesomeApp', + 'AwesomeApp.xcodeproj', + 'AwesomeApp.xcworkspace', + 'AwesomeAppTests', + 'PodFile', + 'Podfile.lock', + 'Pods', + ]), + ).toEqual({ name: 'AwesomeApp.xcworkspace', isWorkspace: true, }); }); it('should return null if nothing found', () => { - expect(findXcodeProject([ - '.DS_Store', - 'AwesomeApp', - 'AwesomeAppTests', - 'PodFile', - 'Podfile.lock', - 'Pods' - ])).toEqual(null); + expect( + findXcodeProject([ + '.DS_Store', + 'AwesomeApp', + 'AwesomeAppTests', + 'PodFile', + 'Podfile.lock', + 'Pods', + ]), + ).toEqual(null); }); }); diff --git a/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js b/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js index aea241c8fe3..89fca8364ac 100644 --- a/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js +++ b/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @emails oncall+javascript_foundation */ @@ -14,26 +15,34 @@ var parseIOSDevicesList = require('../parseIOSDevicesList'); describe('parseIOSDevicesList', () => { it('parses typical output', () => { - var devices = parseIOSDevicesList([ - 'Known Devices:', - 'Maxs MacBook Pro [11111111-1111-1111-1111-111111111111]', - "Max's iPhone (9.2) [11111111111111111111aaaaaaaaaaaaaaaaaaaa]", - 'iPad 2 (9.3) [07538CE4-675B-4EDA-90F2-3DD3CD93309D] (Simulator)', - 'iPad Air (9.3) [0745F6D1-6DC5-4427-B9A6-6FBA327ED65A] (Simulator)', - 'iPhone 6s (9.3) [3DBE4ECF-9A86-469E-921B-EE0F9C9AB8F4] (Simulator)', - 'Known Templates:', - 'Activity Monitor', - 'Blank', - 'System Usage', - 'Zombies' - ].join('\n')); + var devices = parseIOSDevicesList( + [ + 'Known Devices:', + 'Maxs MacBook Pro [11111111-1111-1111-1111-111111111111]', + "Max's iPhone (9.2) [11111111111111111111aaaaaaaaaaaaaaaaaaaa]", + 'iPad 2 (9.3) [07538CE4-675B-4EDA-90F2-3DD3CD93309D] (Simulator)', + 'iPad Air (9.3) [0745F6D1-6DC5-4427-B9A6-6FBA327ED65A] (Simulator)', + 'iPhone 6s (9.3) [3DBE4ECF-9A86-469E-921B-EE0F9C9AB8F4] (Simulator)', + 'Known Templates:', + 'Activity Monitor', + 'Blank', + 'System Usage', + 'Zombies', + ].join('\n'), + ); expect(devices).toEqual([ - {name: "Max's iPhone", udid: '11111111111111111111aaaaaaaaaaaaaaaaaaaa', version: '9.2'}, + { + name: "Max's iPhone", + udid: '11111111111111111111aaaaaaaaaaaaaaaaaaaa', + version: '9.2', + }, ]); }); it('ignores garbage', () => { - expect(parseIOSDevicesList('Something went terribly wrong (-42)')).toEqual([]); + expect(parseIOSDevicesList('Something went terribly wrong (-42)')).toEqual( + [], + ); }); }); diff --git a/local-cli/runIOS/findMatchingSimulator.js b/local-cli/runIOS/findMatchingSimulator.js index 8b964ec7dba..f4794c389f1 100644 --- a/local-cli/runIOS/findMatchingSimulator.js +++ b/local-cli/runIOS/findMatchingSimulator.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; /** @@ -40,7 +43,7 @@ function findMatchingSimulator(simulators, simulatorName) { udid: simulator.udid, name: simulator.name, booted, - version + version, }; } if (simulator.name === simulatorName && !match) { @@ -48,7 +51,7 @@ function findMatchingSimulator(simulators, simulatorName) { udid: simulator.udid, name: simulator.name, booted, - version + version, }; } // Keeps track of the first available simulator for use if we can't find one above. @@ -57,7 +60,7 @@ function findMatchingSimulator(simulators, simulatorName) { udid: simulator.udid, name: simulator.name, booted, - version + version, }; } } diff --git a/local-cli/runIOS/findXcodeProject.js b/local-cli/runIOS/findXcodeProject.js index ecb80b3d3da..c154221b86c 100644 --- a/local-cli/runIOS/findXcodeProject.js +++ b/local-cli/runIOS/findXcodeProject.js @@ -4,16 +4,18 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; const path = require('path'); type ProjectInfo = { - name: string; - isWorkspace: boolean; -} + name: string, + isWorkspace: boolean, +}; function findXcodeProject(files: Array): ?ProjectInfo { const sortedFiles = files.sort(); diff --git a/local-cli/runIOS/parseIOSDevicesList.js b/local-cli/runIOS/parseIOSDevicesList.js index d0c10a3a5ea..a85ea352f88 100644 --- a/local-cli/runIOS/parseIOSDevicesList.js +++ b/local-cli/runIOS/parseIOSDevicesList.js @@ -4,25 +4,27 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; type IOSDeviceInfo = { - name: string; - udid: string; - version: string; -} + name: string, + udid: string, + version: string, +}; /** * Parses the output of `xcrun simctl list devices` command */ function parseIOSDevicesList(text: string): Array { const devices = []; - text.split('\n').forEach((line) => { + text.split('\n').forEach(line => { const device = line.match(/(.*?) \((.*?)\) \[(.*?)\]/); const noSimulator = line.match(/(.*?) \((.*?)\) \[(.*?)\] \((.*?)\)/); - if (device != null && noSimulator == null){ + if (device != null && noSimulator == null) { var name = device[1]; var version = device[2]; var udid = device[3]; diff --git a/local-cli/runIOS/runIOS.js b/local-cli/runIOS/runIOS.js index 61b6795d5ab..f78700fffbc 100644 --- a/local-cli/runIOS/runIOS.js +++ b/local-cli/runIOS/runIOS.js @@ -1,9 +1,12 @@ /** -* Copyright (c) 2015-present, Facebook, Inc. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + 'use strict'; const child_process = require('child_process'); @@ -13,7 +16,7 @@ const findXcodeProject = require('./findXcodeProject'); const findReactNativeScripts = require('../util/findReactNativeScripts'); const parseIOSDevicesList = require('./parseIOSDevicesList'); const findMatchingSimulator = require('./findMatchingSimulator'); -const getBuildPath = function (configuration = 'Debug', appName, isDevice) { +const getBuildPath = function(configuration = 'Debug', appName, isDevice) { let device; if (isDevice) { @@ -29,7 +32,7 @@ const getBuildPath = function (configuration = 'Debug', appName, isDevice) { const xcprettyAvailable = function() { try { child_process.execSync('xcpretty --version', { - stdio: [ 0, 'pipe', 'ignore', ] + stdio: [0, 'pipe', 'ignore'], }); } catch (error) { return false; @@ -44,11 +47,13 @@ function runIOS(argv, config, args) { child_process.spawnSync( reactNativeScriptsPath, ['ios'].concat(process.argv.slice(1)), - {stdio: 'inherit'} + {stdio: 'inherit'}, ); return; } else { - throw new Error('iOS project folder not found. Are you sure this is a React Native project?'); + throw new Error( + 'iOS project folder not found. Are you sure this is a React Native project?', + ); } } process.chdir(args.projectPath); @@ -57,19 +62,38 @@ function runIOS(argv, config, args) { throw new Error('Could not find Xcode project files in ios folder'); } - const inferredSchemeName = path.basename(xcodeProject.name, path.extname(xcodeProject.name)); + const inferredSchemeName = path.basename( + xcodeProject.name, + path.extname(xcodeProject.name), + ); const scheme = args.scheme || inferredSchemeName; - console.log(`Found Xcode ${xcodeProject.isWorkspace ? 'workspace' : 'project'} ${xcodeProject.name}`); + console.log( + `Found Xcode ${xcodeProject.isWorkspace ? 'workspace' : 'project'} ${ + xcodeProject.name + }`, + ); const devices = parseIOSDevicesList( - child_process.execFileSync('xcrun', ['instruments', '-s'], {encoding: 'utf8'}) + child_process.execFileSync('xcrun', ['instruments', '-s'], { + encoding: 'utf8', + }), ); if (args.device) { const selectedDevice = matchingDevice(devices, args.device); if (selectedDevice) { - return runOnDevice(selectedDevice, scheme, xcodeProject, args.configuration, args.packager, args.verbose, args.port); + return runOnDevice( + selectedDevice, + scheme, + xcodeProject, + args.configuration, + args.packager, + args.verbose, + args.port, + ); } else { if (devices && devices.length > 0) { - console.log('Could not find device with the name: "' + args.device + '".'); + console.log( + 'Could not find device with the name: "' + args.device + '".', + ); console.log('Choose one of the following:'); printFoundDevices(devices); } else { @@ -86,7 +110,15 @@ function runIOS(argv, config, args) { function runOnDeviceByUdid(args, scheme, xcodeProject, devices) { const selectedDevice = matchingDeviceByUdid(devices, args.udid); if (selectedDevice) { - return runOnDevice(selectedDevice, scheme, xcodeProject, args.configuration, args.packager, args.verbose, args.port); + return runOnDevice( + selectedDevice, + scheme, + xcodeProject, + args.configuration, + args.packager, + args.verbose, + args.port, + ); } else { if (devices && devices.length > 0) { console.log('Could not find device with the udid: "' + args.udid + '".'); @@ -99,10 +131,14 @@ function runOnDeviceByUdid(args, scheme, xcodeProject, devices) { } function runOnSimulator(xcodeProject, args, scheme) { - return new Promise((resolve) => { + return new Promise(resolve => { try { var simulators = JSON.parse( - child_process.execFileSync('xcrun', ['simctl', 'list', '--json', 'devices'], {encoding: 'utf8'}) + child_process.execFileSync( + 'xcrun', + ['simctl', 'list', '--json', 'devices'], + {encoding: 'utf8'}, + ), ); } catch (e) { throw new Error('Could not parse the simulator list output'); @@ -112,71 +148,110 @@ function runOnSimulator(xcodeProject, args, scheme) { if (!selectedSimulator) { throw new Error(`Could not find ${args.simulator} simulator`); } - + /** - * Booting simulator through `xcrun simctl boot` will boot it in the `headless` mode - * (running in the background). - * - * In order for user to see the app and the simulator itself, we have to make sure - * that the Simulator.app is running. - * - * We also pass it `-CurrentDeviceUDID` so that when we launch it for the first time, - * it will not boot the "default" device, but the one we set. If the app is already running, - * this flag has no effect. - */ - child_process.execFileSync('open', [ - '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app', - '--args', - '-CurrentDeviceUDID', - selectedSimulator.udid - ]); + * Booting simulator through `xcrun simctl boot` will boot it in the `headless` mode + * (running in the background). + * + * In order for user to see the app and the simulator itself, we have to make sure + * that the Simulator.app is running. + * + * We also pass it `-CurrentDeviceUDID` so that when we launch it for the first time, + * it will not boot the "default" device, but the one we set. If the app is already running, + * this flag has no effect. + */ + child_process.execFileSync('open', [ + '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app', + '--args', + '-CurrentDeviceUDID', + selectedSimulator.udid, + ]); if (!selectedSimulator.booted) { const simulatorFullName = formattedDeviceName(selectedSimulator); console.log(`Launching ${simulatorFullName}...`); try { - child_process.spawnSync('xcrun', ['instruments', '-w', selectedSimulator.udid]); + child_process.spawnSync('xcrun', [ + 'instruments', + '-w', + selectedSimulator.udid, + ]); } catch (e) { // instruments always fail with 255 because it expects more arguments, // but we want it to only launch the simulator } } - buildProject(xcodeProject, selectedSimulator.udid, scheme, args.configuration, args.packager, args.verbose, args.port) - .then((appName) => resolve({ udid: selectedSimulator.udid, appName })); - }) - .then(({udid, appName}) => { + buildProject( + xcodeProject, + selectedSimulator.udid, + scheme, + args.configuration, + args.packager, + args.verbose, + args.port, + ).then(appName => resolve({udid: selectedSimulator.udid, appName})); + }).then(({udid, appName}) => { if (!appName) { appName = scheme; } let appPath = getBuildPath(args.configuration, appName); console.log(`Installing ${appPath}`); - child_process.spawnSync('xcrun', ['simctl', 'install', udid, appPath], {stdio: 'inherit'}); + child_process.spawnSync('xcrun', ['simctl', 'install', udid, appPath], { + stdio: 'inherit', + }); - const bundleID = child_process.execFileSync( - '/usr/libexec/PlistBuddy', - ['-c', 'Print:CFBundleIdentifier', path.join(appPath, 'Info.plist')], - {encoding: 'utf8'} - ).trim(); + const bundleID = child_process + .execFileSync( + '/usr/libexec/PlistBuddy', + ['-c', 'Print:CFBundleIdentifier', path.join(appPath, 'Info.plist')], + {encoding: 'utf8'}, + ) + .trim(); console.log(`Launching ${bundleID}`); - child_process.spawnSync('xcrun', ['simctl', 'launch', udid, bundleID], {stdio: 'inherit'}); + child_process.spawnSync('xcrun', ['simctl', 'launch', udid, bundleID], { + stdio: 'inherit', + }); }); } -function runOnDevice(selectedDevice, scheme, xcodeProject, configuration, launchPackager, verbose, port) { - return buildProject(xcodeProject, selectedDevice.udid, scheme, configuration, launchPackager, verbose, port) - .then((appName) => { +function runOnDevice( + selectedDevice, + scheme, + xcodeProject, + configuration, + launchPackager, + verbose, + port, +) { + return buildProject( + xcodeProject, + selectedDevice.udid, + scheme, + configuration, + launchPackager, + verbose, + port, + ).then(appName => { if (!appName) { appName = scheme; } const iosDeployInstallArgs = [ - '--bundle', getBuildPath(configuration, appName, true), - '--id' , selectedDevice.udid, - '--justlaunch' + '--bundle', + getBuildPath(configuration, appName, true), + '--id', + selectedDevice.udid, + '--justlaunch', ]; - console.log(`installing and launching your app on ${selectedDevice.name}...`); - const iosDeployOutput = child_process.spawnSync('ios-deploy', iosDeployInstallArgs, {encoding: 'utf8'}); + console.log( + `installing and launching your app on ${selectedDevice.name}...`, + ); + const iosDeployOutput = child_process.spawnSync( + 'ios-deploy', + iosDeployInstallArgs, + {encoding: 'utf8'}, + ); if (iosDeployOutput.error) { console.log(''); console.log('** INSTALLATION FAILED **'); @@ -188,22 +263,42 @@ function runOnDevice(selectedDevice, scheme, xcodeProject, configuration, launch }); } -function buildProject(xcodeProject, udid, scheme, configuration = 'Debug', launchPackager = false, verbose, port) { - return new Promise((resolve,reject) => - { - var xcodebuildArgs = [ - xcodeProject.isWorkspace ? '-workspace' : '-project', xcodeProject.name, - '-configuration', configuration, - '-scheme', scheme, - '-destination', `id=${udid}`, - '-derivedDataPath', 'build', +function buildProject( + xcodeProject, + udid, + scheme, + configuration = 'Debug', + launchPackager = false, + verbose, + port, +) { + return new Promise((resolve, reject) => { + var xcodebuildArgs = [ + xcodeProject.isWorkspace ? '-workspace' : '-project', + xcodeProject.name, + '-configuration', + configuration, + '-scheme', + scheme, + '-destination', + `id=${udid}`, + '-derivedDataPath', + 'build', ]; console.log(`Building using "xcodebuild ${xcodebuildArgs.join(' ')}"`); let xcpretty; if (!verbose) { - xcpretty = xcprettyAvailable() && child_process.spawn('xcpretty', [], { stdio: ['pipe', process.stdout, process.stderr] }); + xcpretty = + xcprettyAvailable() && + child_process.spawn('xcpretty', [], { + stdio: ['pipe', process.stdout, process.stderr], + }); } - const buildProcess = child_process.spawn('xcodebuild', xcodebuildArgs, getProcessOptions(launchPackager, port)); + const buildProcess = child_process.spawn( + 'xcodebuild', + xcodebuildArgs, + getProcessOptions(launchPackager, port), + ); let buildOutput = ''; buildProcess.stdout.on('data', function(data) { buildOutput += data.toString(); @@ -221,9 +316,15 @@ function buildProject(xcodeProject, udid, scheme, configuration = 'Debug', launc xcpretty.stdin.end(); } //FULL_PRODUCT_NAME is the actual file name of the app, which actually comes from the Product Name in the build config, which does not necessary match a scheme name, example output line: export FULL_PRODUCT_NAME="Super App Dev.app" - let productNameMatch = /export FULL_PRODUCT_NAME="?(.+).app"?$/m.exec(buildOutput); - if (productNameMatch && productNameMatch.length && productNameMatch.length > 1) { - return resolve(productNameMatch[1]);//0 is the full match, 1 is the app name + let productNameMatch = /export FULL_PRODUCT_NAME="?(.+).app"?$/m.exec( + buildOutput, + ); + if ( + productNameMatch && + productNameMatch.length && + productNameMatch.length > 1 + ) { + return resolve(productNameMatch[1]); //0 is the full match, 1 is the app name } return buildProcess.error ? reject(buildProcess.error) : resolve(); }); @@ -231,13 +332,19 @@ function buildProject(xcodeProject, udid, scheme, configuration = 'Debug', launc } function matchingDevice(devices, deviceName) { - if (deviceName === true && devices.length === 1) - { - console.log(`Using first available device ${devices[0].name} due to lack of name supplied.`); + if (deviceName === true && devices.length === 1) { + console.log( + `Using first available device ${ + devices[0].name + } due to lack of name supplied.`, + ); return devices[0]; } for (let i = devices.length - 1; i >= 0; i--) { - if (devices[i].name === deviceName || formattedDeviceName(devices[i]) === deviceName) { + if ( + devices[i].name === deviceName || + formattedDeviceName(devices[i]) === deviceName + ) { return devices[i]; } } @@ -264,12 +371,12 @@ function printFoundDevices(devices) { function getProcessOptions(launchPackager, port) { if (launchPackager) { return { - env: { ...process.env, RCT_METRO_PORT: port } + env: {...process.env, RCT_METRO_PORT: port}, }; } return { - env: { ...process.env, RCT_NO_LAUNCH_PACKAGER: true }, + env: {...process.env, RCT_NO_LAUNCH_PACKAGER: true}, }; } @@ -278,53 +385,66 @@ module.exports = { description: 'builds your app and starts it on iOS simulator', func: runIOS, examples: [ - { - desc: 'Run on a different simulator, e.g. iPhone 5', - cmd: 'react-native run-ios --simulator "iPhone 5"', - }, - { - desc: 'Pass a non-standard location of iOS directory', - cmd: 'react-native run-ios --project-path "./app/ios"', - }, - { - desc: "Run on a connected device, e.g. Max's iPhone", - cmd: 'react-native run-ios --device "Max\'s iPhone"', - }, - { - desc: 'Run on the AppleTV simulator', - cmd: 'react-native run-ios --simulator "Apple TV" --scheme "helloworld-tvOS"', - } + { + desc: 'Run on a different simulator, e.g. iPhone 5', + cmd: 'react-native run-ios --simulator "iPhone 5"', + }, + { + desc: 'Pass a non-standard location of iOS directory', + cmd: 'react-native run-ios --project-path "./app/ios"', + }, + { + desc: "Run on a connected device, e.g. Max's iPhone", + cmd: 'react-native run-ios --device "Max\'s iPhone"', + }, + { + desc: 'Run on the AppleTV simulator', + cmd: + 'react-native run-ios --simulator "Apple TV" --scheme "helloworld-tvOS"', + }, + ], + options: [ + { + command: '--simulator [string]', + description: 'Explicitly set simulator to use', + default: 'iPhone 6', + }, + { + command: '--configuration [string]', + description: 'Explicitly set the scheme configuration to use', + }, + { + command: '--scheme [string]', + description: 'Explicitly set Xcode scheme to use', + }, + { + command: '--project-path [string]', + description: + 'Path relative to project root where the Xcode project ' + + "(.xcodeproj) lives. The default is 'ios'.", + default: 'ios', + }, + { + command: '--device [string]', + description: + 'Explicitly set device to use by name. The value is not required if you have a single device connected.', + }, + { + command: '--udid [string]', + description: 'Explicitly set device to use by udid', + }, + { + command: '--no-packager', + description: 'Do not launch packager while building', + }, + { + command: '--verbose', + description: 'Do not use xcpretty even if installed', + }, + { + command: '--port [number]', + default: process.env.RCT_METRO_PORT || 8081, + parse: (val: string) => Number(val), + }, ], - options: [{ - command: '--simulator [string]', - description: 'Explicitly set simulator to use', - default: 'iPhone 6', - } , { - command: '--configuration [string]', - description: 'Explicitly set the scheme configuration to use', - } , { - command: '--scheme [string]', - description: 'Explicitly set Xcode scheme to use', - }, { - command: '--project-path [string]', - description: 'Path relative to project root where the Xcode project ' - + '(.xcodeproj) lives. The default is \'ios\'.', - default: 'ios', - }, { - command: '--device [string]', - description: 'Explicitly set device to use by name. The value is not required if you have a single device connected.', - }, { - command: '--udid [string]', - description: 'Explicitly set device to use by udid', - }, { - command: '--no-packager', - description: 'Do not launch packager while building', - }, { - command: '--verbose', - description: 'Do not use xcpretty even if installed', - },{ - command: '--port [number]', - default: process.env.RCT_METRO_PORT || 8081, - parse: (val: string) => Number(val), - }], }; diff --git a/local-cli/server/checkNodeVersion.js b/local-cli/server/checkNodeVersion.js index 46ec6cdc2f7..8917be55c65 100644 --- a/local-cli/server/checkNodeVersion.js +++ b/local-cli/server/checkNodeVersion.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; var chalk = require('chalk'); @@ -12,12 +15,14 @@ var semver = require('semver'); module.exports = function() { if (!semver.satisfies(process.version, '>=4')) { - var engine = semver.satisfies(process.version, '<1') - ? 'Node' - : 'io.js'; + var engine = semver.satisfies(process.version, '<1') ? 'Node' : 'io.js'; - var message = 'You are currently running ' + engine + ' ' + - process.version + '.\n' + + var message = + 'You are currently running ' + + engine + + ' ' + + process.version + + '.\n' + '\n' + 'React Native runs on Node 4.0 or newer. There are several ways to ' + 'upgrade Node.js depending on your preference.\n' + @@ -28,12 +33,14 @@ module.exports = function() { '\n' + 'About Node.js: https://nodejs.org\n' + 'Follow along at: https://github.com/facebook/react-native/issues/2545'; - console.log(formatBanner(message, { - chalkFunction: chalk.green, - marginLeft: 1, - marginRight: 1, - paddingBottom: 1, - })); + console.log( + formatBanner(message, { + chalkFunction: chalk.green, + marginLeft: 1, + marginRight: 1, + paddingBottom: 1, + }), + ); process.exit(1); } }; diff --git a/local-cli/server/middleware/copyToClipBoardMiddleware.js b/local-cli/server/middleware/copyToClipBoardMiddleware.js index 723fbd30c88..3f04c69a158 100644 --- a/local-cli/server/middleware/copyToClipBoardMiddleware.js +++ b/local-cli/server/middleware/copyToClipBoardMiddleware.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const copyToClipBoard = require('../util/copyToClipBoard'); diff --git a/local-cli/server/middleware/indexPage.js b/local-cli/server/middleware/indexPage.js index dee12456db2..55b55c0f792 100644 --- a/local-cli/server/middleware/indexPage.js +++ b/local-cli/server/middleware/indexPage.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const fs = require('fs'); diff --git a/local-cli/server/middleware/loadRawBodyMiddleware.js b/local-cli/server/middleware/loadRawBodyMiddleware.js index 924275009eb..1530c28fa84 100644 --- a/local-cli/server/middleware/loadRawBodyMiddleware.js +++ b/local-cli/server/middleware/loadRawBodyMiddleware.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; module.exports = function(req, res, next) { diff --git a/local-cli/server/middleware/openStackFrameInEditorMiddleware.js b/local-cli/server/middleware/openStackFrameInEditorMiddleware.js index 471c8ed8bbe..290969ac6f4 100644 --- a/local-cli/server/middleware/openStackFrameInEditorMiddleware.js +++ b/local-cli/server/middleware/openStackFrameInEditorMiddleware.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const launchEditor = require('../util/launchEditor'); diff --git a/local-cli/server/middleware/statusPageMiddleware.js b/local-cli/server/middleware/statusPageMiddleware.js index cd8fb80200c..bbc189223ff 100644 --- a/local-cli/server/middleware/statusPageMiddleware.js +++ b/local-cli/server/middleware/statusPageMiddleware.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; /** diff --git a/local-cli/server/middleware/systraceProfileMiddleware.js b/local-cli/server/middleware/systraceProfileMiddleware.js index fc1669468f8..dbf71d41d8c 100644 --- a/local-cli/server/middleware/systraceProfileMiddleware.js +++ b/local-cli/server/middleware/systraceProfileMiddleware.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const fs = require('fs'); @@ -18,7 +21,9 @@ module.exports = function(req, res, next) { var dumpName = '/tmp/dump_' + Date.now() + '.json'; fs.writeFileSync(dumpName, req.rawBody); var response = - 'Your profile was saved at:\n' + dumpName + '\n\n' + + 'Your profile was saved at:\n' + + dumpName + + '\n\n' + 'On Google Chrome navigate to chrome://tracing and then click on "load" ' + 'to load and visualise your profile.\n\n' + 'This message is also printed to your console by the packager so you can copy it :)'; diff --git a/local-cli/server/middleware/unless.js b/local-cli/server/middleware/unless.js index acf0643cf3a..016adfa7f22 100644 --- a/local-cli/server/middleware/unless.js +++ b/local-cli/server/middleware/unless.js @@ -3,11 +3,14 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; module.exports = (url, middleware) => { - return (req, res, next) => { + return (req, res, next) => { if (req.url === url || req.url.startsWith(url + '/')) { middleware(req, res, next); } else { diff --git a/local-cli/server/server.js b/local-cli/server/server.js index 7711e8590af..b1b3851b3ff 100644 --- a/local-cli/server/server.js +++ b/local-cli/server/server.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ @@ -56,80 +57,106 @@ module.exports = { name: 'start', func: server, description: 'starts the webserver', - options: [{ - command: '--port [number]', - default: process.env.RCT_METRO_PORT || 8081, - parse: (val: string) => Number(val), - }, { - command: '--host [string]', - default: '', - }, { - command: '--root [list]', - description: 'add another root(s) to be used by the packager in this project', - parse: (val: string) => val.split(',').map(root => path.resolve(root)), - default: [], - }, { - command: '--projectRoots [list]', - description: 'override the root(s) to be used by the packager', - parse: (val: string) => val.split(','), - default: (config: ConfigT) => config.getProjectRoots(), - }, { - command: '--assetExts [list]', - description: 'Specify any additional asset extensions to be used by the packager', - parse: (val: string) => val.split(','), - default: (config: ConfigT) => config.getAssetExts(), - }, { - command: '--sourceExts [list]', - description: 'Specify any additional source extensions to be used by the packager', - parse: (val: string) => val.split(','), - default: (config: ConfigT) => config.getSourceExts(), - }, { - command: '--platforms [list]', - description: 'Specify any additional platforms to be used by the packager', - parse: (val: string) => val.split(','), - default: (config: ConfigT) => config.getPlatforms(), - }, { - command: '--providesModuleNodeModules [list]', - description: 'Specify any npm packages that import dependencies with providesModule', - parse: (val: string) => val.split(','), - default: (config: RNConfig) => { - if (typeof config.getProvidesModuleNodeModules === 'function') { - return config.getProvidesModuleNodeModules(); - } - return null; + options: [ + { + command: '--port [number]', + default: process.env.RCT_METRO_PORT || 8081, + parse: (val: string) => Number(val), }, - }, { - command: '--max-workers [number]', - description: 'Specifies the maximum number of workers the worker-pool ' + - 'will spawn for transforming files. This defaults to the number of the ' + - 'cores available on your machine.', - parse: (workers: string) => Number(workers), - }, { - command: '--skipflow', - description: 'Disable flow checks' - }, { - command: '--nonPersistent', - description: 'Disable file watcher' - }, { - command: '--transformer [string]', - description: 'Specify a custom transformer to be used' - }, { - command: '--reset-cache, --resetCache', - description: 'Removes cached files', - }, { - command: '--custom-log-reporter-path, --customLogReporterPath [string]', - description: 'Path to a JavaScript file that exports a log reporter as a replacement for TerminalReporter', - }, { - command: '--verbose', - description: 'Enables logging', - }, { - command: '--https', - description: 'Enables https connections to the server', - }, { - command: '--key [path]', - description: 'Path to custom SSL key', - }, { - command: '--cert [path]', - description: 'Path to custom SSL cert', - }], + { + command: '--host [string]', + default: '', + }, + { + command: '--root [list]', + description: + 'add another root(s) to be used by the packager in this project', + parse: (val: string) => val.split(',').map(root => path.resolve(root)), + default: [], + }, + { + command: '--projectRoots [list]', + description: 'override the root(s) to be used by the packager', + parse: (val: string) => val.split(','), + default: (config: ConfigT) => config.getProjectRoots(), + }, + { + command: '--assetExts [list]', + description: + 'Specify any additional asset extensions to be used by the packager', + parse: (val: string) => val.split(','), + default: (config: ConfigT) => config.getAssetExts(), + }, + { + command: '--sourceExts [list]', + description: + 'Specify any additional source extensions to be used by the packager', + parse: (val: string) => val.split(','), + default: (config: ConfigT) => config.getSourceExts(), + }, + { + command: '--platforms [list]', + description: + 'Specify any additional platforms to be used by the packager', + parse: (val: string) => val.split(','), + default: (config: ConfigT) => config.getPlatforms(), + }, + { + command: '--providesModuleNodeModules [list]', + description: + 'Specify any npm packages that import dependencies with providesModule', + parse: (val: string) => val.split(','), + default: (config: RNConfig) => { + if (typeof config.getProvidesModuleNodeModules === 'function') { + return config.getProvidesModuleNodeModules(); + } + return null; + }, + }, + { + command: '--max-workers [number]', + description: + 'Specifies the maximum number of workers the worker-pool ' + + 'will spawn for transforming files. This defaults to the number of the ' + + 'cores available on your machine.', + parse: (workers: string) => Number(workers), + }, + { + command: '--skipflow', + description: 'Disable flow checks', + }, + { + command: '--nonPersistent', + description: 'Disable file watcher', + }, + { + command: '--transformer [string]', + description: 'Specify a custom transformer to be used', + }, + { + command: '--reset-cache, --resetCache', + description: 'Removes cached files', + }, + { + command: '--custom-log-reporter-path, --customLogReporterPath [string]', + description: + 'Path to a JavaScript file that exports a log reporter as a replacement for TerminalReporter', + }, + { + command: '--verbose', + description: 'Enables logging', + }, + { + command: '--https', + description: 'Enables https connections to the server', + }, + { + command: '--key [path]', + description: 'Path to custom SSL key', + }, + { + command: '--cert [path]', + description: 'Path to custom SSL cert', + }, + ], }; diff --git a/local-cli/server/util/copyToClipBoard.js b/local-cli/server/util/copyToClipBoard.js index bb2259e8150..0dbf3a78683 100644 --- a/local-cli/server/util/copyToClipBoard.js +++ b/local-cli/server/util/copyToClipBoard.js @@ -3,13 +3,16 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; var child_process = require('child_process'); var spawn = child_process.spawn; var path = require('path'); -var fs = require('fs'); +var fs = require('fs'); const xsel = path.join(__dirname, 'external/xsel'); fs.chmodSync(xsel, '0755'); @@ -18,20 +21,20 @@ fs.chmodSync(xsel, '0755'); */ function copyToClipBoard(content) { switch (process.platform) { - case 'darwin': - var child = spawn('pbcopy', []); - child.stdin.end(new Buffer(content, 'utf8')); - return true; - case 'win32': - var child = spawn('clip', []); - child.stdin.end(new Buffer(content, 'utf8')); - return true; - case 'linux': - var child = spawn(xsel, ['--clipboard', '--input']); - child.stdin.end(new Buffer(content, 'utf8')); - return true; - default: - return false; + case 'darwin': + var child = spawn('pbcopy', []); + child.stdin.end(new Buffer(content, 'utf8')); + return true; + case 'win32': + var child = spawn('clip', []); + child.stdin.end(new Buffer(content, 'utf8')); + return true; + case 'linux': + var child = spawn(xsel, ['--clipboard', '--input']); + child.stdin.end(new Buffer(content, 'utf8')); + return true; + default: + return false; } } diff --git a/local-cli/server/util/debugger-ui/debuggerWorker.js b/local-cli/server/util/debugger-ui/debuggerWorker.js index e70ca0ec973..ad820c16fc0 100644 --- a/local-cli/server/util/debugger-ui/debuggerWorker.js +++ b/local-cli/server/util/debugger-ui/debuggerWorker.js @@ -3,6 +3,8 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ /* global __fbBatchedBridge, self, importScripts, postMessage, onmessage: true */ @@ -22,14 +24,14 @@ onmessage = (function() { hasWarned = true; console.warn( 'Remote debugger is in a background tab which may cause apps to ' + - 'perform slowly. Fix this by foregrounding the tab (or opening it in ' + - 'a separate window).' + 'perform slowly. Fix this by foregrounding the tab (or opening it in ' + + 'a separate window).', ); }; })(); var messageHandlers = { - 'executeApplicationScript': function(message, sendReply) { + executeApplicationScript: function(message, sendReply) { for (var key in message.inject) { self[key] = JSON.parse(message.inject[key]); } @@ -41,7 +43,7 @@ onmessage = (function() { } sendReply(null /* result */, error); }, - 'setDebuggerVisibility': function(message) { + setDebuggerVisibility: function(message) { visibilityState = message.visibilityState; }, }; @@ -67,7 +69,10 @@ onmessage = (function() { var error; try { if (typeof __fbBatchedBridge === 'object') { - returnValue = __fbBatchedBridge[object.method].apply(null, object.arguments); + returnValue = __fbBatchedBridge[object.method].apply( + null, + object.arguments, + ); } else { error = 'Failed to call function, __fbBatchedBridge is undefined'; } diff --git a/local-cli/server/util/jsPackagerClient.js b/local-cli/server/util/jsPackagerClient.js index 3b449db160e..0052198228d 100644 --- a/local-cli/server/util/jsPackagerClient.js +++ b/local-cli/server/util/jsPackagerClient.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format */ 'use strict'; @@ -47,43 +48,51 @@ class JsPackagerClient { } sendRequest(method, target, params) { - return this.openPromise.then(() => new Promise((resolve, reject) => { - const messageId = getMessageId(); - this.msgCallbacks.set(messageId, {resolve: resolve, reject: reject}); - this.ws.send( - JSON.stringify({ - version: PROTOCOL_VERSION, - target: target, - method: method, - id: messageId, - params: params, + return this.openPromise.then( + () => + new Promise((resolve, reject) => { + const messageId = getMessageId(); + this.msgCallbacks.set(messageId, {resolve: resolve, reject: reject}); + this.ws.send( + JSON.stringify({ + version: PROTOCOL_VERSION, + target: target, + method: method, + id: messageId, + params: params, + }), + error => { + if (error !== undefined) { + this.msgCallbacks.delete(messageId); + reject(error); + } + }, + ); }), - error => { - if (error !== undefined) { - this.msgCallbacks.delete(messageId); - reject(error); - } - }); - })); + ); } sendNotification(method, target, params) { - return this.openPromise.then(() => new Promise((resolve, reject) => { - this.ws.send( - JSON.stringify({ - version: PROTOCOL_VERSION, - target: target, - method: method, - params: params, + return this.openPromise.then( + () => + new Promise((resolve, reject) => { + this.ws.send( + JSON.stringify({ + version: PROTOCOL_VERSION, + target: target, + method: method, + params: params, + }), + error => { + if (error !== undefined) { + reject(error); + } else { + resolve(); + } + }, + ); }), - error => { - if (error !== undefined) { - reject(error); - } else { - resolve(); - } - }); - })); + ); } sendBroadcast(method, params) { @@ -92,16 +101,16 @@ class JsPackagerClient { getPeers() { return new Promise((resolve, reject) => { - this.sendRequest('getpeers', TARGET_SERVER, undefined).then( - response => { - if (!response instanceof Map) { - reject('Results received from server are of wrong format:\n' + - JSON.stringify(response)); - } else { - resolve(response); - } - }, - reject); + this.sendRequest('getpeers', TARGET_SERVER, undefined).then(response => { + if (!response instanceof Map) { + reject( + 'Results received from server are of wrong format:\n' + + JSON.stringify(response), + ); + } else { + resolve(response); + } + }, reject); }); } diff --git a/local-cli/server/util/launchChrome.js b/local-cli/server/util/launchChrome.js index 6999a3d0bdd..f37f06b088c 100644 --- a/local-cli/server/util/launchChrome.js +++ b/local-cli/server/util/launchChrome.js @@ -4,8 +4,10 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @format * @flow */ + 'use strict'; /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error @@ -14,11 +16,16 @@ const opn = require('opn'); const execSync = require('child_process').execSync; -function commandExistsUnixSync (commandName, callback) { +function commandExistsUnixSync(commandName, callback) { try { - var stdout = execSync('command -v ' + commandName + - ' 2>/dev/null' + - ' && { echo >&1 \'' + commandName + ' found\'; exit 0; }'); + var stdout = execSync( + 'command -v ' + + commandName + + ' 2>/dev/null' + + " && { echo >&1 '" + + commandName + + " found'; exit 0; }", + ); return !!stdout; } catch (error) { return false; @@ -27,20 +34,20 @@ function commandExistsUnixSync (commandName, callback) { function getChromeAppName(): string { switch (process.platform) { - case 'darwin': - return 'google chrome'; - case 'win32': - return 'chrome'; - case 'linux': - if (commandExistsUnixSync('google-chrome')) { + case 'darwin': + return 'google chrome'; + case 'win32': + return 'chrome'; + case 'linux': + if (commandExistsUnixSync('google-chrome')) { + return 'google-chrome'; + } else if (commandExistsUnixSync('chromium-browser')) { + return 'chromium-browser'; + } else { + return 'chromium'; + } + default: return 'google-chrome'; - } else if (commandExistsUnixSync('chromium-browser')) { - return 'chromium-browser'; - } else { - return 'chromium'; - } - default: - return 'google-chrome'; } } diff --git a/local-cli/server/util/launchEditor.js b/local-cli/server/util/launchEditor.js index f78927d82d6..8b9f1729e10 100644 --- a/local-cli/server/util/launchEditor.js +++ b/local-cli/server/util/launchEditor.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; var chalk = require('chalk'); @@ -71,7 +74,10 @@ function getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) { case 'mine': return ['--line', lineNumber, fileName]; case 'code': - return addWorkspaceToArgumentsIfExists(['-g', fileName + ':' + lineNumber], workspace); + return addWorkspaceToArgumentsIfExists( + ['-g', fileName + ':' + lineNumber], + workspace, + ); } // For all others, drop the lineNumber until we have @@ -114,17 +120,19 @@ function guessEditor() { } function printInstructions(title) { - console.log([ - '', - chalk.bgBlue.white.bold(' ' + title + ' '), - ' When you see Red Box with stack trace, you can click any ', - ' stack frame to jump to the source file. The packager will launch your ', - ' editor of choice. It will first look at REACT_EDITOR environment ', - ' variable, then at EDITOR. To set it up, you can add something like ', - ' export REACT_EDITOR=atom to your ~/.bashrc or ~/.zshrc depending on ', - ' which shell you use.', - '' - ].join('\n')); + console.log( + [ + '', + chalk.bgBlue.white.bold(' ' + title + ' '), + ' When you see Red Box with stack trace, you can click any ', + ' stack frame to jump to the source file. The packager will launch your ', + ' editor of choice. It will first look at REACT_EDITOR environment ', + ' variable, then at EDITOR. To set it up, you can add something like ', + ' export REACT_EDITOR=atom to your ~/.bashrc or ~/.zshrc depending on ', + ' which shell you use.', + '', + ].join('\n'), + ); } function transformToAbsolutePathIfNeeded(pathName) { @@ -136,7 +144,7 @@ function transformToAbsolutePathIfNeeded(pathName) { function findRootForFile(projectRoots, fileName) { fileName = transformToAbsolutePathIfNeeded(fileName); - return projectRoots.find((root) => { + return projectRoots.find(root => { root = transformToAbsolutePathIfNeeded(root); return fileName.startsWith(root + path.sep); }); @@ -162,11 +170,15 @@ function launchEditor(fileName, lineNumber, projectRoots) { var workspace = findRootForFile(projectRoots, fileName); if (lineNumber) { - args = args.concat(getArgumentsForLineNumber(editor, fileName, lineNumber, workspace)); + args = args.concat( + getArgumentsForLineNumber(editor, fileName, lineNumber, workspace), + ); } else { args.push(fileName); } - console.log('Opening ' + chalk.underline(fileName) + ' with ' + chalk.bold(editor)); + console.log( + 'Opening ' + chalk.underline(fileName) + ' with ' + chalk.bold(editor), + ); if (_childProcess && isTerminalEditor(editor)) { // There's an existing editor process already and it's attached @@ -178,7 +190,11 @@ function launchEditor(fileName, lineNumber, projectRoots) { if (process.platform === 'win32') { // On Windows, launch the editor in a shell because spawn can only // launch .exe files. - _childProcess = child_process.spawn('cmd.exe', ['/C', editor].concat(args), {stdio: 'inherit'}); + _childProcess = child_process.spawn( + 'cmd.exe', + ['/C', editor].concat(args), + {stdio: 'inherit'}, + ); } else { _childProcess = child_process.spawn(editor, args, {stdio: 'inherit'}); } diff --git a/local-cli/server/util/messageSocket.js b/local-cli/server/util/messageSocket.js index bceb72fab01..87772789a34 100644 --- a/local-cli/server/util/messageSocket.js +++ b/local-cli/server/util/messageSocket.js @@ -3,7 +3,10 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ + 'use strict'; const url = require('url'); @@ -21,8 +24,9 @@ function parseMessage(data, binary) { if (message.version === PROTOCOL_VERSION) { return message; } - console.error('Received message had wrong protocol version: ' - + message.version); + console.error( + 'Received message had wrong protocol version: ' + message.version, + ); } catch (e) { console.error('Failed to parse the message as JSON:\n' + data); } @@ -39,24 +43,23 @@ function isBroadcast(message) { function isRequest(message) { return ( - typeof message.method === 'string' && - typeof message.target === 'string'); + typeof message.method === 'string' && typeof message.target === 'string' + ); } function isResponse(message) { return ( typeof message.id === 'object' && typeof message.id.requestId !== undefined && - typeof message.id.clientId === 'string' && ( - message.result !== undefined || - message.error !== undefined - )); + typeof message.id.clientId === 'string' && + (message.result !== undefined || message.error !== undefined) + ); } function attachToServer(server, path) { const wss = new WebSocketServer({ server: server, - path: path + path: path, }); const clients = new Map(); let nextClientId = 0; @@ -77,10 +80,11 @@ function attachToServer(server, path) { }; if (clients.size === 0) { notifier.notify({ - 'title': 'React Native: No apps connected', - 'message': `Sending '${message.method}' to all React Native apps ` + - 'failed. Make sure your app is running in the simulator ' + - 'or on a phone connected via USB.' + title: 'React Native: No apps connected', + message: + `Sending '${message.method}' to all React Native apps ` + + 'failed. Make sure your app is running in the simulator ' + + 'or on a phone connected via USB.', }); } for (const [otherId, otherWs] of clients) { @@ -88,8 +92,10 @@ function attachToServer(server, path) { try { otherWs.send(JSON.stringify(forwarded)); } catch (e) { - console.error(`Failed to send broadcast to client: '${otherId}' ` + - `due to:\n ${e.toString()}`); + console.error( + `Failed to send broadcast to client: '${otherId}' ` + + `due to:\n ${e.toString()}`, + ); } } } @@ -111,18 +117,23 @@ function attachToServer(server, path) { if (message.id === undefined) { console.error( `Handling message from ${clientId} failed with:\n${error}\n` + - `message:\n${JSON.stringify(errorMessage)}`); + `message:\n${JSON.stringify(errorMessage)}`, + ); } else { try { - clientWs.send(JSON.stringify({ - version: PROTOCOL_VERSION, - error: error, - id: message.id, - })); + clientWs.send( + JSON.stringify({ + version: PROTOCOL_VERSION, + error: error, + id: message.id, + }), + ); } catch (e) { - console.error(`Failed to reply to ${clientId} with error:\n${error}` + - `\nmessage:\n${JSON.stringify(errorMessage)}` + - `\ndue to error: ${e.toString()}`); + console.error( + `Failed to reply to ${clientId} with error:\n${error}` + + `\nmessage:\n${JSON.stringify(errorMessage)}` + + `\ndue to error: ${e.toString()}`, + ); } } } @@ -145,40 +156,46 @@ function attachToServer(server, path) { throw `unknown method: ${message.method}`; } - clientWs.send(JSON.stringify({ - version: PROTOCOL_VERSION, - result: result, - id: message.id - })); + clientWs.send( + JSON.stringify({ + version: PROTOCOL_VERSION, + result: result, + id: message.id, + }), + ); } function forwardRequest(message) { - getClientWs(message.target).send(JSON.stringify({ - version: PROTOCOL_VERSION, - method: message.method, - params: message.params, - id: (message.id === undefined - ? undefined - : {requestId: message.id, clientId: clientId}), - })); + getClientWs(message.target).send( + JSON.stringify({ + version: PROTOCOL_VERSION, + method: message.method, + params: message.params, + id: + message.id === undefined + ? undefined + : {requestId: message.id, clientId: clientId}, + }), + ); } function forwardResponse(message) { - getClientWs(message.id.clientId).send(JSON.stringify({ - version: PROTOCOL_VERSION, - result: message.result, - error: message.error, - id: message.id.requestId, - })); + getClientWs(message.id.clientId).send( + JSON.stringify({ + version: PROTOCOL_VERSION, + result: message.result, + error: message.error, + id: message.id.requestId, + }), + ); } clients.set(clientId, clientWs); - clientWs.onclose = - clientWs.onerror = () => { + clientWs.onclose = clientWs.onerror = () => { clientWs.onmessage = null; clients.delete(clientId); }; - clientWs.onmessage = (event) => { + clientWs.onmessage = event => { const message = parseMessage(event.data, event.binary); if (message === undefined) { console.error('Received message not matching protocol'); @@ -208,7 +225,7 @@ function attachToServer(server, path) { return { broadcast: (method, params) => { handleSendBroadcast(null, {method: method, params: params}); - } + }, }; } diff --git a/local-cli/server/util/webSocketProxy.js b/local-cli/server/util/webSocketProxy.js index 2a854c6d81d..d419e515897 100644 --- a/local-cli/server/util/webSocketProxy.js +++ b/local-cli/server/util/webSocketProxy.js @@ -3,15 +3,17 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ -'use strict'; +'use strict'; function attachToServer(server, path) { var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ server: server, - path: path + path: path, }); var debuggerSocket, clientSocket; @@ -37,8 +39,7 @@ function attachToServer(server, path) { return; } debuggerSocket = ws; - debuggerSocket.onerror = - debuggerSocket.onclose = () => { + debuggerSocket.onerror = debuggerSocket.onclose = () => { debuggerSocket = null; if (clientSocket) { clientSocket.close(1011, 'Debugger was disconnected'); @@ -51,8 +52,7 @@ function attachToServer(server, path) { clientSocket.close(1011, 'Another client connected'); } clientSocket = ws; - clientSocket.onerror = - clientSocket.onclose = () => { + clientSocket.onerror = clientSocket.onclose = () => { clientSocket = null; send(debuggerSocket, JSON.stringify({method: '$disconnected'})); }; @@ -66,10 +66,10 @@ function attachToServer(server, path) { server: wss, isChromeConnected: function() { return !!debuggerSocket; - } + }, }; } module.exports = { - attachToServer: attachToServer + attachToServer: attachToServer, }; diff --git a/local-cli/templates/HelloNavigation/App.js b/local-cli/templates/HelloNavigation/App.js index 8b422a767b8..4ccc87f1791 100644 --- a/local-cli/templates/HelloNavigation/App.js +++ b/local-cli/templates/HelloNavigation/App.js @@ -2,10 +2,12 @@ * This is an example React Native app demonstrates ListViews, text input and * navigation between a few screens. * https://github.com/facebook/react-native + * + * @format */ -import React, { Component } from 'react'; -import { StackNavigator } from 'react-navigation'; +import React, {Component} from 'react'; +import {StackNavigator} from 'react-navigation'; import HomeScreenTabNavigator from './views/HomeScreenTabNavigator'; import ChatScreen from './views/chat/ChatScreen'; diff --git a/local-cli/templates/HelloNavigation/components/KeyboardSpacer.js b/local-cli/templates/HelloNavigation/components/KeyboardSpacer.js index 72e10391757..9b73a41bab2 100644 --- a/local-cli/templates/HelloNavigation/components/KeyboardSpacer.js +++ b/local-cli/templates/HelloNavigation/components/KeyboardSpacer.js @@ -3,28 +3,25 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. + * + * @format */ 'use strict'; /* @flow */ -import React, { Component } from 'react'; +import React, {Component} from 'react'; import PropTypes from 'prop-types'; -import { - Platform, - View, - Keyboard, - LayoutAnimation, -} from 'react-native'; +import {Platform, View, Keyboard, LayoutAnimation} from 'react-native'; type Props = { offset?: number, -} +}; type State = { - keyboardHeight: number -} + keyboardHeight: number, +}; // Consider contributing this to the popular library: // https://github.com/Andr3wHur5t/react-native-keyboard-spacer @@ -48,9 +45,8 @@ type State = { * The KeyboardAvoidingView doesn't work when used together with * a ScrollView/ListView. */ -const KeyboardSpacer = () => ( - Platform.OS === 'ios' ? : null -); +const KeyboardSpacer = () => + Platform.OS === 'ios' ? : null; class KeyboardSpacerIOS extends Component { static propTypes = { @@ -73,17 +69,17 @@ class KeyboardSpacerIOS extends Component { this._unRegisterEvents(); } - _keyboardWillShowSubscription: { +remove: Function }; - _keyboardWillHideSubscription: { +remove: Function }; + _keyboardWillShowSubscription: {+remove: Function}; + _keyboardWillHideSubscription: {+remove: Function}; _registerEvents = () => { this._keyboardWillShowSubscription = Keyboard.addListener( 'keyboardWillShow', - this._keyboardWillShow + this._keyboardWillShow, ); this._keyboardWillHideSubscription = Keyboard.addListener( 'keyboardWillHide', - this._keyboardWillHide + this._keyboardWillHide, ); }; @@ -98,9 +94,9 @@ class KeyboardSpacerIOS extends Component { duration: 100, update: { type: 'keyboard', - } + }, }); - } + }; _keyboardWillShow = (e: any) => { this._configureLayoutAnimation(); @@ -117,7 +113,7 @@ class KeyboardSpacerIOS extends Component { }; render() { - return ; + return ; } } diff --git a/local-cli/templates/HelloNavigation/components/ListItem.js b/local-cli/templates/HelloNavigation/components/ListItem.js index 4e953214ea0..c93e819b5c1 100644 --- a/local-cli/templates/HelloNavigation/components/ListItem.js +++ b/local-cli/templates/HelloNavigation/components/ListItem.js @@ -1,6 +1,8 @@ +/** @format */ + 'use strict'; -import React, { Component } from 'react'; +import React, {Component} from 'react'; import { Platform, StyleSheet, @@ -48,7 +50,7 @@ const styles = StyleSheet.create({ }, label: { fontSize: 16, - } + }, }); export default ListItem; diff --git a/local-cli/templates/HelloNavigation/lib/Backend.js b/local-cli/templates/HelloNavigation/lib/Backend.js index 22cde143b63..a85f0ae753f 100644 --- a/local-cli/templates/HelloNavigation/lib/Backend.js +++ b/local-cli/templates/HelloNavigation/lib/Backend.js @@ -1,3 +1,5 @@ +/** @format */ + 'use strict'; // This file just a dummy example of a HTTP API to talk to the backend. @@ -23,7 +25,7 @@ const backendStateForLoggedInPerson = { text: 'I ❤️ React Native!', }, ], - } + }, ], }; @@ -33,7 +35,7 @@ const backendStateForLoggedInPerson = { * in real-world conditions. */ function isNetworkFailure() { - const chanceOfFailure = 0; // 0..1 + const chanceOfFailure = 0; // 0..1 return Math.random() < chanceOfFailure; } @@ -45,8 +47,8 @@ function isNetworkFailure() { */ function _makeSimulatedNetworkRequest(getValue) { const durationMs = 400; - return new Promise(function (resolve, reject) { - setTimeout(function () { + return new Promise(function(resolve, reject) { + setTimeout(function() { if (isNetworkFailure()) { reject(new Error('Network failure')); } else { @@ -71,9 +73,7 @@ async function fetchChatList() { async function fetchChat(name) { return _makeSimulatedNetworkRequest((resolve, reject) => { resolve( - backendStateForLoggedInPerson.chats.find( - chat => chat.name === name - ) + backendStateForLoggedInPerson.chats.find(chat => chat.name === name), ); }); } @@ -84,7 +84,7 @@ async function fetchChat(name) { async function sendMessage({name, message}) { return _makeSimulatedNetworkRequest((resolve, reject) => { const chatForName = backendStateForLoggedInPerson.chats.find( - chat => chat.name === name + chat => chat.name === name, ); if (chatForName) { chatForName.messages.push({ diff --git a/local-cli/templates/HelloNavigation/views/HomeScreenTabNavigator.js b/local-cli/templates/HelloNavigation/views/HomeScreenTabNavigator.js index 36ca5af70fe..09e411a471a 100644 --- a/local-cli/templates/HelloNavigation/views/HomeScreenTabNavigator.js +++ b/local-cli/templates/HelloNavigation/views/HomeScreenTabNavigator.js @@ -1,4 +1,6 @@ -import { TabNavigator } from 'react-navigation'; +/** @format */ + +import {TabNavigator} from 'react-navigation'; import ChatListScreen from './chat/ChatListScreen'; import WelcomeScreen from './welcome/WelcomeScreen'; diff --git a/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js b/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js index 4d4fcc093e9..121deb36d33 100644 --- a/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js +++ b/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js @@ -1,4 +1,6 @@ -import React, { Component } from 'react'; +/** @format */ + +import React, {Component} from 'react'; import { ActivityIndicator, Image, @@ -11,18 +13,17 @@ import ListItem from '../../components/ListItem'; import Backend from '../../lib/Backend'; export default class ChatListScreen extends Component { - static navigationOptions = { title: 'Chats', header: Platform.OS === 'ios' ? undefined : null, - tabBarIcon: ({ tintColor }) => ( + tabBarIcon: ({tintColor}) => ( ), - } + }; constructor(props) { super(props); @@ -33,7 +34,7 @@ export default class ChatListScreen extends Component { async componentDidMount() { const chatList = await Backend.fetchChatList(); - this.setState((prevState) => ({ + this.setState(prevState => ({ chatList, isLoading: false, })); @@ -41,7 +42,7 @@ export default class ChatListScreen extends Component { // Binding the function so it can be passed to FlatList below // and 'this' works properly inside renderItem - renderItem = ({ item }) => { + renderItem = ({item}) => { return ( ); - } + }; render() { if (this.state.isLoading) { diff --git a/local-cli/templates/HelloNavigation/views/chat/ChatScreen.js b/local-cli/templates/HelloNavigation/views/chat/ChatScreen.js index 6f1dfff3213..0d1e322d151 100644 --- a/local-cli/templates/HelloNavigation/views/chat/ChatScreen.js +++ b/local-cli/templates/HelloNavigation/views/chat/ChatScreen.js @@ -1,4 +1,6 @@ -import React, { Component } from 'react'; +/** @format */ + +import React, {Component} from 'react'; import { ActivityIndicator, Button, @@ -12,8 +14,7 @@ import KeyboardSpacer from '../../components/KeyboardSpacer'; import Backend from '../../lib/Backend'; export default class ChatScreen extends Component { - - static navigationOptions = ({ navigation }) => ({ + static navigationOptions = ({navigation}) => ({ title: `Chat with ${navigation.state.params.name}`, }); constructor(props) { @@ -40,7 +41,7 @@ export default class ChatScreen extends Component { }); return; } - this.setState((prevState) => ({ + this.setState(prevState => ({ messages: chat.messages, isLoading: false, })); @@ -61,18 +62,19 @@ export default class ChatScreen extends Component { // Here we would handle the request failure, e.g. call setState // to display a visual hint showing the message could not be sent. } - } + }; addMessageLocal = () => { - this.setState((prevState) => { + this.setState(prevState => { if (!prevState.myMessage) { return prevState; } const messages = [ - ...prevState.messages, { + ...prevState.messages, + { name: 'Me', text: prevState.myMessage, - } + }, ]; return { messages: messages, @@ -80,18 +82,18 @@ export default class ChatScreen extends Component { }; }); this.textInput.clear(); - } + }; - onMyMessageChange = (event) => { + onMyMessageChange = event => { this.setState({myMessage: event.nativeEvent.text}); - } + }; - renderItem = ({ item }) => ( + renderItem = ({item}) => ( {item.name} {item.text} - ) + ); render() { if (this.state.isLoading) { @@ -104,15 +106,17 @@ export default class ChatScreen extends Component { return ( index} - style={styles.listView} - /> + data={this.state.messages} + renderItem={this.renderItem} + keyExtractor={(item, index) => index} + style={styles.listView} + /> { this.textInput = textInput; }} + ref={textInput => { + this.textInput = textInput; + }} style={styles.textInput} placeholder="Type a message..." text={this.state.myMessage} @@ -120,10 +124,7 @@ export default class ChatScreen extends Component { onChange={this.onMyMessageChange} /> {this.state.myMessage !== '' && ( -