diff --git a/.circleci/config.yml b/.circleci/config.yml index a871be1eb..84e4ac74e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -31,7 +31,7 @@ jobs: - attach_workspace: at: ~/react-native-cli - run: | - # yarn lint – disable temporarily until ESLint is added to the project + yarn lint yarn flow-check tests: <<: *defaults diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..3b29e03f2 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +**/node_modules/** +**/debugger-ui/** +**/templates/** +**/global-cli/** diff --git a/package.json b/package.json index 1e802249d..c0ccdf98b 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,18 @@ ], "scripts": { "test": "cd packages/local-cli && yarn jest; cd -", + "lint": "eslint packages", "flow-check": "cd packages/local-cli && yarn flow check; cd -" + }, + "devDependencies": { + "@callstack/eslint-config": "^3.0.2", + "eslint": "^5.10.0" + }, + "eslintConfig": { + "extends": "@callstack", + "rules": { + "global-require": 0, + "no-console": 0 + } } } diff --git a/packages/local-cli/__mocks__/beeper.js b/packages/local-cli/__mocks__/beeper.js index 9fbb40caa..f2d46e51f 100644 --- a/packages/local-cli/__mocks__/beeper.js +++ b/packages/local-cli/__mocks__/beeper.js @@ -7,9 +7,7 @@ * @format */ -'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 beeper() {}; diff --git a/packages/local-cli/__mocks__/fs.js b/packages/local-cli/__mocks__/fs.js index a3691e3f3..a449fb685 100644 --- a/packages/local-cli/__mocks__/fs.js +++ b/packages/local-cli/__mocks__/fs.js @@ -3,37 +3,34 @@ * * 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'); const MemoryFS = require('metro-memory-fs'); + let fs; function setMockFilesystem(object, platform) { reset(platform); const root = platform === 'win32' ? 'c:\\' : '/'; - mockDir(root, {...object}); + mockDir(root, { ...object }); return root; } function mockDir(dirPath, desc) { - for (const entName in desc) { + for (const entName of Object.keys(desc)) { const ent = desc[entName]; const entPath = path.join(dirPath, entName); if (typeof ent === 'string' || ent instanceof Buffer) { fs.writeFileSync(entPath, ent); - continue; + continue; // eslint-disable-line no-continue } if (typeof ent !== 'object') { throw new Error(require('util').format('invalid entity:', ent)); } if (ent.SYMLINK != null) { fs.symlinkSync(ent.SYMLINK, entPath); - continue; + continue; // eslint-disable-line no-continue } fs.mkdirSync(entPath); mockDir(entPath, ent); @@ -43,18 +40,18 @@ function mockDir(dirPath, desc) { function reset(platform) { if (path.mock == null) { throw new Error( - 'to use this "fs" module mock, you must also mock the "path" module', + 'to use this "fs" module mock, you must also mock the "path" module' ); } path.mock.reset(platform); const cwd = () => (platform === 'win32' ? 'c:\\' : '/'); - fs = new MemoryFS({platform, cwd}); + fs = new MemoryFS({ platform, cwd }); Object.assign(mockFs, fs); } const mockFs = {}; mockFs.__setMockFilesystem = setMockFilesystem; -mockFs.mock = {clear: reset}; +mockFs.mock = { clear: reset }; reset('posix'); diff --git a/packages/local-cli/__mocks__/path.js b/packages/local-cli/__mocks__/path.js index 813a2525c..884f26590 100644 --- a/packages/local-cli/__mocks__/path.js +++ b/packages/local-cli/__mocks__/path.js @@ -7,15 +7,13 @@ * @format */ -'use strict'; - const mockPath = {}; function reset(platform) { Object.assign(mockPath, jest.requireActual('path')[platform]); } -mockPath.mock = {reset}; +mockPath.mock = { reset }; reset('posix'); diff --git a/packages/local-cli/babel.config.js b/packages/local-cli/babel.config.js index e3f02bd9b..6f23a5715 100644 --- a/packages/local-cli/babel.config.js +++ b/packages/local-cli/babel.config.js @@ -1,4 +1,3 @@ -const path = require('path'); const escapeRegExp = require('escape-string-regexp'); module.exports = { @@ -12,7 +11,6 @@ module.exports = { ], require.resolve('@babel/preset-flow'), ], - only: [ - new RegExp('^' + escapeRegExp(__dirname)) - ] + plugins: [require.resolve('@babel/plugin-transform-strict-mode')], + only: [new RegExp(`^${escapeRegExp(__dirname)}`)], }; diff --git a/packages/local-cli/bin.js b/packages/local-cli/bin.js index 74b48b754..836285971 100755 --- a/packages/local-cli/bin.js +++ b/packages/local-cli/bin.js @@ -17,12 +17,12 @@ if (isInstalledGlobally()) { console.error( [ chalk.red( - 'Looks like you installed react-native globally, maybe you meant react-native-cli?', + 'Looks like you installed react-native globally, maybe you meant react-native-cli?' ), chalk.red('To fix the issue, run:'), 'npm uninstall -g react-native', 'npm install -g react-native-cli', - ].join('\n'), + ].join('\n') ); process.exit(1); } else { diff --git a/packages/local-cli/bundle/__mocks__/sign.js b/packages/local-cli/bundle/__mocks__/sign.js index 31fda82f5..0b8c3a132 100644 --- a/packages/local-cli/bundle/__mocks__/sign.js +++ b/packages/local-cli/bundle/__mocks__/sign.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - function sign(source) { return source; } diff --git a/packages/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js b/packages/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js index ca336d8fd..120e3b741 100644 --- a/packages/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js +++ b/packages/local-cli/bundle/__tests__/filterPlatformAssetScales-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../filterPlatformAssetScales').dontMock('../assetPathUtils'); const filterPlatformAssetScales = require('../filterPlatformAssetScales'); diff --git a/packages/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js b/packages/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js index 792e2676c..a2625b5d5 100644 --- a/packages/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js +++ b/packages/local-cli/bundle/__tests__/getAssetDestPathAndroid-test.js @@ -8,13 +8,10 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../getAssetDestPathAndroid').dontMock('../assetPathUtils'); -const getAssetDestPathAndroid = require('../getAssetDestPathAndroid'); - const path = require('path'); +const getAssetDestPathAndroid = require('../getAssetDestPathAndroid'); describe('getAssetDestPathAndroid', () => { it('should use the right destination folder', () => { @@ -24,10 +21,10 @@ describe('getAssetDestPathAndroid', () => { httpServerLocation: '/assets/test', }; - const expectDestPathForScaleToStartWith = (scale, path) => { - if (!getAssetDestPathAndroid(asset, scale).startsWith(path)) { + const expectDestPathForScaleToStartWith = (scale, location) => { + if (!getAssetDestPathAndroid(asset, scale).startsWith(location)) { throw new Error( - `asset for scale ${scale} should start with path '${path}'`, + `asset for scale ${scale} should start with path '${location}'` ); } }; @@ -47,7 +44,7 @@ describe('getAssetDestPathAndroid', () => { }; expect(getAssetDestPathAndroid(asset, 1)).toBe( - path.normalize('drawable-mdpi/app_test_icon.png'), + path.normalize('drawable-mdpi/app_test_icon.png') ); }); @@ -69,7 +66,7 @@ describe('getAssetDestPathAndroid', () => { }; expect(getAssetDestPathAndroid(asset, 1)).toBe( - path.normalize('raw/app_test_video.mp4'), + path.normalize('raw/app_test_video.mp4') ); }); }); diff --git a/packages/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js b/packages/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js index fb05ba3fb..58bdb37b9 100644 --- a/packages/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js +++ b/packages/local-cli/bundle/__tests__/getAssetDestPathIOS-test.js @@ -8,12 +8,10 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../getAssetDestPathIOS'); -const getAssetDestPathIOS = require('../getAssetDestPathIOS'); const path = require('path'); +const getAssetDestPathIOS = require('../getAssetDestPathIOS'); describe('getAssetDestPathIOS', () => { it('should build correct path', () => { @@ -24,7 +22,7 @@ describe('getAssetDestPathIOS', () => { }; expect(getAssetDestPathIOS(asset, 1)).toBe( - path.normalize('assets/test/icon.png'), + path.normalize('assets/test/icon.png') ); }); @@ -36,10 +34,10 @@ describe('getAssetDestPathIOS', () => { }; expect(getAssetDestPathIOS(asset, 2)).toBe( - path.normalize('assets/test/icon@2x.png'), + path.normalize('assets/test/icon@2x.png') ); expect(getAssetDestPathIOS(asset, 3)).toBe( - path.normalize('assets/test/icon@3x.png'), + path.normalize('assets/test/icon@3x.png') ); }); }); diff --git a/packages/local-cli/bundle/assetPathUtils.js b/packages/local-cli/bundle/assetPathUtils.js index 7e71e8e13..24aa8344f 100644 --- a/packages/local-cli/bundle/assetPathUtils.js +++ b/packages/local-cli/bundle/assetPathUtils.js @@ -8,8 +8,6 @@ * @flow strict */ -'use strict'; - export type PackagerAsset = { +httpServerLocation: string, +name: string, @@ -34,8 +32,9 @@ function getAndroidAssetSuffix(scale: number): string { return 'xxhdpi'; case 4: return 'xxxhdpi'; + default: + throw new Error('no such scale'); } - throw new Error('no such scale'); } // See https://developer.android.com/guide/topics/resources/drawable-resource.html @@ -53,20 +52,21 @@ function getAndroidResourceFolderName(asset: PackagerAsset, scale: number) { if (!drawableFileTypes.has(asset.type)) { return 'raw'; } - var suffix = getAndroidAssetSuffix(scale); + const 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; + const androidFolder = `drawable-${suffix}`; return androidFolder; } function getAndroidResourceIdentifier(asset: PackagerAsset) { - var folderPath = getBasePath(asset); - return (folderPath + '/' + asset.name) + const folderPath = getBasePath(asset); + return `${folderPath}/${asset.name}` .toLowerCase() .replace(/\//g, '_') // Encode folder structure in file name .replace(/([^a-z0-9_])/g, '') // Remove illegal chars @@ -74,7 +74,7 @@ function getAndroidResourceIdentifier(asset: PackagerAsset) { } function getBasePath(asset: PackagerAsset) { - var basePath = asset.httpServerLocation; + let basePath = asset.httpServerLocation; if (basePath[0] === '/') { basePath = basePath.substr(1); } @@ -82,8 +82,8 @@ function getBasePath(asset: PackagerAsset) { } module.exports = { - getAndroidAssetSuffix: getAndroidAssetSuffix, - getAndroidResourceFolderName: getAndroidResourceFolderName, - getAndroidResourceIdentifier: getAndroidResourceIdentifier, - getBasePath: getBasePath, + getAndroidAssetSuffix, + getAndroidResourceFolderName, + getAndroidResourceIdentifier, + getBasePath, }; diff --git a/packages/local-cli/bundle/buildBundle.js b/packages/local-cli/bundle/buildBundle.js index 909dfe687..8859bba6e 100644 --- a/packages/local-cli/bundle/buildBundle.js +++ b/packages/local-cli/bundle/buildBundle.js @@ -4,27 +4,29 @@ * 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'; +import type { ContextT } from '../core/types.flow'; +import type { CommandLineArgs } from './bundleCommandLineArgs'; -const log = require('../util/log').out('bundle'); const Server = require('metro/src/Server'); const outputBundle = require('metro/src/shared/output/bundle'); const path = require('path'); +const log = require('./log').out('bundle'); const saveAssets = require('./saveAssets'); const loadMetroConfig = require('../util/loadMetroConfig'); -import type { ContextT } from '../core/types.flow'; -import type { CommandLineArgs } from './bundleCommandLineArgs'; - -async function buildBundle(args: CommandLineArgs, ctx: ContextT, output = outputBundle) { +async function buildBundle( + args: CommandLineArgs, + ctx: ContextT, + output = outputBundle +) { const config = await loadMetroConfig(ctx.root, { resetCache: args.resetCache, - config: args.config + config: args.config, }); // This is used by a bazillion of npm modules we don't control so we don't diff --git a/packages/local-cli/bundle/bundle.js b/packages/local-cli/bundle/bundle.js index 2eb039044..f0642598e 100644 --- a/packages/local-cli/bundle/bundle.js +++ b/packages/local-cli/bundle/bundle.js @@ -7,11 +7,8 @@ * @format */ -'use strict'; - const buildBundle = require('./buildBundle'); const bundleCommandLineArgs = require('./bundleCommandLineArgs'); -const outputBundle = require('metro/src/shared/output/bundle'); /** * Builds the bundle starting to look for dependencies at the given entry path. diff --git a/packages/local-cli/bundle/bundleCommandLineArgs.js b/packages/local-cli/bundle/bundleCommandLineArgs.js index 3d70b2e11..7d3e9abfc 100644 --- a/packages/local-cli/bundle/bundleCommandLineArgs.js +++ b/packages/local-cli/bundle/bundleCommandLineArgs.js @@ -7,8 +7,6 @@ * @flow */ -'use strict'; - const path = require('path'); export type CommandLineArgs = { @@ -48,7 +46,7 @@ module.exports = [ { command: '--dev [boolean]', description: 'If false, warnings are disabled and the bundle is minified', - parse: (val: string) => (val === 'false' ? false : true), + parse: (val: string) => val !== 'false', default: true, }, { @@ -57,7 +55,7 @@ module.exports = [ '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: string) => (val === 'false' ? false : true), + parse: (val: string) => val !== 'false', }, { command: '--bundle-output ', diff --git a/packages/local-cli/bundle/filterPlatformAssetScales.js b/packages/local-cli/bundle/filterPlatformAssetScales.js index d75512e86..681cc6cef 100644 --- a/packages/local-cli/bundle/filterPlatformAssetScales.js +++ b/packages/local-cli/bundle/filterPlatformAssetScales.js @@ -8,15 +8,13 @@ * @format */ -'use strict'; - const ALLOWED_SCALES = { ios: [1, 2, 3], }; function filterPlatformAssetScales( platform: string, - scales: $ReadOnlyArray, + scales: $ReadOnlyArray ): $ReadOnlyArray { const whitelist = ALLOWED_SCALES[platform]; if (!whitelist) { diff --git a/packages/local-cli/bundle/getAssetDestPathAndroid.js b/packages/local-cli/bundle/getAssetDestPathAndroid.js index 91e71d623..ff7576dfa 100644 --- a/packages/local-cli/bundle/getAssetDestPathAndroid.js +++ b/packages/local-cli/bundle/getAssetDestPathAndroid.js @@ -8,20 +8,18 @@ * @flow strict */ -'use strict'; +import type { PackagerAsset } from './assetPathUtils'; -const assetPathUtils = require('./assetPathUtils'); const path = require('path'); - -import type { PackagerAsset } from './assetPathUtils'; +const assetPathUtils = require('./assetPathUtils'); function getAssetDestPathAndroid(asset: PackagerAsset, scale: number): string { const androidFolder = assetPathUtils.getAndroidResourceFolderName( asset, - scale, + scale ); const fileName = assetPathUtils.getAndroidResourceIdentifier(asset); - return path.join(androidFolder, fileName + '.' + asset.type); + return path.join(androidFolder, `${fileName}.${asset.type}`); } module.exports = getAssetDestPathAndroid; diff --git a/packages/local-cli/bundle/getAssetDestPathIOS.js b/packages/local-cli/bundle/getAssetDestPathIOS.js index ba0b65a1f..3978b8a97 100644 --- a/packages/local-cli/bundle/getAssetDestPathIOS.js +++ b/packages/local-cli/bundle/getAssetDestPathIOS.js @@ -8,15 +8,13 @@ * @flow strict */ -'use strict'; +import type { PackagerAsset } from './assetPathUtils'; const path = require('path'); -import type { PackagerAsset } from './assetPathUtils'; - function getAssetDestPathIOS(asset: PackagerAsset, scale: number): string { - const suffix = scale === 1 ? '' : '@' + scale + 'x'; - const fileName = asset.name + suffix + '.' + asset.type; + const suffix = scale === 1 ? '' : `@${scale}x`; + const fileName = `${asset.name + suffix}.${asset.type}`; return path.join(asset.httpServerLocation.substr(1), fileName); } diff --git a/packages/local-cli/util/log.js b/packages/local-cli/bundle/log.js similarity index 72% rename from packages/local-cli/util/log.js rename to packages/local-cli/bundle/log.js index e74d74f18..cc32a941d 100644 --- a/packages/local-cli/util/log.js +++ b/packages/local-cli/bundle/log.js @@ -7,21 +7,19 @@ * @format */ -'use strict'; - -var _enabled = true; +let _enabled = true; function disable() { _enabled = false; } function log(stream, module) { - return function() { + return (...args) => { if (!_enabled) { return; } - const message = Array.prototype.slice.call(arguments).join(' '); - stream.write(module + ': ' + message + '\n'); + const message = Array.prototype.slice.call(args).join(' '); + stream.write(`${module}: ${message}\n`); }; } diff --git a/packages/local-cli/bundle/ramBundle.js b/packages/local-cli/bundle/ramBundle.js index 796389034..1697bfa30 100644 --- a/packages/local-cli/bundle/ramBundle.js +++ b/packages/local-cli/bundle/ramBundle.js @@ -6,12 +6,10 @@ * * @format */ - -'use strict'; +const outputUnbundle = require('metro/src/shared/output/RamBundle'); const bundleWithOutput = require('./bundle').withOutput; const bundleCommandLineArgs = require('./bundleCommandLineArgs'); -const outputUnbundle = require('metro/src/shared/output/RamBundle'); /** * Builds the bundle starting to look for dependencies at the given entry path. diff --git a/packages/local-cli/bundle/saveAssets.js b/packages/local-cli/bundle/saveAssets.js index d43197ec5..ff1e1b953 100644 --- a/packages/local-cli/bundle/saveAssets.js +++ b/packages/local-cli/bundle/saveAssets.js @@ -7,15 +7,14 @@ * @format */ -'use strict'; +const mkdirp = require('mkdirp'); +const path = require('path'); +const fs = require('fs'); const filterPlatformAssetScales = require('./filterPlatformAssetScales'); -const fs = require('fs'); const getAssetDestPathAndroid = require('./getAssetDestPathAndroid'); const getAssetDestPathIOS = require('./getAssetDestPathIOS'); -const log = require('../util/log').out('bundle'); -const mkdirp = require('mkdirp'); -const path = require('path'); +const log = require('./log').out('bundle'); function saveAssets(assets, platform, assetsDest) { if (!assetsDest) { @@ -29,7 +28,7 @@ function saveAssets(assets, platform, assetsDest) { const filesToCopy = Object.create(null); // Map src -> dest assets.forEach(asset => { const validScales = new Set( - filterPlatformAssetScales(platform, asset.scales), + filterPlatformAssetScales(platform, asset.scales) ); asset.scales.forEach((scale, idx) => { if (!validScales.has(scale)) { @@ -50,11 +49,12 @@ function copyAll(filesToCopy) { return Promise.resolve(); } - log('Copying ' + queue.length + ' asset files'); + log(`Copying ${queue.length} asset files`); return new Promise((resolve, reject) => { const copyNext = error => { if (error) { - return reject(error); + reject(error); + return; } if (queue.length === 0) { log('Done copying assets'); @@ -73,7 +73,8 @@ function copy(src, dest, callback) { const destDir = path.dirname(dest); mkdirp(destDir, err => { if (err) { - return callback(err); + callback(err); + return; } fs.createReadStream(src) .pipe(fs.createWriteStream(dest)) diff --git a/packages/local-cli/cli.js b/packages/local-cli/cli.js index bd23859ff..5bd3a473f 100644 --- a/packages/local-cli/cli.js +++ b/packages/local-cli/cli.js @@ -7,13 +7,12 @@ * @format */ -'use strict'; - // gracefulify() has to be called before anything else runs require('graceful-fs').gracefulify(require('fs')); // Transpile the source code const babelConfig = require('./babel.config'); + require('@babel/register')(babelConfig); const cli = require('./cliEntry'); diff --git a/packages/local-cli/cliEntry.js b/packages/local-cli/cliEntry.js index a0992550b..5df8dec07 100644 --- a/packages/local-cli/cliEntry.js +++ b/packages/local-cli/cliEntry.js @@ -8,21 +8,19 @@ * @flow */ -'use strict'; +import type { CommandT, ContextT } from './core/types.flow'; -const assertRequiredOptions = require('./util/assertRequiredOptions'); const chalk = require('chalk'); const childProcess = require('child_process'); const commander = require('commander'); +const minimist = require('minimist'); +const path = require('path'); const getCommands = require('./core/getCommands'); const getLegacyConfig = require('./core/getLegacyConfig'); -const minimist = require('minimist'); const init = require('./init/init'); -const path = require('path'); +const assertRequiredOptions = require('./util/assertRequiredOptions'); const pkg = require('./package.json'); -import type { CommandT, ContextT } from './core/types.flow'; - commander.version(pkg.version); const defaultOptParser = val => val; @@ -43,7 +41,7 @@ const handleError = err => { function printHelpInformation() { let cmdName = this._name; if (this._alias) { - cmdName = cmdName + '|' + this._alias; + cmdName = `${cmdName}|${this._alias}`; } const sourceInformation = this.pkg @@ -85,10 +83,10 @@ function printUnknownCommand(cmdName) { ? chalk.red(` Unrecognized command '${cmdName}'`) : chalk.red(" You didn't pass any command"), ` Run ${chalk.cyan( - 'react-native --help', + 'react-native --help' )} to see list of all available commands`, '', - ].join('\n'), + ].join('\n') ); } @@ -100,9 +98,9 @@ const addCommand = (command: CommandT, ctx: ContextT) => { noHelp: !command.description, }) .description(command.description) - .action(function runAction() { + .action(function handleAction(...args) { const passedOptions = this.opts(); - const argv: Array = Array.from(arguments).slice(0, -1); + const argv: Array = Array.from(args).slice(0, -1); Promise.resolve() .then(() => { @@ -122,10 +120,10 @@ const addCommand = (command: CommandT, ctx: ContextT) => { opt.command, opt.description, opt.parse || defaultOptParser, - typeof opt.default === 'function' ? opt.default(ctx) : opt.default, - ), + typeof opt.default === 'function' ? opt.default(ctx) : opt.default + ) ); - + // This is needed to avoid `unknown option` error by Commander.js cmd.option('--projectRoot [string]', 'Path to the root of the project'); }; @@ -139,7 +137,7 @@ async function run() { /** * Read passed `options` and take the "global" settings - * + * * @todo(grabbou): Consider unifying this by removing either `commander` * or `minimist` */ @@ -161,7 +159,7 @@ async function run() { commander.parse(process.argv); const isValidCommand = commands.find( - cmd => cmd.name.split(' ')[0] === process.argv[2], + cmd => cmd.name.split(' ')[0] === process.argv[2] ); if (!isValidCommand) { @@ -175,6 +173,6 @@ async function run() { } module.exports = { - run: run, - init: init, + run, + init, }; diff --git a/packages/local-cli/core/__fixtures__/android.js b/packages/local-cli/core/__fixtures__/android.js index d5f603069..d6097b0bf 100644 --- a/packages/local-cli/core/__fixtures__/android.js +++ b/packages/local-cli/core/__fixtures__/android.js @@ -11,10 +11,10 @@ const fs = jest.requireActual('fs'); const path = jest.requireActual('path'); const manifest = fs.readFileSync( - path.join(__dirname, './files/AndroidManifest.xml'), + path.join(__dirname, './files/AndroidManifest.xml') ); const mainJavaClass = fs.readFileSync( - path.join(__dirname, './files/Main.java'), + path.join(__dirname, './files/Main.java') ); function generateValidFileStructure(classFileName) { @@ -27,7 +27,7 @@ function generateValidFileStructure(classFileName) { example: { 'Main.java': mainJavaClass, [classFileName]: fs.readFileSync( - path.join(__dirname, `./files/${classFileName}`), + path.join(__dirname, `./files/${classFileName}`) ), }, }, @@ -50,7 +50,7 @@ exports.userConfigManifest = { example: { 'Main.java': mainJavaClass, 'ReactPackage.java': fs.readFileSync( - path.join(__dirname, './files/ReactPackage.java'), + path.join(__dirname, './files/ReactPackage.java') ), }, }, @@ -58,7 +58,7 @@ exports.userConfigManifest = { }, debug: { 'AndroidManifest.xml': fs.readFileSync( - path.join(__dirname, './files/AndroidManifest-debug.xml'), + path.join(__dirname, './files/AndroidManifest-debug.xml') ), }, }, diff --git a/packages/local-cli/core/__fixtures__/ios.js b/packages/local-cli/core/__fixtures__/ios.js index 1792f6730..eb043ea11 100644 --- a/packages/local-cli/core/__fixtures__/ios.js +++ b/packages/local-cli/core/__fixtures__/ios.js @@ -13,7 +13,7 @@ const path = require('path'); exports.valid = { 'demoProject.xcodeproj': { 'project.pbxproj': fs.readFileSync( - path.join(__dirname, './files/project.pbxproj'), + path.join(__dirname, './files/project.pbxproj') ), }, 'TestPod.podspec': 'empty', @@ -22,7 +22,7 @@ exports.valid = { exports.validTestName = { 'MyTestProject.xcodeproj': { 'project.pbxproj': fs.readFileSync( - path.join(__dirname, './files/project.pbxproj'), + path.join(__dirname, './files/project.pbxproj') ), }, }; diff --git a/packages/local-cli/core/__fixtures__/projects.js b/packages/local-cli/core/__fixtures__/projects.js index c3d42d693..a3e8d0b67 100644 --- a/packages/local-cli/core/__fixtures__/projects.js +++ b/packages/local-cli/core/__fixtures__/projects.js @@ -34,4 +34,4 @@ const withPods = { ios: ios.pod, }; -module.exports = {flat, nested, withExamples, withPods}; +module.exports = { flat, nested, withExamples, withPods }; diff --git a/packages/local-cli/core/__tests__/android/findAndroidAppFolder-test.js b/packages/local-cli/core/__tests__/android/findAndroidAppFolder-test.js index 331dfe8e1..2eb8d9a7b 100644 --- a/packages/local-cli/core/__tests__/android/findAndroidAppFolder-test.js +++ b/packages/local-cli/core/__tests__/android/findAndroidAppFolder-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); diff --git a/packages/local-cli/core/__tests__/android/findManifest-test.js b/packages/local-cli/core/__tests__/android/findManifest-test.js index 242b20a74..d1dc608d8 100644 --- a/packages/local-cli/core/__tests__/android/findManifest-test.js +++ b/packages/local-cli/core/__tests__/android/findManifest-test.js @@ -8,13 +8,11 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const findManifest = require('../../android/findManifest'); const fs = require('fs'); +const findManifest = require('../../android/findManifest'); const mocks = require('../../__fixtures__/android'); describe('android::findManifest', () => { diff --git a/packages/local-cli/core/__tests__/android/findPackageClassName-test.js b/packages/local-cli/core/__tests__/android/findPackageClassName-test.js index 5c15fd658..251b7e988 100644 --- a/packages/local-cli/core/__tests__/android/findPackageClassName-test.js +++ b/packages/local-cli/core/__tests__/android/findPackageClassName-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); +const fs = require('fs'); const mocks = require('../../__fixtures__/android'); const findPackageClassName = require('../../android/findPackageClassName'); -const fs = require('fs'); ['posix', 'win32'].forEach(platform => { let root; @@ -31,28 +29,28 @@ const fs = require('fs'); android: mocks.validKotlin, }, }, - platform, + platform ); }); it('returns manifest content if file exists in the folder', () => { - expect(typeof findPackageClassName(root + 'flatJava')).toBe('string'); + expect(typeof findPackageClassName(`${root}flatJava`)).toBe('string'); }); it('returns the name of the java class implementing ReactPackage', () => { - expect(findPackageClassName(root + 'flatJava')).toBe( - 'SomeExampleJavaPackage', + expect(findPackageClassName(`${root}flatJava`)).toBe( + 'SomeExampleJavaPackage' ); }); it('returns the name of the kotlin class implementing ReactPackage', () => { - expect(findPackageClassName(root + 'flatKotlin')).toBe( - 'SomeExampleKotlinPackage', + expect(findPackageClassName(`${root}flatKotlin`)).toBe( + 'SomeExampleKotlinPackage' ); }); it('returns `null` if there are no matches', () => { - expect(findPackageClassName(root + 'empty')).toBeNull(); + expect(findPackageClassName(`${root}empty`)).toBeNull(); }); }); }); diff --git a/packages/local-cli/core/__tests__/android/getDependencyConfig-test.js b/packages/local-cli/core/__tests__/android/getDependencyConfig-test.js index 7a43db319..f8fcb0017 100644 --- a/packages/local-cli/core/__tests__/android/getDependencyConfig-test.js +++ b/packages/local-cli/core/__tests__/android/getDependencyConfig-test.js @@ -8,13 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const getDependencyConfig = require('../../android').dependencyConfig; const fs = require('fs'); + +const getDependencyConfig = require('../../android').dependencyConfig; const mocks = require('../../__fixtures__/android'); const userConfig = {}; diff --git a/packages/local-cli/core/__tests__/android/getProjectConfig-test.js b/packages/local-cli/core/__tests__/android/getProjectConfig-test.js index 863138c95..8fa3b4eb2 100644 --- a/packages/local-cli/core/__tests__/android/getProjectConfig-test.js +++ b/packages/local-cli/core/__tests__/android/getProjectConfig-test.js @@ -8,13 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const getProjectConfig = require('../../android').projectConfig; const fs = require('fs'); + +const getProjectConfig = require('../../android').projectConfig; const mocks = require('../../__fixtures__/android'); describe('android::getProjectConfig', () => { diff --git a/packages/local-cli/core/__tests__/android/readManifest-test.js b/packages/local-cli/core/__tests__/android/readManifest-test.js index 2b8f41e4f..bc8379eff 100644 --- a/packages/local-cli/core/__tests__/android/readManifest-test.js +++ b/packages/local-cli/core/__tests__/android/readManifest-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); +const fs = require('fs'); const findManifest = require('../../android/findManifest'); const readManifest = require('../../android/readManifest'); -const fs = require('fs'); const mocks = require('../../__fixtures__/android'); describe('android::readManifest', () => { diff --git a/packages/local-cli/core/__tests__/findAssets-test.js b/packages/local-cli/core/__tests__/findAssets-test.js index bb3a000cc..adaeb8db7 100644 --- a/packages/local-cli/core/__tests__/findAssets-test.js +++ b/packages/local-cli/core/__tests__/findAssets-test.js @@ -8,18 +8,17 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); +const fs = require('fs'); + const { findAssets } = require('../getAssets'); const dependencies = require('../__fixtures__/dependencies'); -const fs = require('fs'); describe('findAssets', () => { beforeEach(() => { - fs.__setMockFilesystem({testDir: dependencies.withAssets}); + fs.__setMockFilesystem({ testDir: dependencies.withAssets }); }); it('returns an array of all files in given folders', () => { diff --git a/packages/local-cli/core/__tests__/findPlugins-test.js b/packages/local-cli/core/__tests__/findPlugins-test.js index bf04ddecb..901bd7acf 100644 --- a/packages/local-cli/core/__tests__/findPlugins-test.js +++ b/packages/local-cli/core/__tests__/findPlugins-test.js @@ -8,10 +8,8 @@ * @emails oncall+javascript_foundation */ -'use strict'; - -const findPlugins = require('../findPlugins'); const path = require('path'); +const findPlugins = require('../findPlugins'); const ROOT = path.join(__dirname, '..', '..'); const pjsonPath = path.join(ROOT, 'package.json'); @@ -23,7 +21,7 @@ describe('findPlugins', () => { it('returns an array of dependencies', () => { jest.mock(pjsonPath, () => ({ - dependencies: {'rnpm-plugin-test': '*'}, + dependencies: { 'rnpm-plugin-test': '*' }, })); expect(findPlugins(ROOT)).toHaveProperty('commands'); @@ -50,8 +48,8 @@ describe('findPlugins', () => { it('returns plugins from both dependencies and dev dependencies', () => { jest.mock(pjsonPath, () => ({ - dependencies: {'rnpm-plugin-test': '*'}, - devDependencies: {'rnpm-plugin-test-2': '*'}, + dependencies: { 'rnpm-plugin-test': '*' }, + devDependencies: { 'rnpm-plugin-test-2': '*' }, })); expect(findPlugins(ROOT)).toHaveProperty('commands'); expect(findPlugins(ROOT)).toHaveProperty('platforms'); @@ -61,8 +59,8 @@ describe('findPlugins', () => { it('returns unique list of plugins', () => { jest.mock(pjsonPath, () => ({ - dependencies: {'rnpm-plugin-test': '*'}, - devDependencies: {'rnpm-plugin-test': '*'}, + dependencies: { 'rnpm-plugin-test': '*' }, + devDependencies: { 'rnpm-plugin-test': '*' }, })); expect(findPlugins(ROOT).commands).toHaveLength(1); }); diff --git a/packages/local-cli/core/__tests__/ios/findPodfilePath-test.js b/packages/local-cli/core/__tests__/ios/findPodfilePath-test.js index 227d24512..798cb9251 100644 --- a/packages/local-cli/core/__tests__/ios/findPodfilePath-test.js +++ b/packages/local-cli/core/__tests__/ios/findPodfilePath-test.js @@ -8,13 +8,11 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const findPodfilePath = require('../../ios/findPodfilePath'); const fs = require('fs'); +const findPodfilePath = require('../../ios/findPodfilePath'); const projects = require('../../__fixtures__/projects'); const ios = require('../../__fixtures__/ios'); diff --git a/packages/local-cli/core/__tests__/ios/findPodspecName-test.js b/packages/local-cli/core/__tests__/ios/findPodspecName-test.js index 14d73cd7d..a54c11abc 100644 --- a/packages/local-cli/core/__tests__/ios/findPodspecName-test.js +++ b/packages/local-cli/core/__tests__/ios/findPodspecName-test.js @@ -8,13 +8,11 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const findPodspecName = require('../../ios/findPodspecName'); const fs = require('fs'); +const findPodspecName = require('../../ios/findPodspecName'); const projects = require('../../__fixtures__/projects'); const ios = require('../../__fixtures__/ios'); diff --git a/packages/local-cli/core/__tests__/ios/findProject-test.js b/packages/local-cli/core/__tests__/ios/findProject-test.js index 0083e9bd0..fce47f476 100644 --- a/packages/local-cli/core/__tests__/ios/findProject-test.js +++ b/packages/local-cli/core/__tests__/ios/findProject-test.js @@ -8,13 +8,11 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const findProject = require('../../ios/findProject'); const fs = require('fs'); +const findProject = require('../../ios/findProject'); const projects = require('../../__fixtures__/projects'); const ios = require('../../__fixtures__/ios'); @@ -25,22 +23,22 @@ describe('ios::findProject', () => { }); it('returns null if there are no projects', () => { - fs.__setMockFilesystem({testDir: projects}); + fs.__setMockFilesystem({ testDir: projects }); expect(findProject('/')).toBeNull(); }); it('returns ios project regardless of its name', () => { - fs.__setMockFilesystem({ios: ios.validTestName}); + fs.__setMockFilesystem({ ios: ios.validTestName }); expect(findProject('/')).not.toBeNull(); }); it('ignores node_modules', () => { - fs.__setMockFilesystem({node_modules: projects.flat}); + fs.__setMockFilesystem({ node_modules: projects.flat }); expect(findProject('/')).toBeNull(); }); it('ignores Pods', () => { - fs.__setMockFilesystem({Pods: projects.flat}); + fs.__setMockFilesystem({ Pods: projects.flat }); expect(findProject('/')).toBeNull(); }); diff --git a/packages/local-cli/core/__tests__/ios/getProjectConfig-test.js b/packages/local-cli/core/__tests__/ios/getProjectConfig-test.js index d1af61e4b..1ac8ce211 100644 --- a/packages/local-cli/core/__tests__/ios/getProjectConfig-test.js +++ b/packages/local-cli/core/__tests__/ios/getProjectConfig-test.js @@ -8,20 +8,19 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.mock('path'); jest.mock('fs'); -const getProjectConfig = require('../../ios').projectConfig; const fs = require('fs'); + +const getProjectConfig = require('../../ios').projectConfig; const projects = require('../../__fixtures__/projects'); describe('ios::getProjectConfig', () => { const userConfig = {}; beforeEach(() => { - fs.__setMockFilesystem({testDir: projects}); + fs.__setMockFilesystem({ testDir: projects }); }); it('returns an object with ios project configuration', () => { diff --git a/packages/local-cli/core/__tests__/makeCommand-test.js b/packages/local-cli/core/__tests__/makeCommand-test.js index 34a55e6f2..38a076a30 100644 --- a/packages/local-cli/core/__tests__/makeCommand-test.js +++ b/packages/local-cli/core/__tests__/makeCommand-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - let spawnError = false; jest.setMock('child_process', { diff --git a/packages/local-cli/core/android/findAndroidAppFolder.js b/packages/local-cli/core/android/findAndroidAppFolder.js index 41e1319a0..0d8848b36 100644 --- a/packages/local-cli/core/android/findAndroidAppFolder.js +++ b/packages/local-cli/core/android/findAndroidAppFolder.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const path = require('path'); diff --git a/packages/local-cli/core/android/findManifest.js b/packages/local-cli/core/android/findManifest.js index 4c04ed7cb..1354a85d1 100644 --- a/packages/local-cli/core/android/findManifest.js +++ b/packages/local-cli/core/android/findManifest.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const glob = require('glob'); const path = require('path'); diff --git a/packages/local-cli/core/android/findPackageClassName.js b/packages/local-cli/core/android/findPackageClassName.js index a1bfaf6f2..01436454b 100644 --- a/packages/local-cli/core/android/findPackageClassName.js +++ b/packages/local-cli/core/android/findPackageClassName.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const glob = require('glob'); const path = require('path'); @@ -20,7 +18,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/packages/local-cli/core/android/index.js b/packages/local-cli/core/android/index.js index 2106ed7a9..1a674af6a 100644 --- a/packages/local-cli/core/android/index.js +++ b/packages/local-cli/core/android/index.js @@ -7,12 +7,10 @@ * @format */ -'use strict'; - +const path = require('path'); const findAndroidAppFolder = require('./findAndroidAppFolder'); const findManifest = require('./findManifest'); const findPackageClassName = require('./findPackageClassName'); -const path = require('path'); const readManifest = require('./readManifest'); const getPackageName = manifest => manifest.attr.package; @@ -52,28 +50,28 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig = {}) { const mainFilePath = path.join( sourceDir, userConfig.mainFilePath || - `src/main/java/${packageFolder}/MainApplication.java`, + `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 { @@ -95,7 +93,7 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig = {}) { */ exports.dependencyConfig = function dependencyConfigAndroid( folder, - userConfig = {}, + userConfig = {} ) { const src = userConfig.sourceDir || findAndroidAppFolder(folder); @@ -130,7 +128,7 @@ exports.dependencyConfig = function dependencyConfigAndroid( 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/packages/local-cli/core/android/readManifest.js b/packages/local-cli/core/android/readManifest.js index 159cb601d..b86cc725f 100644 --- a/packages/local-cli/core/android/readManifest.js +++ b/packages/local-cli/core/android/readManifest.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const xml = require('xmldoc'); diff --git a/packages/local-cli/core/findPlugins.js b/packages/local-cli/core/findPlugins.js index 3ff90bfc4..43b061a75 100644 --- a/packages/local-cli/core/findPlugins.js +++ b/packages/local-cli/core/findPlugins.js @@ -4,15 +4,11 @@ * 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'); -const union = require('lodash').union; -const uniq = require('lodash').uniq; -const flatten = require('lodash').flatten; +const { union, uniq, flatten } = require('lodash'); const RNPM_PLUGIN_PATTERNS = [/^rnpm-plugin-/, /^@(.*)\/rnpm-plugin-/]; @@ -69,15 +65,17 @@ const findHasteConfigInPackageAndConcat = (pjson, haste) => { if (!pjson.rnpm || !pjson.rnpm.haste) { return; } - let pkgHaste = pjson.rnpm.haste; + const pkgHaste = pjson.rnpm.haste; if (pkgHaste.platforms) { + // eslint-disable-next-line no-param-reassign haste.platforms = haste.platforms.concat(pkgHaste.platforms); } if (pkgHaste.providesModuleNodeModules) { + // eslint-disable-next-line no-param-reassign haste.providesModuleNodeModules = haste.providesModuleNodeModules.concat( - pkgHaste.providesModuleNodeModules, + pkgHaste.providesModuleNodeModules ); } }; @@ -91,13 +89,11 @@ const findPluginsInFolder = folder => { const deps = union( Object.keys(pjson.dependencies || {}), - Object.keys(pjson.devDependencies || {}), + Object.keys(pjson.devDependencies || {}) ); return deps.reduce((acc, pkg) => { - let commands = acc.commands; - let platforms = acc.platforms; - let haste = acc.haste; + let { commands, platforms } = acc; if (isRNPMPlugin(pkg)) { commands = commands.concat(pkg); } @@ -106,10 +102,10 @@ const findPluginsInFolder = folder => { if (pkgJson) { commands = commands.concat(findPluginsInReactNativePackage(pkgJson)); platforms = platforms.concat(findPlatformsInPackage(pkgJson)); - findHasteConfigInPackageAndConcat(pkgJson, haste); + findHasteConfigInPackageAndConcat(pkgJson, acc.haste); } } - return {commands: commands, platforms: platforms, haste: haste}; + return { commands, platforms, haste: acc.haste }; }, getEmptyPluginConfig()); }; @@ -125,7 +121,7 @@ module.exports = function findPlugins(folder: string) { haste: { platforms: uniq(flatten(plugin.haste.platforms)), providesModuleNodeModules: uniq( - flatten(plugin.haste.providesModuleNodeModules), + flatten(plugin.haste.providesModuleNodeModules) ), }, }; diff --git a/packages/local-cli/core/getAssets.js b/packages/local-cli/core/getAssets.js index f25ce57df..97fffd78b 100644 --- a/packages/local-cli/core/getAssets.js +++ b/packages/local-cli/core/getAssets.js @@ -2,14 +2,12 @@ * @flow */ -'use strict'; - const glob = require('glob'); const path = require('path'); const getPackageConfiguration = require('./getPackageConfiguration'); const findAssetsInFolder = folder => - glob.sync(path.join(folder, '**'), {nodir: true}); + glob.sync(path.join(folder, '**'), { nodir: true }); /** * Given an array of assets folders, e.g. ['Fonts', 'Images'], @@ -21,10 +19,11 @@ function findAssets(folder, assets) { return (assets || []) .map(asset => path.join(folder, asset)) .reduce( - (acc, assetPath) => (acc.concat(findAssetsInFolder(assetPath)): Array), - [], + (acc, assetPath) => + (acc.concat(findAssetsInFolder(assetPath)): Array), + [] ); -}; +} /** * Returns a project configuration in a given folder diff --git a/packages/local-cli/core/getCommands.js b/packages/local-cli/core/getCommands.js index 325f678ae..decec9850 100644 --- a/packages/local-cli/core/getCommands.js +++ b/packages/local-cli/core/getCommands.js @@ -2,13 +2,10 @@ * @flow */ -'use strict'; +import type { CommandT, ProjectCommandT } from './types.flow'; -const findPlugins = require('./findPlugins'); const path = require('path'); -const flatten = require('lodash').flatten; - -import type { CommandT, ProjectCommandT } from './types.flow'; +const findPlugins = require('./findPlugins'); /** * List of built-in commands @@ -33,8 +30,8 @@ const loadLocalCommands = () => [ ]; /** - * Returns an array of commands that are defined in the project. - * + * Returns an array of commands that are defined in the project. + * * This checks all CLI plugins for presence of 3rd party packages that define commands * and loads them */ @@ -44,29 +41,35 @@ const loadProjectCommands = (root: string): Array => { return plugins.commands.reduce((acc: Array, pathToCommands) => { /** * `pathToCommand` is a path to a file where commands are defined, relative to `node_modules` - * folder. - * + * folder. + * * Following code gets the name of the package name out of the path, taking scope * into consideration. */ const name = pathToCommands[0] === '@' ? pathToCommands - .split(path.sep) - .slice(0, 2) - .join(path.sep) + .split(path.sep) + .slice(0, 2) + .join(path.sep) : pathToCommands.split(path.sep)[0]; // $FlowFixMe: Non-literal require const pkg = require(path.join(root, 'node_modules', name, 'package.json')); // $FlowFixMe: Non-literal require - let requiredCommands: (ProjectCommandT | Array) = require( - path.join(root, 'node_modules', pathToCommands) - ); + const requiredCommands: + | ProjectCommandT + | Array = require(path.join( + root, + 'node_modules', + pathToCommands + )); if (Array.isArray(requiredCommands)) { - return acc.concat(requiredCommands.map(requiredCommand => ({ ...requiredCommand, pkg }))); + return acc.concat( + requiredCommands.map(requiredCommand => ({ ...requiredCommand, pkg })) + ); } return acc.concat({ ...requiredCommands }); @@ -85,7 +88,7 @@ module.exports = (root: string): Array => [ [ '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'), + ].join('\n') ); }, }, diff --git a/packages/local-cli/core/getHooks.js b/packages/local-cli/core/getHooks.js index dafb34de9..84d193073 100644 --- a/packages/local-cli/core/getHooks.js +++ b/packages/local-cli/core/getHooks.js @@ -2,16 +2,14 @@ * @flow */ -'use strict'; - -const spawn = require('child_process').spawn; +const { spawn } = require('child_process'); const getPackageConfiguration = require('./getPackageConfiguration'); function makeCommand(command) { return cb => { if (!cb) { throw new Error( - `You missed a callback function for the ${command} command`, + `You missed a callback function for the ${command} command` ); } @@ -23,7 +21,7 @@ function makeCommand(command) { stdin: 'inherit', }); - commandProcess.on('close', function prelink(code) { + commandProcess.on('close', code => { if (code) { throw new Error(`Error occurred during executing "${command}" command`); } @@ -31,19 +29,18 @@ function makeCommand(command) { cb(); }); }; -}; +} module.exports = function getHooks(root: string) { const commands = getPackageConfiguration(root).commands || {}; - + const acc = {}; - - Object.keys(commands) - .forEach(command => { - acc[command] = makeCommand(commands[command]); - }); - - return acc; + + Object.keys(commands).forEach(command => { + acc[command] = makeCommand(commands[command]); + }); + + return acc; }; module.exports.makeCommand = makeCommand; diff --git a/packages/local-cli/core/getLegacyConfig.js b/packages/local-cli/core/getLegacyConfig.js index a252eaa09..88b61c81a 100644 --- a/packages/local-cli/core/getLegacyConfig.js +++ b/packages/local-cli/core/getLegacyConfig.js @@ -10,60 +10,53 @@ const getHooks = require('./getHooks'); const getAssets = require('./getAssets'); const getParams = require('./getParams'); -const generateDeprecationMessage = (api) => { - return `${api} is deprecated and will be removed soon. Please check release notes on how to upgrade` -}; +const generateDeprecationMessage = api => + `${api} is deprecated and will be removed soon. Please check release notes on how to upgrade`; /** * Gets legacy configuration to support existing plugins while they migrate * to the new API - * + * * This file will be removed from the next version. */ module.exports = (root: string) => ({ getPlatformConfig: util.deprecate( () => getPlatforms(root), - generateDeprecationMessage("getPlatformConfig()"), + generateDeprecationMessage('getPlatformConfig()') ), - getProjectConfig: util.deprecate( - () => { - const platforms = getPlatforms(root); + getProjectConfig: util.deprecate(() => { + const platforms = getPlatforms(root); - const rnpm = getPackageConfiguration(root); + const rnpm = getPackageConfiguration(root); - const config = { - ...rnpm, - assets: getAssets(root), - }; + const config = { + ...rnpm, + assets: getAssets(root), + }; - Object.keys(platforms).forEach(key => { - config[key] = platforms[key].projectConfig(root, rnpm[key] || {}); - }); + Object.keys(platforms).forEach(key => { + config[key] = platforms[key].projectConfig(root, rnpm[key] || {}); + }); - return config; - }, - generateDeprecationMessage("getProjectConfig()"), - ), - getDependencyConfig: util.deprecate( - (packageName: string) => { - const platforms = getPlatforms(root); - const folder = path.join(process.cwd(), 'node_modules', packageName); + return config; + }, generateDeprecationMessage('getProjectConfig()')), + getDependencyConfig: util.deprecate((packageName: string) => { + const platforms = getPlatforms(root); + const folder = path.join(process.cwd(), 'node_modules', packageName); - const rnpm = getPackageConfiguration(folder); + const rnpm = getPackageConfiguration(folder); - const config = { - ...rnpm, - assets: getAssets(folder), - commands: getHooks(folder), - params: getParams(folder), - }; + const config = { + ...rnpm, + assets: getAssets(folder), + commands: getHooks(folder), + params: getParams(folder), + }; - Object.keys(platforms).forEach(key => { - config[key] = platforms[key].dependencyConfig(folder, rnpm[key] || {}); - }); + Object.keys(platforms).forEach(key => { + config[key] = platforms[key].dependencyConfig(folder, rnpm[key] || {}); + }); - return config; - }, - generateDeprecationMessage("getDependencyConfig()"), - ), + return config; + }, generateDeprecationMessage('getDependencyConfig()')), }); diff --git a/packages/local-cli/core/getPackageConfiguration.js b/packages/local-cli/core/getPackageConfiguration.js index 656e0f818..e9e46a81f 100644 --- a/packages/local-cli/core/getPackageConfiguration.js +++ b/packages/local-cli/core/getPackageConfiguration.js @@ -1,14 +1,16 @@ /** * @flow */ -const path = require('path'); - import type { PackageConfigurationT } from './types.flow'; +const path = require('path'); + /** * Returns configuration of the CLI from `package.json`. */ -module.exports = function getPackageConfiguration(folder: string): PackageConfigurationT { +module.exports = function getPackageConfiguration( + folder: string +): PackageConfigurationT { // $FlowFixMe: Non-literal require return require(path.join(folder, './package.json')).rnpm || {}; }; diff --git a/packages/local-cli/core/getParams.js b/packages/local-cli/core/getParams.js index 52c985e9d..9dc3d792f 100644 --- a/packages/local-cli/core/getParams.js +++ b/packages/local-cli/core/getParams.js @@ -2,8 +2,6 @@ * @flow */ -'use strict'; - const getPackageConfiguration = require('./getPackageConfiguration'); module.exports = function getParams(root: string) { diff --git a/packages/local-cli/core/getPlatforms.js b/packages/local-cli/core/getPlatforms.js index 2d3f22248..718ebc9b5 100644 --- a/packages/local-cli/core/getPlatforms.js +++ b/packages/local-cli/core/getPlatforms.js @@ -2,11 +2,14 @@ * @flow */ +import type { PlatformsT } from './types.flow'; + +const path = require('path'); const findPlugins = require('./findPlugins'); /** * Support for `ios` and `android` platforms is built-in - * + * * @todo(grabbou): Move this out of the core to increase "interoperability" * with other platforms */ @@ -15,8 +18,6 @@ const builtInPlatforms = { android: require('./android'), }; -import type { PlatformsT } from './types.flow'; - /** * Returns an object with available platforms */ @@ -26,20 +27,22 @@ module.exports = function getPlatforms(root: string): PlatformsT { /** * Each `platfom` is a file that should define an object with platforms available * and the config required. - * + * * @todo(grabbou): We should validate if the config loaded is correct, warn and skip * using it if it's invalid. */ - const projectPlatforms = plugins.platforms.reduce((acc, pathToPlatform) => { - return Object.assign( - acc, - // $FlowFixMe non-literal require - require(path.join(root, 'node_modules', pathToPlatform)), - ); - }, {}); + const projectPlatforms = plugins.platforms.reduce( + (acc, pathToPlatform) => + Object.assign( + acc, + // $FlowFixMe non-literal require + require(path.join(root, 'node_modules', pathToPlatform)) + ), + {} + ); return { ...builtInPlatforms, ...projectPlatforms, }; -} +}; diff --git a/packages/local-cli/core/ios/findPodfilePath.js b/packages/local-cli/core/ios/findPodfilePath.js index 672325354..f2263046b 100644 --- a/packages/local-cli/core/ios/findPodfilePath.js +++ b/packages/local-cli/core/ios/findPodfilePath.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const path = require('path'); diff --git a/packages/local-cli/core/ios/findPodspecName.js b/packages/local-cli/core/ios/findPodspecName.js index 1041a0a99..cd3d6c7a5 100644 --- a/packages/local-cli/core/ios/findPodspecName.js +++ b/packages/local-cli/core/ios/findPodspecName.js @@ -7,24 +7,23 @@ * @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) { - podspecFile = podspecs[0]; + } + if (podspecs.length === 1) { + podspecFile = podspecs[0]; // eslint-disable-line prefer-destructuring } else { const folderParts = folder.split(path.sep); const currentFolder = folderParts[folderParts.length - 1]; - const toSelect = podspecs.indexOf(currentFolder + '.podspec'); + const toSelect = podspecs.indexOf(`${currentFolder}.podspec`); if (toSelect === -1) { - podspecFile = podspecs[0]; + podspecFile = podspecs[0]; // eslint-disable-line prefer-destructuring } else { podspecFile = podspecs[toSelect]; } diff --git a/packages/local-cli/core/ios/findProject.js b/packages/local-cli/core/ios/findProject.js index d98695d67..f4ea052a1 100644 --- a/packages/local-cli/core/ios/findProject.js +++ b/packages/local-cli/core/ios/findProject.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const glob = require('glob'); const path = require('path'); @@ -46,12 +44,11 @@ module.exports = function findProject(folder) { cwd: folder, ignore: GLOB_EXCLUDE_PATTERN, }) - .filter(project => { - return path.dirname(project) === IOS_BASE || !TEST_PROJECTS.test(project); - }) - .sort((projectA, projectB) => { - return path.dirname(projectA) === IOS_BASE ? -1 : 1; - }); + .filter( + project => + path.dirname(project) === IOS_BASE || !TEST_PROJECTS.test(project) + ) + .sort(project => (path.dirname(project) === IOS_BASE ? -1 : 1)); if (projects.length === 0) { return null; diff --git a/packages/local-cli/core/ios/index.js b/packages/local-cli/core/ios/index.js index df8761150..70842f0e0 100644 --- a/packages/local-cli/core/ios/index.js +++ b/packages/local-cli/core/ios/index.js @@ -7,25 +7,22 @@ * @format */ -'use strict'; - +const path = require('path'); const findProject = require('./findProject'); const findPodfilePath = require('./findPodfilePath'); const findPodspecName = require('./findPodspecName'); -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 => { - return libraries.map(name => { +const mapSharedLibaries = libraries => + libraries.map(name => { if (path.extname(name)) { return name; } return name + (name.indexOf('lib') === 0 ? '.tbd' : '.framework'); }); -}; /** * Returns project config by analyzing given folder and applying some user defaults @@ -45,11 +42,11 @@ exports.projectConfig = function projectConfigIOS(folder, userConfig) { return { sourceDir: path.dirname(projectPath), - folder: folder, + folder, pbxprojPath: path.join(projectPath, 'project.pbxproj'), podfile: findPodfilePath(projectPath), podspec: findPodspecName(folder), - projectPath: projectPath, + projectPath, projectName: path.basename(projectPath), libraryFolder: userConfig.libraryFolder || 'Libraries', sharedLibraries: mapSharedLibaries(userConfig.sharedLibraries || []), diff --git a/packages/local-cli/core/types.flow.js b/packages/local-cli/core/types.flow.js index 9434e700c..e06b06f06 100644 --- a/packages/local-cli/core/types.flow.js +++ b/packages/local-cli/core/types.flow.js @@ -2,6 +2,8 @@ * @flow */ +/* eslint-disable flowtype/no-weak-types */ + export type ContextT = { root: string, }; @@ -10,7 +12,7 @@ export type LocalCommandT = { name: string, description?: string, usage?: string, - func: (argv: Array, ctx: ContextT, args: Object) =>?Promise, + func: (argv: Array, ctx: ContextT, args: Object) => ?Promise, options?: Array<{ command: string, description?: string, @@ -30,10 +32,10 @@ type Package = { /** * User can define command either as an object (RequiredCommandT) or - * as an array of commands (Array). + * as an array of commands (Array). */ export type ProjectCommandT = LocalCommandT & { - pkg: Package + pkg: Package, }; /** @@ -48,7 +50,7 @@ export type PlatformConfigT = { projectConfig: (string, ParamsT) => ?ProjectConfigT, dependencyConfig: (string, ParamsT) => ?DependencyConfigT, /** - * @todo(grabbou): This should not be part of the "core". It should be + * @todo(grabbou): This should not be part of the "core". It should be * specific to `link` and `unlink`. Remove it from here soon. */ linkConfig: () => { @@ -57,9 +59,14 @@ export type PlatformConfigT = { */ isInstalled: (ProjectConfigT, string, DependencyConfigT) => boolean, register: (string, DependencyConfigT, Object, ProjectConfigT) => void, - unregister: (string, DependencyConfigT, ProjectConfigT, Array) => void, + unregister: ( + string, + DependencyConfigT, + ProjectConfigT, + Array + ) => void, copyAssets: (string[], ProjectConfigT) => void, - unlinkAssets: (string[], ProjectConfigT) => void + unlinkAssets: (string[], ProjectConfigT) => void, }, }; @@ -81,13 +88,13 @@ export type DependencyConfigAndroidT = {}; /** * Config of a project. - * + * * When one of the projects is `null`, that means given platform * is not available in the current project. */ export type ProjectConfigT = { android: ?ProjectConfigAndroidT, - ios: ?ProjectConfigIOST + ios: ?ProjectConfigIOST, }; /** @@ -96,27 +103,35 @@ export type ProjectConfigT = { */ export type DependencyConfigT = { android: ?DependencyConfigAndroidT, - ios: ?DependencyConfigIOST + ios: ?DependencyConfigIOST, }; /** * Available platforms. Additional plugins should assert the type on their own. */ export type PlatformsT = { - ios: PlatformConfigT, - android: PlatformConfigT, - [name: string]: PlatformConfigT + ios: PlatformConfigT< + ProjectConfigIOST, + DependencyConfigIOST, + IOSConfigParamsT + >, + android: PlatformConfigT< + ProjectConfigAndroidT, + DependencyConfigAndroidT, + AndroidConfigParamsT + >, + [name: string]: PlatformConfigT, }; export type InquirerPromptT = any; /** - * Configuration of the CLI as set by a package in the package.json + * Configuration of the CLI as set by a package in the package.json */ export type PackageConfigurationT = { assets?: string[], commands?: { [name: string]: string }, params?: InquirerPromptT[], android: AndroidConfigParamsT, - ios: IOSConfigParamsT + ios: IOSConfigParamsT, }; diff --git a/packages/local-cli/dependencies/dependencies.js b/packages/local-cli/dependencies/dependencies.js index 192926a84..4cc4986d6 100644 --- a/packages/local-cli/dependencies/dependencies.js +++ b/packages/local-cli/dependencies/dependencies.js @@ -4,11 +4,9 @@ * 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 Metro = require('metro'); const denodeify = require('denodeify'); @@ -20,7 +18,7 @@ async function dependencies(argv, configPromise, args, packagerInstance) { const config = await configPromise; if (!fs.existsSync(rootModuleAbsolutePath)) { return Promise.reject( - new Error(`File ${rootModuleAbsolutePath} does not exist`), + new Error(`File ${rootModuleAbsolutePath} does not exist`) ); } @@ -28,7 +26,7 @@ async function dependencies(argv, configPromise, args, packagerInstance) { const relativePath = path.relative( config.projectRoot, - rootModuleAbsolutePath, + rootModuleAbsolutePath ); const options = { @@ -58,7 +56,7 @@ async function dependencies(argv, configPromise, args, packagerInstance) { 0; if (isInsideProjectRoots) { - outStream.write(modulePath + '\n'); + outStream.write(`${modulePath}\n`); } }); return writeToFile @@ -99,7 +97,7 @@ module.exports = { { command: '--dev [boolean]', description: 'If false, skip all dev-only code path', - parse: val => (val === 'false' ? false : true), + parse: val => val !== 'false', default: true, }, { diff --git a/packages/local-cli/eject/eject.js b/packages/local-cli/eject/eject.js index ff7d085be..5da04b862 100644 --- a/packages/local-cli/eject/eject.js +++ b/packages/local-cli/eject/eject.js @@ -7,11 +7,9 @@ * @format */ -'use strict'; - -const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace'); const path = require('path'); const fs = require('fs'); +const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace'); /** * The eject command re-creates the `android` and `ios` native folders. Because native code can be @@ -30,7 +28,7 @@ function eject() { 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); } @@ -42,9 +40,9 @@ function eject() { console.error( 'Eject requires an `app.json` config file to be located at ' + `${path.resolve( - 'app.json', + 'app.json' )}, and it must at least specify a \`name\` for the project ` + - "name, and a `displayName` for the app's home screen label.", + "name, and a `displayName` for the app's home screen label." ); process.exit(1); } @@ -53,20 +51,22 @@ 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); } + + // eslint-disable-next-line prefer-destructuring const displayName = appConfig.displayName; 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.'); @@ -77,11 +77,11 @@ function eject() { 'local-cli', 'templates', 'HelloWorld', - 'ios', + 'ios' ), path.resolve('ios'), appName, - templateOptions, + templateOptions ); } @@ -94,11 +94,11 @@ function eject() { 'local-cli', 'templates', 'HelloWorld', - 'android', + 'android' ), path.resolve('android'), appName, - templateOptions, + templateOptions ); } } diff --git a/packages/local-cli/generator/copyProjectTemplateAndReplace.js b/packages/local-cli/generator/copyProjectTemplateAndReplace.js index 8f04b439f..6b77d7d01 100644 --- a/packages/local-cli/generator/copyProjectTemplateAndReplace.js +++ b/packages/local-cli/generator/copyProjectTemplateAndReplace.js @@ -7,11 +7,9 @@ * @format */ -'use strict'; - const chalk = require('chalk'); -const copyAndReplace = require('../util/copyAndReplace'); const path = require('path'); +const copyAndReplace = require('../util/copyAndReplace'); const prompt = require('./promptSync')(); const walk = require('../util/walk'); @@ -33,7 +31,7 @@ function copyProjectTemplateAndReplace( srcPath, destPath, newProjectName, - options, + options = {} ) { if (!srcPath) { throw new Error('Need a path to copy from'); @@ -45,8 +43,6 @@ function copyProjectTemplateAndReplace( throw new Error('Need a project name'); } - options = options || {}; - walk(srcPath).forEach(absoluteSrcFilePath => { // 'react-native upgrade' if (options.upgrade) { @@ -90,13 +86,12 @@ function copyProjectTemplateAndReplace( let contentChangedCallback = null; if (options.upgrade && !options.force) { - contentChangedCallback = (_, contentChanged) => { - return upgradeFileContentChangedCallback( + contentChangedCallback = (_, contentChanged) => + upgradeFileContentChangedCallback( absoluteSrcFilePath, relativeRenamedPath, - contentChanged, + contentChanged ); - }; } copyAndReplace( absoluteSrcFilePath, @@ -106,7 +101,7 @@ function copyProjectTemplateAndReplace( HelloWorld: newProjectName, helloworld: newProjectName.toLowerCase(), }, - contentChangedCallback, + contentChangedCallback ); }); } @@ -119,11 +114,11 @@ function copyProjectTemplateAndReplace( * This is especially important for .gitignore because npm has some special * behavior of automatically renaming .gitignore to .npmignore. */ -function translateFilePath(path) { - if (!path) { - return path; +function translateFilePath(filePath) { + if (!filePath) { + return filePath; } - return path + return filePath .replace('_BUCK', 'BUCK') .replace('_gitignore', '.gitignore') .replace('_gitattributes', '.gitattributes') @@ -136,43 +131,36 @@ function translateFilePath(path) { function upgradeFileContentChangedCallback( absoluteSrcFilePath, relativeDestPath, - contentChanged, + contentChanged ) { if (contentChanged === 'new') { - console.log(chalk.bold('new') + ' ' + relativeDestPath); + console.log(`${chalk.bold('new')} ${relativeDestPath}`); return 'overwrite'; - } else if (contentChanged === 'changed') { + } + 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: ', + `${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); + console.log(`Replacing ${relativeDestPath}`); return 'overwrite'; - } else { - console.log('Keeping your ' + relativeDestPath); - return 'keep'; } - } else if (contentChanged === 'identical') { + console.log(`Keeping your ${relativeDestPath}`); + return 'keep'; + } + if (contentChanged === 'identical') { return 'keep'; - } else { - throw new Error( - `Unknown file changed state: ${relativeDestPath}, ${contentChanged}`, - ); } + throw new Error( + `Unknown file changed state: ${relativeDestPath}, ${contentChanged}` + ); } module.exports = copyProjectTemplateAndReplace; diff --git a/packages/local-cli/generator/printRunInstructions.js b/packages/local-cli/generator/printRunInstructions.js index 7110f646a..b011902ab 100644 --- a/packages/local-cli/generator/printRunInstructions.js +++ b/packages/local-cli/generator/printRunInstructions.js @@ -7,31 +7,32 @@ * @format */ -'use strict'; - -var chalk = require('chalk'); -var path = require('path'); +const chalk = require('chalk'); +const path = require('path'); function printRunInstructions(projectDir, projectName) { const absoluteProjectDir = path.resolve(projectDir); // iOS - const xcodeProjectPath = - path.resolve(projectDir, 'ios', projectName) + '.xcodeproj'; + const xcodeProjectPath = `${path.resolve( + projectDir, + 'ios', + projectName + )}.xcodeproj`; const relativeXcodeProjectPath = path.relative( process.cwd(), - xcodeProjectPath, + xcodeProjectPath ); console.log(chalk.white.bold('To run your app on iOS:')); - console.log(' cd ' + absoluteProjectDir); + console.log(` cd ${absoluteProjectDir}`); console.log(' react-native run-ios'); console.log(' - or -'); - console.log(' Open ' + relativeXcodeProjectPath + ' in Xcode'); + console.log(` Open ${relativeXcodeProjectPath} in Xcode`); console.log(' Hit the Run button'); // Android console.log(chalk.white.bold('To run your app on Android:')); - console.log(' cd ' + absoluteProjectDir); + console.log(` cd ${absoluteProjectDir}`); console.log( - ' Have an Android emulator running (quickest way to get started), or a device connected', + ' Have an Android emulator running (quickest way to get started), or a device connected' ); console.log(' react-native run-android'); } diff --git a/packages/local-cli/generator/promptSync.js b/packages/local-cli/generator/promptSync.js index 2388ef046..41a874f23 100644 --- a/packages/local-cli/generator/promptSync.js +++ b/packages/local-cli/generator/promptSync.js @@ -10,16 +10,17 @@ // Simplified version of: // https://github.com/0x00A/prompt-sync/blob/master/index.js -'use strict'; +/* eslint-disable */ -var fs = require('fs'); -var term = 13; // carriage return +const fs = require('fs'); + +const term = 13; // carriage return function create() { return prompt; function prompt(ask, value, opts) { - var insert = 0; + let insert = 0; opts = opts || {}; if (Object(ask) === ask) { @@ -30,23 +31,25 @@ function create() { value = opts.value; } ask = ask || ''; - var echo = opts.echo; - var masked = 'echo' in opts; + const echo = opts.echo; + const masked = 'echo' in opts; - var fd = + const fd = process.platform === 'win32' ? process.stdin.fd : fs.openSync('/dev/tty', 'rs'); - var wasRaw = process.stdin.isRaw; + const wasRaw = process.stdin.isRaw; if (!wasRaw) { process.stdin.setRawMode(true); } - var buf = Buffer.alloc(3); - var str = '', - character, - read; + let buf = Buffer.alloc(3); + let str = ''; + + let character; + + let read; if (ask) { process.stdout.write(ask); @@ -57,11 +60,11 @@ function create() { if (read > 1) { // received a control sequence if (buf.toString()) { - str = str + buf.toString(); + str += buf.toString(); str = str.replace(/\0/g, ''); insert = str.length; - process.stdout.write('\u001b[2K\u001b[0G' + ask + str); - process.stdout.write('\u001b[' + (insert + ask.length + 1) + 'G'); + process.stdout.write(`\u001b[2K\u001b[0G${ask}${str}`); + process.stdout.write(`\u001b[${insert + ask.length + 1}G`); buf = Buffer.alloc(3); } continue; // any other 3 character sequence is ignored @@ -89,7 +92,7 @@ function create() { character === 127 || (process.platform === 'win32' && character === 8) ) { - //backspace + // backspace if (!insert) { continue; } @@ -109,24 +112,18 @@ function create() { if (masked) { process.stdout.write( - '\u001b[2K\u001b[0G' + ask + Array(str.length + 1).join(echo), + `\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 { - 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'); diff --git a/packages/local-cli/generator/templates.js b/packages/local-cli/generator/templates.js index 544940a7d..5d262be11 100644 --- a/packages/local-cli/generator/templates.js +++ b/packages/local-cli/generator/templates.js @@ -7,12 +7,10 @@ * @format */ -'use strict'; - -const copyProjectTemplateAndReplace = require('./copyProjectTemplateAndReplace'); -const execSync = require('child_process').execSync; +const { execSync } = require('child_process'); const fs = require('fs'); const path = require('path'); +const copyProjectTemplateAndReplace = require('./copyProjectTemplateAndReplace'); /** * @param destPath Create the new project at this path. @@ -25,13 +23,13 @@ function createProjectFromTemplate( destPath, newProjectName, template, - yarnVersion, + yarnVersion ) { // Expand the basic 'HelloWorld' template copyProjectTemplateAndReplace( path.resolve(__dirname, '../templates/HelloWorld'), destPath, - newProjectName, + newProjectName ); if (template === undefined) { @@ -59,7 +57,7 @@ function createFromRemoteTemplate( template, destPath, newProjectName, - yarnVersion, + yarnVersion ) { let installPackage; let templateName; @@ -69,7 +67,7 @@ function createFromRemoteTemplate( templateName = template.substr(template.lastIndexOf('/') + 1); } else { // e.g 'demo' - installPackage = 'react-native-template-' + template; + installPackage = `react-native-template-${template}`; templateName = installPackage; } @@ -83,7 +81,7 @@ function createFromRemoteTemplate( } else { execSync( `npm install ${installPackage} --save --save-exact --ignore-scripts`, - {stdio: 'inherit'}, + { stdio: 'inherit' } ); } const templatePath = path.resolve('node_modules', templateName); @@ -113,7 +111,7 @@ function createFromRemoteTemplate( // 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.' ); } } @@ -134,15 +132,15 @@ 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) { + for (const depName of Object.keys(dependencies)) { const depVersion = dependencies[depName]; - const depToInstall = depName + '@' + depVersion; - console.log('Adding ' + depToInstall + '...'); + const depToInstall = `${depName}@${depVersion}`; + console.log(`Adding ${depToInstall}...`); if (yarnVersion) { - execSync(`yarn add ${depToInstall}`, {stdio: 'inherit'}); + execSync(`yarn add ${depToInstall}`, { stdio: 'inherit' }); } else { execSync(`npm install ${depToInstall} --save --save-exact`, { stdio: 'inherit', @@ -150,7 +148,7 @@ function installTemplateDependencies(templatePath, yarnVersion) { } } console.log("Linking native dependencies into the project's build files..."); - execSync('react-native link', {stdio: 'inherit'}); + execSync('react-native link', { stdio: 'inherit' }); } function installTemplateDevDependencies(templatePath, yarnVersion) { @@ -158,7 +156,7 @@ function installTemplateDevDependencies(templatePath, yarnVersion) { // that are required by this template const devDependenciesJsonPath = path.resolve( templatePath, - 'devDependencies.json', + 'devDependencies.json' ); console.log('Adding develop dependencies for the project...'); if (!fs.existsSync(devDependenciesJsonPath)) { @@ -171,15 +169,15 @@ 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) { + for (const depName of Object.keys(dependencies)) { const depVersion = dependencies[depName]; - const depToInstall = depName + '@' + depVersion; - console.log('Adding ' + depToInstall + '...'); + const depToInstall = `${depName}@${depVersion}`; + console.log(`Adding ${depToInstall}...`); if (yarnVersion) { - execSync(`yarn add ${depToInstall} -D`, {stdio: 'inherit'}); + execSync(`yarn add ${depToInstall} -D`, { stdio: 'inherit' }); } else { execSync(`npm install ${depToInstall} --save-dev --save-exact`, { stdio: 'inherit', diff --git a/packages/local-cli/info/info.js b/packages/local-cli/info/info.js index 9f09de587..4dbe517ce 100644 --- a/packages/local-cli/info/info.js +++ b/packages/local-cli/info/info.js @@ -7,13 +7,9 @@ * @format */ -'use strict'; - const envinfo = require('envinfo'); -const info = function() { - const args = Array.prototype.slice.call(arguments)[2]; - +const info = function getInfo(argv, ctx, options) { try { envinfo .run( @@ -23,19 +19,19 @@ const info = function() { IDEs: ['Xcode', 'Android Studio'], SDKs: ['iOS SDK', 'Android SDK'], npmPackages: - (typeof args.packages === 'string' && - !args.packages.includes('*')) || - !args.packages + (typeof options.packages === 'string' && + !options.packages.includes('*')) || + !options.packages ? ['react', 'react-native'].concat( - (args.packages || '').split(','), + (options.packages || '').split(',') ) - : args.packages, + : options.packages, npmGlobalPackages: '*react-native*', }, { - clipboard: !!args.clipboard, + clipboard: !!options.clipboard, title: 'React Native Environment Info', - }, + } ) .then(console.log) .catch(err => { diff --git a/packages/local-cli/init/init.js b/packages/local-cli/init/init.js index fc0f81d71..96bfb0ba6 100644 --- a/packages/local-cli/init/init.js +++ b/packages/local-cli/init/init.js @@ -7,15 +7,13 @@ * @format */ -'use strict'; - -const {createProjectFromTemplate} = require('../generator/templates'); -const execSync = require('child_process').execSync; +const { execSync } = require('child_process'); const fs = require('fs'); const minimist = require('minimist'); const path = require('path'); -const printRunInstructions = require('../generator/printRunInstructions'); const process = require('process'); +const printRunInstructions = require('../generator/printRunInstructions'); +const { createProjectFromTemplate } = require('../generator/templates'); const yarn = require('../util/yarn'); /** @@ -41,7 +39,7 @@ function init(projectDir, argsOrName) { const newProjectName = args[0]; const options = minimist(args); - console.log('Setting up new React Native app in ' + projectDir); + console.log(`Setting up new React Native app in ${projectDir}`); generateProject(projectDir, newProjectName, options); } @@ -51,19 +49,19 @@ function init(projectDir, argsOrName) { * @param options Command line arguments parsed by minimist. */ function generateProject(destinationRoot, newProjectName, options) { - var reactNativePackageJson = require.resolve('react-native/package.json'); - var {peerDependencies} = reactNativePackageJson; + const reactNativePackageJson = require.resolve('react-native/package.json'); + const { peerDependencies } = reactNativePackageJson; if (!peerDependencies) { console.error( - "Missing React peer dependency in React Native's package.json. Aborting.", + "Missing React peer dependency in React Native's package.json. Aborting." ); return; } - var reactVersion = peerDependencies.react; + const reactVersion = peerDependencies.react; if (!reactVersion) { console.error( - "Missing React peer dependency in React Native's package.json. Aborting.", + "Missing React peer dependency in React Native's package.json. Aborting." ); return; } @@ -77,12 +75,12 @@ function generateProject(destinationRoot, newProjectName, options) { destinationRoot, newProjectName, options.template, - yarnVersion, + yarnVersion ); if (yarnVersion) { console.log('Adding React...'); - execSync(`yarn add react@${reactVersion}`, {stdio: 'inherit'}); + execSync(`yarn add react@${reactVersion}`, { stdio: 'inherit' }); } else { console.log('Installing React...'); execSync(`npm install react@${reactVersion} --save --save-exact`, { @@ -93,7 +91,7 @@ function generateProject(destinationRoot, newProjectName, options) { const jestDeps = `jest babel-jest metro-react-native-babel-preset react-test-renderer@${reactVersion}`; if (yarnVersion) { console.log('Adding Jest...'); - execSync(`yarn add ${jestDeps} --dev --exact`, {stdio: 'inherit'}); + execSync(`yarn add ${jestDeps} --dev --exact`, { stdio: 'inherit' }); } else { console.log('Installing Jest...'); execSync(`npm install ${jestDeps} --save-dev --save-exact`, { @@ -109,8 +107,8 @@ function generateProject(destinationRoot, newProjectName, options) { * Add Jest-related stuff to package.json, which was created by the react-native-cli. */ function addJestToPackageJson(destinationRoot) { - var packageJSONPath = path.join(destinationRoot, 'package.json'); - var packageJSON = JSON.parse(fs.readFileSync(packageJSONPath)); + const packageJSONPath = path.join(destinationRoot, 'package.json'); + const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath)); packageJSON.scripts.test = 'jest'; packageJSON.jest = { diff --git a/packages/local-cli/install/install.js b/packages/local-cli/install/install.js index b15a3e6d5..25a2ba776 100644 --- a/packages/local-cli/install/install.js +++ b/packages/local-cli/install/install.js @@ -7,11 +7,10 @@ * @format */ -'use strict'; - -const spawnSync = require('child_process').spawnSync; +const { spawnSync } = require('child_process'); const log = require('npmlog'); const PackageManager = require('../util/PackageManager'); + const spawnOpts = { stdio: 'inherit', stdin: 'inherit', @@ -19,7 +18,7 @@ const spawnOpts = { log.heading = 'rnpm-install'; -function install(args, config) { +function install(args) { const name = args[0]; let res = PackageManager.add(name); diff --git a/packages/local-cli/install/uninstall.js b/packages/local-cli/install/uninstall.js index 096396220..af056073b 100644 --- a/packages/local-cli/install/uninstall.js +++ b/packages/local-cli/install/uninstall.js @@ -7,11 +7,10 @@ * @format */ -'use strict'; - -const spawnSync = require('child_process').spawnSync; +const { spawnSync } = require('child_process'); const log = require('npmlog'); const PackageManager = require('../util/PackageManager'); + const spawnOpts = { stdio: 'inherit', stdin: 'inherit', @@ -19,10 +18,10 @@ const spawnOpts = { log.heading = 'rnpm-install'; -function uninstall(args, config) { +function uninstall(args) { const name = args[0]; - var res = spawnSync('react-native', ['unlink', name], spawnOpts); + let res = spawnSync('react-native', ['unlink', name], spawnOpts); if (res.status) { process.exit(res.status); diff --git a/packages/local-cli/library/library.js b/packages/local-cli/library/library.js index 23a82a1ee..d4a1dea04 100644 --- a/packages/local-cli/library/library.js +++ b/packages/local-cli/library/library.js @@ -7,23 +7,20 @@ * @format */ -'use strict'; - -const copyAndReplace = require('../util/copyAndReplace'); const fs = require('fs'); -const isValidPackageName = require('../util/isValidPackageName'); const path = require('path'); +const copyAndReplace = require('../util/copyAndReplace'); +const isValidPackageName = require('../util/isValidPackageName'); const walk = require('../util/walk'); /** * Creates a new native library with the given name */ -function library(argv, config, args) { +async 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).', + throw new Error( + `${args.name} is not a valid name for a project. Please use a valid ` + + `identifier name (alphanumeric).` ); } @@ -34,7 +31,7 @@ function library(argv, config, args) { 'node_modules', 'react-native', 'Libraries', - 'Sample', + 'Sample' ); if (!fs.existsSync(libraries)) { @@ -42,9 +39,7 @@ function library(argv, config, args) { } if (fs.existsSync(libraryDest)) { - return Promise.reject( - new Error(`Library already exists in ${libraryDest}`), - ); + throw new Error(`Library already exists in ${libraryDest}`); } walk(source).forEach(f => { @@ -57,7 +52,7 @@ function library(argv, config, args) { const dest = path.relative( source, - f.replace(/Sample/g, args.name).replace(/^_/, '.'), + f.replace(/Sample/g, args.name).replace(/^_/, '.') ); copyAndReplace(path.resolve(source, f), path.resolve(libraryDest, dest), { Sample: args.name, @@ -69,7 +64,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' ); } diff --git a/packages/local-cli/link/__tests__/android/applyPatch-test.js b/packages/local-cli/link/__tests__/android/applyPatch-test.js index aea686d08..93de418a0 100644 --- a/packages/local-cli/link/__tests__/android/applyPatch-test.js +++ b/packages/local-cli/link/__tests__/android/applyPatch-test.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 - * @emails oncall+javascript_foundation */ -'use strict'; +/* eslint-disable no-template-curly-in-string */ 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)' ); }); diff --git a/packages/local-cli/link/__tests__/android/isInstalled-test.js b/packages/local-cli/link/__tests__/android/isInstalled-test.js index 28bc43f11..bf7f3bc52 100644 --- a/packages/local-cli/link/__tests__/android/isInstalled-test.js +++ b/packages/local-cli/link/__tests__/android/isInstalled-test.js @@ -8,15 +8,13 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const isInstalled = require('../../android/isInstalled'); const projectConfig = { buildGradlePath: path.join( __dirname, - '../../__fixtures__/android/patchedBuild.gradle', + '../../__fixtures__/android/patchedBuild.gradle' ), }; diff --git a/packages/local-cli/link/__tests__/android/makeBuildPatch-test.js b/packages/local-cli/link/__tests__/android/makeBuildPatch-test.js index e630f7664..a5c1a67e4 100644 --- a/packages/local-cli/link/__tests__/android/makeBuildPatch-test.js +++ b/packages/local-cli/link/__tests__/android/makeBuildPatch-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const makeBuildPatch = require('../../android/patches/makeBuildPatch'); const normalizeProjectName = require('../../android/patches/normalizeProjectName'); @@ -20,17 +18,17 @@ const normalizedScopedName = normalizeProjectName('@scoped/test'); describe('makeBuildPatch', () => { it('should build a patch function', () => { expect(Object.prototype.toString(makeBuildPatch(name))).toBe( - '[object Object]', + '[object Object]' ); }); it('should make a correct patch', () => { - const {patch} = makeBuildPatch(name); + const { patch } = makeBuildPatch(name); expect(patch).toBe(` implementation project(':${name}')\n`); }); it('should make a correct install check pattern', () => { - const {installPattern} = makeBuildPatch(name); + const { installPattern } = makeBuildPatch(name); const match = `/\\s{4}(implementation)(\\(|\\s)(project)\\(\\':${name}\\'\\)(\\)|\\s)/`; expect(installPattern.toString()).toBe(match); }); @@ -38,14 +36,14 @@ describe('makeBuildPatch', () => { describe('makeBuildPatchWithScopedPackage', () => { it('should make a correct patch', () => { - const {patch} = makeBuildPatch(scopedName); + const { patch } = makeBuildPatch(scopedName); expect(patch).toBe( - ` implementation project(':${normalizedScopedName}')\n`, + ` implementation project(':${normalizedScopedName}')\n` ); }); it('should make a correct install check pattern', () => { - const {installPattern} = makeBuildPatch(scopedName); + const { installPattern } = makeBuildPatch(scopedName); const match = `/\\s{4}(implementation)(\\(|\\s)(project)\\(\\':${normalizedScopedName}\\'\\)(\\)|\\s)/`; expect(installPattern.toString()).toBe(match); }); diff --git a/packages/local-cli/link/__tests__/android/makeImportPatch-test.js b/packages/local-cli/link/__tests__/android/makeImportPatch-test.js index 8a5d32358..8fcb305c0 100644 --- a/packages/local-cli/link/__tests__/android/makeImportPatch-test.js +++ b/packages/local-cli/link/__tests__/android/makeImportPatch-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const makeImportPatch = require('../../android/patches/makeImportPatch'); const packageImportPath = 'import some.example.project'; @@ -17,13 +15,13 @@ const packageImportPath = 'import some.example.project'; describe('makeImportPatch', () => { it('should build a patch', () => { expect(Object.prototype.toString(makeImportPatch(packageImportPath))).toBe( - '[object Object]', + '[object Object]' ); }); it('MainActivity contains a correct import patch', () => { - const {patch} = makeImportPatch(packageImportPath); + const { patch } = makeImportPatch(packageImportPath); - expect(patch).toBe('\n' + packageImportPath); + expect(patch).toBe(`\n${packageImportPath}`); }); }); diff --git a/packages/local-cli/link/__tests__/android/makePackagePatch-test.js b/packages/local-cli/link/__tests__/android/makePackagePatch-test.js index 6dada4508..23a4eba1e 100644 --- a/packages/local-cli/link/__tests__/android/makePackagePatch-test.js +++ b/packages/local-cli/link/__tests__/android/makePackagePatch-test.js @@ -3,12 +3,9 @@ * * 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'; +/* eslint-disable no-template-curly-in-string */ const makePackagePatch = require('../../android/patches/makePackagePatch'); const applyParams = require('../../android/patches/applyParams'); @@ -27,9 +24,9 @@ describe('makePackagePatch@0.20', () => { }); it('MainActivity contains a correct 0.20 import patch', () => { - const {patch} = makePackagePatch(packageInstance, params, name); + const { patch } = makePackagePatch(packageInstance, params, name); const processedInstance = applyParams(packageInstance, params, name); - expect(patch).toBe(',\n ' + processedInstance); + expect(patch).toBe(`,\n ${processedInstance}`); }); }); diff --git a/packages/local-cli/link/__tests__/android/makeSettingsPatch-test.js b/packages/local-cli/link/__tests__/android/makeSettingsPatch-test.js index 6df7b0dd9..e16adbbaf 100644 --- a/packages/local-cli/link/__tests__/android/makeSettingsPatch-test.js +++ b/packages/local-cli/link/__tests__/android/makeSettingsPatch-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const makeSettingsPatch = require('../../android/patches/makeSettingsPatch'); const normalizeProjectName = require('../../android/patches/normalizeProjectName'); @@ -32,23 +30,23 @@ describe('makeSettingsPatch', () => { it('should build a patch function', () => { expect( Object.prototype.toString( - makeSettingsPatch(name, dependencyConfig, projectConfig), - ), + 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); + const { patch } = makeSettingsPatch(name, dependencyConfig, projectConfig); expect(patch).toBe( `include ':${name}'\n` + `project(':${name}').projectDir = ` + - `new File(rootProject.projectDir, '${projectDir}')\n`, + `new File(rootProject.projectDir, '${projectDir}')\n` ); }); }); @@ -57,27 +55,27 @@ describe('makeSettingsPatchWithScopedPackage', () => { it('should build a patch function', () => { expect( Object.prototype.toString( - makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig), - ), + 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( + const { patch } = makeSettingsPatch( scopedName, scopedDependencyConfig, - projectConfig, + projectConfig ); expect(patch).toBe( `include ':${normalizedScopedName}'\n` + `project(':${normalizedScopedName}').projectDir = ` + - `new File(rootProject.projectDir, '${projectDir}')\n`, + `new File(rootProject.projectDir, '${projectDir}')\n` ); }); }); diff --git a/packages/local-cli/link/__tests__/android/makeStringsPatch-test.js b/packages/local-cli/link/__tests__/android/makeStringsPatch-test.js index 4ea281640..1d7b2553e 100644 --- a/packages/local-cli/link/__tests__/android/makeStringsPatch-test.js +++ b/packages/local-cli/link/__tests__/android/makeStringsPatch-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const makeStringsPatch = require('../../android/patches/makeStringsPatch'); describe('makeStringsPatch', () => { @@ -19,7 +17,7 @@ describe('makeStringsPatch', () => { }; expect(makeStringsPatch(params, 'module').patch).toContain( - 'valueA', + 'valueA' ); }); diff --git a/packages/local-cli/link/__tests__/android/normalizeProjectName-test.js b/packages/local-cli/link/__tests__/android/normalizeProjectName-test.js index 93f425fd2..6d8c9c8b9 100644 --- a/packages/local-cli/link/__tests__/android/normalizeProjectName-test.js +++ b/packages/local-cli/link/__tests__/android/normalizeProjectName-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const normalizeProjectName = require('../../android/patches/normalizeProjectName'); const name = 'test'; diff --git a/packages/local-cli/link/__tests__/getDependencyConfig-test.js b/packages/local-cli/link/__tests__/getDependencyConfig-test.js index 78a4bfdbe..267da1254 100644 --- a/packages/local-cli/link/__tests__/getDependencyConfig-test.js +++ b/packages/local-cli/link/__tests__/getDependencyConfig-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const platforms = { ios: { dependencyConfig: () => ({ sampleiOSKey: '' }), @@ -19,7 +17,7 @@ const platforms = { }, }; -jest.setMock('../../core/getPackageConfiguration', (folder) => { +jest.setMock('../../core/getPackageConfiguration', folder => { if (folder === '/root/node_modules/abcd') { throw new Error('Cannot require'); } @@ -30,17 +28,18 @@ const getDependencyConfig = require('../getDependencyConfig'); describe('getDependencyConfig', () => { it("should return an array of dependencies' config", () => { - const dependencies = getDependencyConfig({ root: '/root' }, platforms, ['react-native-windows']); + const dependencies = getDependencyConfig({ root: '/root' }, platforms, [ + 'react-native-windows', + ]); expect(dependencies).toMatchSnapshot(); }); it('should filter out invalid react-native projects', () => { - const dependencies = getDependencyConfig( - { root: '/root' }, - platforms, - ['react-native-windows', 'abcd'] - ); + const dependencies = getDependencyConfig({ root: '/root' }, platforms, [ + 'react-native-windows', + 'abcd', + ]); expect(dependencies).toMatchSnapshot(); }); diff --git a/packages/local-cli/link/__tests__/getProjectDependencies-test.js b/packages/local-cli/link/__tests__/getProjectDependencies-test.js index 82a5e0109..268a48436 100644 --- a/packages/local-cli/link/__tests__/getProjectDependencies-test.js +++ b/packages/local-cli/link/__tests__/getProjectDependencies-test.js @@ -9,10 +9,8 @@ * @format */ -'use strict'; - -const getProjectDependencies = require('../getProjectDependencies'); const path = require('path'); +const getProjectDependencies = require('../getProjectDependencies'); const CWD = path.resolve(__dirname, '../../'); @@ -22,7 +20,11 @@ describe('getProjectDependencies', () => { }); it('should return an array of project dependencies', () => { jest.setMock(path.join(CWD, './package.json'), { - dependencies: {lodash: '^6.0.0', 'react-native': '^16.0.0', 'react-native-local-cli': '*'}, + dependencies: { + lodash: '^6.0.0', + 'react-native': '^16.0.0', + 'react-native-local-cli': '*', + }, }); expect(getProjectDependencies(CWD)).toEqual(['lodash']); diff --git a/packages/local-cli/link/__tests__/groupFilesByType-test.js b/packages/local-cli/link/__tests__/groupFilesByType-test.js index 173857927..1d86a1cbb 100644 --- a/packages/local-cli/link/__tests__/groupFilesByType-test.js +++ b/packages/local-cli/link/__tests__/groupFilesByType-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const groupFilesByType = require('../groupFilesByType'); describe('groupFilesByType', () => { diff --git a/packages/local-cli/link/__tests__/ios/addFileToProject-test.js b/packages/local-cli/link/__tests__/ios/addFileToProject-test.js index 397b25019..ad3eefbb6 100644 --- a/packages/local-cli/link/__tests__/ios/addFileToProject-test.js +++ b/packages/local-cli/link/__tests__/ios/addFileToProject-test.js @@ -8,15 +8,13 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const path = require('path'); -const addFileToProject = require('../../ios/addFileToProject'); const _ = require('lodash'); +const addFileToProject = require('../../ios/addFileToProject'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::addFileToProject', () => { @@ -25,12 +23,12 @@ describe('ios::addFileToProject', () => { }); it('should add file to a project', () => { - const fileRef = addFileToProject( + const { fileRef } = addFileToProject( project, - '../../__fixtures__/linearGradient.pbxproj', - ).fileRef; + '../../__fixtures__/linearGradient.pbxproj' + ); expect( - _.includes(Object.keys(project.pbxFileReferenceSection()), fileRef), + _.includes(Object.keys(project.pbxFileReferenceSection()), fileRef) ).toBeTruthy(); }); }); diff --git a/packages/local-cli/link/__tests__/ios/addProjectToLibraries-test.js b/packages/local-cli/link/__tests__/ios/addProjectToLibraries-test.js index 9a921c217..c7deab740 100644 --- a/packages/local-cli/link/__tests__/ios/addProjectToLibraries-test.js +++ b/packages/local-cli/link/__tests__/ios/addProjectToLibraries-test.js @@ -8,16 +8,15 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const path = require('path'); const PbxFile = require('xcode/lib/pbxFile'); +const { last } = require('lodash'); + 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/packages/local-cli/link/__tests__/ios/addSharedLibraries-test.js b/packages/local-cli/link/__tests__/ios/addSharedLibraries-test.js index c4a262015..5c5fb181c 100644 --- a/packages/local-cli/link/__tests__/ios/addSharedLibraries-test.js +++ b/packages/local-cli/link/__tests__/ios/addSharedLibraries-test.js @@ -8,15 +8,13 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const path = require('path'); 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', () => { @@ -34,11 +32,11 @@ describe('ios::addSharedLibraries', () => { addSharedLibraries(project, ['libz.tbd']); const frameworksGroup = getGroup(project, 'Frameworks'); - expect(frameworksGroup.children.length).toEqual(1); + expect(frameworksGroup.children).toHaveLength(1); expect(frameworksGroup.children[0].comment).toEqual('libz.tbd'); addSharedLibraries(project, ['MessageUI.framework']); - expect(frameworksGroup.children.length).toEqual(2); + expect(frameworksGroup.children).toHaveLength(2); }); it('should not add duplicate libraries to project', () => { @@ -46,6 +44,6 @@ describe('ios::addSharedLibraries', () => { addSharedLibraries(project, ['libz.tbd']); const frameworksGroup = getGroup(project, 'Frameworks'); - expect(frameworksGroup.children.length).toEqual(1); + expect(frameworksGroup.children).toHaveLength(1); }); }); diff --git a/packages/local-cli/link/__tests__/ios/createGroup-test.js b/packages/local-cli/link/__tests__/ios/createGroup-test.js index 6100b92d0..c96f8543b 100644 --- a/packages/local-cli/link/__tests__/ios/createGroup-test.js +++ b/packages/local-cli/link/__tests__/ios/createGroup-test.js @@ -8,16 +8,15 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const path = require('path'); +const { last } = require('lodash'); + const createGroup = require('../../ios/createGroup'); 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', () => { @@ -50,8 +49,8 @@ describe('ios::createGroup', () => { const mainGroup = getGroup(project); expect( - mainGroup.children.filter(group => group.comment === 'Libraries').length, - ).toBe(1); + mainGroup.children.filter(group => group.comment === 'Libraries') + ).toHaveLength(1); expect(last(outerGroup.children).comment).toBe(createdGroup.name); }); }); diff --git a/packages/local-cli/link/__tests__/ios/getBuildProperty-test.js b/packages/local-cli/link/__tests__/ios/getBuildProperty-test.js index ff5c622eb..8c2618ca8 100644 --- a/packages/local-cli/link/__tests__/ios/getBuildProperty-test.js +++ b/packages/local-cli/link/__tests__/ios/getBuildProperty-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); 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/packages/local-cli/link/__tests__/ios/getGroup-test.js b/packages/local-cli/link/__tests__/ios/getGroup-test.js index a08434d26..c9f61fc80 100644 --- a/packages/local-cli/link/__tests__/ios/getGroup-test.js +++ b/packages/local-cli/link/__tests__/ios/getGroup-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const getGroup = require('../../ios/getGroup'); const path = require('path'); +const getGroup = require('../../ios/getGroup'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::getGroup', () => { @@ -31,7 +29,7 @@ describe('ios::getGroup', () => { it('should return nested group when specified', () => { const group = getGroup(project, 'NestedGroup/Libraries'); - expect(group.children.length).toBe(0); // our test nested Libraries is empty + expect(group.children).toHaveLength(0); // our test nested Libraries is empty expect(group.name).toBe('Libraries'); }); diff --git a/packages/local-cli/link/__tests__/ios/getHeaderSearchPath-test.js b/packages/local-cli/link/__tests__/ios/getHeaderSearchPath-test.js index 551834607..35cb07e54 100644 --- a/packages/local-cli/link/__tests__/ios/getHeaderSearchPath-test.js +++ b/packages/local-cli/link/__tests__/ios/getHeaderSearchPath-test.js @@ -8,10 +8,8 @@ * @emails oncall+javascript_foundation */ -'use strict'; - -const getHeaderSearchPath = require('../../ios/getHeaderSearchPath'); const path = require('path'); +const getHeaderSearchPath = require('../../ios/getHeaderSearchPath'); const SRC_DIR = path.join('react-native-project', 'ios'); @@ -25,7 +23,7 @@ describe('ios::getHeaderSearchPath', () => { 'react-native-project', 'node_modules', 'package', - 'Gradient.h', + 'Gradient.h' ), path.join('react-native-project', 'node_modules', 'package', 'Manager.h'), ]; @@ -33,7 +31,7 @@ describe('ios::getHeaderSearchPath', () => { const searchPath = getHeaderSearchPath(SRC_DIR, files); expect(searchPath).toBe( - `"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"`, + `"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"` ); }); @@ -48,7 +46,7 @@ describe('ios::getHeaderSearchPath', () => { 'package', 'src', 'folderA', - 'Gradient.h', + 'Gradient.h' ), path.join( 'react-native-project', @@ -56,7 +54,7 @@ describe('ios::getHeaderSearchPath', () => { 'package', 'src', 'folderB', - 'Manager.h', + 'Manager.h' ), ]; @@ -64,8 +62,8 @@ describe('ios::getHeaderSearchPath', () => { expect(searchPath).toBe( `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join( - path.sep, - )}/**"`, + path.sep + )}/**"` ); }); @@ -80,7 +78,7 @@ describe('ios::getHeaderSearchPath', () => { 'package', 'src', 'folderA', - 'Gradient.h', + 'Gradient.h' ), path.join( 'react-native-project', @@ -88,14 +86,14 @@ describe('ios::getHeaderSearchPath', () => { 'package', 'src', 'folderB', - 'Manager.h', + 'Manager.h' ), path.join( 'react-native-project', 'node_modules', 'package', 'src', - 'Manager.h', + 'Manager.h' ), ]; @@ -103,8 +101,8 @@ describe('ios::getHeaderSearchPath', () => { expect(searchPath).toBe( `"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join( - path.sep, - )}/**"`, + path.sep + )}/**"` ); }); }); diff --git a/packages/local-cli/link/__tests__/ios/getHeadersInFolder-test.js b/packages/local-cli/link/__tests__/ios/getHeadersInFolder-test.js index d590d6c73..c5da4d023 100644 --- a/packages/local-cli/link/__tests__/ios/getHeadersInFolder-test.js +++ b/packages/local-cli/link/__tests__/ios/getHeadersInFolder-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const getHeadersInFolder = require('../../ios/getHeadersInFolder'); describe('ios::getHeadersInFolder', () => { @@ -21,10 +19,10 @@ describe('ios::getHeadersInFolder', () => { const foundHeaders = getHeadersInFolder(process.cwd()); - expect(foundHeaders.length).toBe(2); + expect(foundHeaders).toHaveLength(2); getHeadersInFolder(process.cwd()).forEach(headerPath => { - expect(headerPath).to.contain(process.cwd()); + expect(headerPath.includes(process.cwd())).toBe(true); }); }); @@ -43,6 +41,6 @@ describe('ios::getHeadersInFolder', () => { }, }); - expect(getHeadersInFolder(process.cwd()).length).to.equals(2); + expect(getHeadersInFolder(process.cwd())).toEqual(2); }); }); diff --git a/packages/local-cli/link/__tests__/ios/getPlist-test.js b/packages/local-cli/link/__tests__/ios/getPlist-test.js index f229af7a4..609132ad4 100644 --- a/packages/local-cli/link/__tests__/ios/getPlist-test.js +++ b/packages/local-cli/link/__tests__/ios/getPlist-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const getPlist = require('../../ios/getPlist'); const path = require('path'); +const getPlist = require('../../ios/getPlist'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::getPlist', () => { diff --git a/packages/local-cli/link/__tests__/ios/getPlistPath-test.js b/packages/local-cli/link/__tests__/ios/getPlistPath-test.js index ae2de5914..c0fa8aef8 100644 --- a/packages/local-cli/link/__tests__/ios/getPlistPath-test.js +++ b/packages/local-cli/link/__tests__/ios/getPlistPath-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const getPlistPath = require('../../ios/getPlistPath'); const path = require('path'); +const getPlistPath = require('../../ios/getPlistPath'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::getPlistPath', () => { diff --git a/packages/local-cli/link/__tests__/ios/getTargets-test.js b/packages/local-cli/link/__tests__/ios/getTargets-test.js index 0f1142b5e..10a8bcad4 100644 --- a/packages/local-cli/link/__tests__/ios/getTargets-test.js +++ b/packages/local-cli/link/__tests__/ios/getTargets-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const getTargets = require('../../ios/getTargets'); const path = require('path'); +const getTargets = require('../../ios/getTargets'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::getTargets', () => { @@ -25,7 +23,7 @@ describe('ios::getTargets', () => { it('should return an array of project targets', () => { const targets = getTargets(project); - expect(targets.length).toBe(2); + expect(targets).toHaveLength(2); expect(targets[0].name).toContain('Basic.app'); expect(targets[1].name).toContain('BasicTests.xctest'); }); diff --git a/packages/local-cli/link/__tests__/ios/hasLibraryImported-test.js b/packages/local-cli/link/__tests__/ios/hasLibraryImported-test.js index b36fbd78d..3f495522e 100644 --- a/packages/local-cli/link/__tests__/ios/hasLibraryImported-test.js +++ b/packages/local-cli/link/__tests__/ios/hasLibraryImported-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const hasLibraryImported = require('../../ios/hasLibraryImported'); const path = require('path'); +const hasLibraryImported = require('../../ios/hasLibraryImported'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::hasLibraryImported', () => { diff --git a/packages/local-cli/link/__tests__/ios/isInstalled-test.js b/packages/local-cli/link/__tests__/ios/isInstalled-test.js index 5998c2e51..9c4fea215 100644 --- a/packages/local-cli/link/__tests__/ios/isInstalled-test.js +++ b/packages/local-cli/link/__tests__/ios/isInstalled-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const isInstalled = require('../../ios/isInstalled'); @@ -20,17 +18,17 @@ 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 dependencyConfig = { projectName: 'React.xcodeproj' }; const projectConfig = Object.assign({}, baseProjectConfig, { libraryFolder: 'Missing', }); diff --git a/packages/local-cli/link/__tests__/ios/mapHeaderSearchPaths-test.js b/packages/local-cli/link/__tests__/ios/mapHeaderSearchPaths-test.js index 0be5740c2..99e3ae958 100644 --- a/packages/local-cli/link/__tests__/ios/mapHeaderSearchPaths-test.js +++ b/packages/local-cli/link/__tests__/ios/mapHeaderSearchPaths-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); -const mapHeaderSearchPaths = require('../../ios/mapHeaderSearchPaths'); const path = require('path'); +const mapHeaderSearchPaths = require('../../ios/mapHeaderSearchPaths'); const project = xcode.project( - path.join(__dirname, '../../__fixtures__/project.pbxproj'), + path.join(__dirname, '../../__fixtures__/project.pbxproj') ); describe('ios::mapHeaderSearchPaths', () => { @@ -31,7 +29,7 @@ describe('ios::mapHeaderSearchPaths', () => { const callback = jest.fn(); mapHeaderSearchPaths(project, callback); - expect(callback.mock.calls.length).toBe(2); + expect(callback.mock.calls).toHaveLength(2); }); it('calls the function with an array of paths, given a project with one', () => { @@ -41,7 +39,7 @@ describe('ios::mapHeaderSearchPaths', () => { const paths = callback.mock.calls[0][0]; expect(paths instanceof Array).toBe(true); - expect(paths.length).toBe(1); + expect(paths).toHaveLength(1); expect(paths[0]).toBe('"$(inherited)"'); }); }); diff --git a/packages/local-cli/link/__tests__/ios/removeProjectFromLibraries-test.js b/packages/local-cli/link/__tests__/ios/removeProjectFromLibraries-test.js index 1abf072a1..e21f84d45 100644 --- a/packages/local-cli/link/__tests__/ios/removeProjectFromLibraries-test.js +++ b/packages/local-cli/link/__tests__/ios/removeProjectFromLibraries-test.js @@ -8,17 +8,16 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const PbxFile = require('xcode/lib/pbxFile'); +const path = require('path'); +const { last } = require('lodash'); + const addProjectToLibraries = require('../../ios/addProjectToLibraries'); const removeProjectFromLibraries = require('../../ios/removeProjectFromLibraries'); -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', () => { @@ -27,7 +26,7 @@ describe('ios::removeProjectFromLibraries', () => { addProjectToLibraries( project.pbxGroupByName('Libraries'), - new PbxFile('fakePath'), + new PbxFile('fakePath') ); }); diff --git a/packages/local-cli/link/__tests__/ios/removeProjectFromProject-test.js b/packages/local-cli/link/__tests__/ios/removeProjectFromProject-test.js index 257e9f0e7..a1a9ea1ef 100644 --- a/packages/local-cli/link/__tests__/ios/removeProjectFromProject-test.js +++ b/packages/local-cli/link/__tests__/ios/removeProjectFromProject-test.js @@ -8,16 +8,14 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const pbxFile = require('xcode/lib/pbxFile'); +const path = require('path'); const addFileToProject = require('../../ios/addFileToProject'); 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'; @@ -29,7 +27,7 @@ describe('ios::addFileToProject', () => { it('should return removed file', () => { expect( - removeProjectFromProject(project, filePath) instanceof pbxFile, + removeProjectFromProject(project, filePath) instanceof pbxFile ).toBeTruthy(); }); diff --git a/packages/local-cli/link/__tests__/ios/removeSharedLibrary-test.js b/packages/local-cli/link/__tests__/ios/removeSharedLibrary-test.js index 5f983e551..f119fea97 100644 --- a/packages/local-cli/link/__tests__/ios/removeSharedLibrary-test.js +++ b/packages/local-cli/link/__tests__/ios/removeSharedLibrary-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const xcode = require('xcode'); const path = require('path'); const addSharedLibraries = require('../../ios/addSharedLibraries'); @@ -17,7 +15,7 @@ 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', () => { @@ -30,7 +28,7 @@ describe('ios::removeSharedLibraries', () => { removeSharedLibraries(project, ['libc++.tbd']); const frameworksGroup = getGroup(project, 'Frameworks'); - expect(frameworksGroup.children.length).toEqual(1); + expect(frameworksGroup.children).toHaveLength(1); expect(frameworksGroup.children[0].comment).toEqual('libz.tbd'); }); @@ -38,6 +36,6 @@ describe('ios::removeSharedLibraries', () => { removeSharedLibraries(project, ['libxml2.tbd']); const frameworksGroup = getGroup(project, 'Frameworks'); - expect(frameworksGroup.children.length).toEqual(2); + expect(frameworksGroup.children).toHaveLength(2); }); }); diff --git a/packages/local-cli/link/__tests__/ios/writePlist-test.js b/packages/local-cli/link/__tests__/ios/writePlist-test.js index 36afc2255..c21011a8d 100644 --- a/packages/local-cli/link/__tests__/ios/writePlist-test.js +++ b/packages/local-cli/link/__tests__/ios/writePlist-test.js @@ -8,10 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - -const getPlistPath = require('../../ios/getPlistPath'); - jest.mock('path'); jest.mock('fs'); jest.mock('../../ios/getPlistPath', () => jest.fn(() => null)); @@ -20,6 +16,7 @@ const { readFileSync } = jest.requireActual('fs'); const fs = require('fs'); const xcode = require('xcode'); +const getPlistPath = require('../../ios/getPlistPath'); const writePlist = require('../../ios/writePlist'); const realPath = jest.requireActual('path'); @@ -51,7 +48,10 @@ describe('ios::writePlist', () => { getPlistPath.mockImplementation(() => '/Basic/Info.plist'); writePlist(project, '/', plist); const infoPlist = readFileSync(infoPlistPath).toString(); - expect(fs.writeFileSync).toHaveBeenCalledWith('/Basic/Info.plist', infoPlist); + expect(fs.writeFileSync).toHaveBeenCalledWith( + '/Basic/Info.plist', + infoPlist + ); }); it('when plistPath is null it should return null', () => { diff --git a/packages/local-cli/link/__tests__/link-test.js b/packages/local-cli/link/__tests__/link-test.js index 6e9d71141..0f80fb7a9 100644 --- a/packages/local-cli/link/__tests__/link-test.js +++ b/packages/local-cli/link/__tests__/link-test.js @@ -8,11 +8,9 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const log = require('npmlog'); -jest.setMock('chalk', {grey: str => str}); +jest.setMock('chalk', { grey: str => str }); const context = { root: process.cwd(), @@ -31,14 +29,16 @@ describe('link', () => { }); it('should accept a name of a dependency to link', done => { - const getDependencyConfig = jest.fn(() => [{ - config: { - ios: null, - android: null, + const getDependencyConfig = jest.fn(() => [ + { + config: { + ios: null, + android: null, + }, + assets: [], + commands: {}, }, - assets: [], - commands: {} - }]); + ]); jest.setMock('../getDependencyConfig', getDependencyConfig); @@ -52,23 +52,23 @@ describe('link', () => { }); it('should accept the name of a dependency with a scope / tag', async () => { - const getDependencyConfig = jest.fn(() => [{ - config: { - ios: null, - android: null, + const getDependencyConfig = jest.fn(() => [ + { + config: { + ios: null, + android: null, + }, + assets: [], + commands: {}, }, - assets: [], - commands: {} - }]); + ]); jest.setMock('../getDependencyConfig', getDependencyConfig); const link = require('../link').func; await link(['@scope/something@latest'], context); - - expect(getDependencyConfig.mock.calls[0][2]).toEqual([ - '@scope/something', - ]); + + expect(getDependencyConfig.mock.calls[0][2]).toEqual(['@scope/something']); }); it('should register native module when android/ios projects are present', done => { @@ -80,14 +80,16 @@ describe('link', () => { android: {}, })); - const getDependencyConfig = jest.fn(() => [{ - config: { - ios: {}, - android: {}, + const getDependencyConfig = jest.fn(() => [ + { + config: { + ios: {}, + android: {}, + }, + assets: [], + commands: { prelink, postlink }, }, - assets: [], - commands: {prelink, postlink} - }]); + ]); jest.setMock('../getDependencyConfig', getDependencyConfig); @@ -95,21 +97,21 @@ describe('link', () => { jest.setMock('../android/isInstalled.js', jest.fn().mockReturnValue(false)); jest.setMock('../android/registerNativeModule.js', registerNativeModule); - + jest.setMock('../ios/isInstalled.js', jest.fn().mockReturnValue(false)); jest.setMock('../ios/registerNativeModule.js', registerNativeModule); const link = require('../link').func; link(['react-native-blur'], context).then(() => { - expect(registerNativeModule.mock.calls.length).toBe(2); + expect(registerNativeModule.mock.calls).toHaveLength(2); expect(prelink.mock.invocationCallOrder[0]).toBeLessThan( - registerNativeModule.mock.invocationCallOrder[0], + registerNativeModule.mock.invocationCallOrder[0] ); expect(postlink.mock.invocationCallOrder[0]).toBeGreaterThan( - registerNativeModule.mock.invocationCallOrder[0], + registerNativeModule.mock.invocationCallOrder[0] ); done(); @@ -119,24 +121,26 @@ describe('link', () => { it('should copy assets from both project and dependencies projects', done => { const dependencyAssets = ['Fonts/Font.ttf']; const projectAssets = ['Fonts/FontC.ttf']; - + jest.setMock('../getProjectConfig', () => ({ ios: {}, android: {}, })); - jest.setMock('../getDependencyConfig', () => [{ - config: { - ios: {}, - android: {}, + jest.setMock('../getDependencyConfig', () => [ + { + config: { + ios: {}, + android: {}, + }, + assets: dependencyAssets, + commands: {}, }, - assets: dependencyAssets, - commands: {} - }]); + ]); jest.setMock('../android/isInstalled.js', jest.fn().mockReturnValue(false)); jest.setMock('../android/registerNativeModule.js', jest.fn()); - + jest.setMock('../ios/isInstalled.js', jest.fn().mockReturnValue(false)); jest.setMock('../ios/registerNativeModule.js', jest.fn()); @@ -150,9 +154,9 @@ describe('link', () => { const link = require('../link').func; link(['react-native-blur'], context).then(() => { - expect(copyAssets.mock.calls.length).toBe(2); + expect(copyAssets.mock.calls).toHaveLength(2); expect(copyAssets.mock.calls[0][0]).toEqual( - projectAssets.concat(dependencyAssets), + projectAssets.concat(dependencyAssets) ); jest.unmock('../../core/getAssets'); done(); @@ -165,14 +169,16 @@ describe('link', () => { android: {}, })); - const getDependencyConfig = jest.fn(() => [{ - config: { - ios: {}, - android: {}, + const getDependencyConfig = jest.fn(() => [ + { + config: { + ios: {}, + android: {}, + }, + assets: [], + commands: {}, }, - assets: [], - commands: {} - }]); + ]); jest.setMock('../getDependencyConfig', getDependencyConfig); @@ -180,14 +186,14 @@ describe('link', () => { jest.setMock('../android/isInstalled.js', jest.fn().mockReturnValue(true)); jest.setMock('../android/registerNativeModule.js', registerNativeModule); - + jest.setMock('../ios/isInstalled.js', jest.fn().mockReturnValue(true)); jest.setMock('../ios/registerNativeModule.js', registerNativeModule); const link = require('../link').func; link(['react-native-blur'], context).then(() => { - expect(registerNativeModule.mock.calls.length).toEqual(0); + expect(registerNativeModule.mock.calls).toHaveLength(0); done(); }); }); @@ -205,35 +211,37 @@ describe('link', () => { isInstalled: () => false, register: registerNativeModule, }); - - const getDependencyConfig = jest.fn(() => [{ - config: { - ios: {}, - android: {}, - windows: {} + + const getDependencyConfig = jest.fn(() => [ + { + config: { + ios: {}, + android: {}, + windows: {}, + }, + assets: [], + commands: {}, }, - assets: [], - commands: {} - }]); + ]); jest.setMock('../../core/getPlatforms', () => ({ - ios: {linkConfig: require('../ios')}, - android: {linkConfig: require('../android')}, - windows: {linkConfig: genericLinkConfig}, + ios: { linkConfig: require('../ios') }, + android: { linkConfig: require('../android') }, + windows: { linkConfig: genericLinkConfig }, })); jest.setMock('../getDependencyConfig', getDependencyConfig); jest.setMock('../android/isInstalled.js', jest.fn().mockReturnValue(true)); jest.setMock('../android/registerNativeModule.js', registerNativeModule); - + jest.setMock('../ios/isInstalled.js', jest.fn().mockReturnValue(true)); jest.setMock('../ios/registerNativeModule.js', registerNativeModule); const link = require('../link').func; link(['react-native-blur'], context).then(() => { - expect(registerNativeModule.mock.calls.length).toBe(1); + expect(registerNativeModule.mock.calls).toHaveLength(1); done(); }); }); diff --git a/packages/local-cli/link/__tests__/pods/findLineToAddPod-test.js b/packages/local-cli/link/__tests__/pods/findLineToAddPod-test.js index d27b341dd..c04ad4ad6 100644 --- a/packages/local-cli/link/__tests__/pods/findLineToAddPod-test.js +++ b/packages/local-cli/link/__tests__/pods/findLineToAddPod-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const findLineToAddPod = require('../../pods/findLineToAddPod'); const readPodfile = require('../../pods/readPodfile'); @@ -21,30 +19,30 @@ 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), + 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}); + 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}); + 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'), + path.join(PODFILES_PATH, 'PodfileWithFunction') ); expect( - findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), - ).toEqual({line: 26, indentation: 2}); + findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE) + ).toEqual({ line: 26, indentation: 2 }); }); }); diff --git a/packages/local-cli/link/__tests__/pods/findMarkedLinesInPodfile-test.js b/packages/local-cli/link/__tests__/pods/findMarkedLinesInPodfile-test.js index 2c9d8decd..dd0ff0f34 100644 --- a/packages/local-cli/link/__tests__/pods/findMarkedLinesInPodfile-test.js +++ b/packages/local-cli/link/__tests__/pods/findMarkedLinesInPodfile-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const readPodfile = require('../../pods/readPodfile'); const findMarkedLinesInPodfile = require('../../pods/findMarkedLinesInPodfile'); @@ -26,18 +24,18 @@ 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), + 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}, + { line: 18, indentation: 2 }, + { line: 31, indentation: 4 }, ]; expect( - findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE), + findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE) ).toEqual(expectedObject); }); }); diff --git a/packages/local-cli/link/__tests__/pods/findPodTargetLine-test.js b/packages/local-cli/link/__tests__/pods/findPodTargetLine-test.js index 6b7b360e0..6b0ff45a3 100644 --- a/packages/local-cli/link/__tests__/pods/findPodTargetLine-test.js +++ b/packages/local-cli/link/__tests__/pods/findPodTargetLine-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const findPodTargetLine = require('../../pods/findPodTargetLine'); const readPodfile = require('../../pods/readPodfile'); @@ -27,7 +25,7 @@ describe('pods::findPodTargetLine', () => { expect(findPodTargetLine(podfile, 'invalidName')).toBeNull(); }); - it('returns null if there is not matching project name', () => { + it('returns correct line if there is a matching project', () => { const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple')); expect(findPodTargetLine(podfile, 'Testing')).toBe(4); }); diff --git a/packages/local-cli/link/__tests__/pods/isInstalled-test.js b/packages/local-cli/link/__tests__/pods/isInstalled-test.js index dbf484574..74c0708f5 100644 --- a/packages/local-cli/link/__tests__/pods/isInstalled-test.js +++ b/packages/local-cli/link/__tests__/pods/isInstalled-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const isInstalled = require('../../pods/isInstalled'); @@ -17,26 +15,28 @@ 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/packages/local-cli/link/__tests__/pods/removePodEntry-test.js b/packages/local-cli/link/__tests__/pods/removePodEntry-test.js index 83106805c..18eb1c1cf 100644 --- a/packages/local-cli/link/__tests__/pods/removePodEntry-test.js +++ b/packages/local-cli/link/__tests__/pods/removePodEntry-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const path = require('path'); const removePodEntry = require('../../pods/removePodEntry'); const readPodfile = require('../../pods/readPodfile'); @@ -18,15 +16,15 @@ 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; @@ -34,8 +32,8 @@ describe('pods::removePodEntry', () => { }); 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; diff --git a/packages/local-cli/link/__tests__/promiseWaterfall-test.js b/packages/local-cli/link/__tests__/promiseWaterfall-test.js index 3507ce991..5a6cfd741 100644 --- a/packages/local-cli/link/__tests__/promiseWaterfall-test.js +++ b/packages/local-cli/link/__tests__/promiseWaterfall-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - const promiseWaterfall = require('../promiseWaterfall'); describe('promiseWaterfall', () => { @@ -20,7 +18,7 @@ describe('promiseWaterfall', () => { // Check that tasks[0] is executed before tasks[1]. expect(tasks[0].mock.invocationCallOrder[0]).toBeLessThan( - tasks[1].mock.invocationCallOrder[0], + tasks[1].mock.invocationCallOrder[0] ); }); @@ -41,7 +39,7 @@ describe('promiseWaterfall', () => { promiseWaterfall(tasks).catch(err => { expect(err).toEqual(error); - expect(tasks[1].mock.calls.length).toEqual(0); + expect(tasks[1].mock.calls).toHaveLength(0); done(); }); }); diff --git a/packages/local-cli/link/android/copyAssets.js b/packages/local-cli/link/android/copyAssets.js index 4b58f46fb..36d54c381 100644 --- a/packages/local-cli/link/android/copyAssets.js +++ b/packages/local-cli/link/android/copyAssets.js @@ -23,7 +23,7 @@ module.exports = function copyAssetsAndroid(files, project) { (assets.font || []).forEach(asset => fs.copySync( asset, - path.join(project.assetsPath, 'fonts', path.basename(asset)), - ), + path.join(project.assetsPath, 'fonts', path.basename(asset)) + ) ); }; diff --git a/packages/local-cli/link/android/index.js b/packages/local-cli/link/android/index.js index d8b8f5add..0e070d783 100644 --- a/packages/local-cli/link/android/index.js +++ b/packages/local-cli/link/android/index.js @@ -7,7 +7,7 @@ * @format */ -module.exports = function() { +module.exports = function getAndroidLinkConfig() { return { isInstalled: require('./isInstalled'), register: require('./registerNativeModule'), diff --git a/packages/local-cli/link/android/patches/applyParams.js b/packages/local-cli/link/android/patches/applyParams.js index 11b66bef2..c34d226ed 100644 --- a/packages/local-cli/link/android/patches/applyParams.js +++ b/packages/local-cli/link/android/patches/applyParams.js @@ -11,7 +11,7 @@ const toCamelCase = require('lodash').camelCase; module.exports = function applyParams(str, params, prefix) { return str.replace(/\$\{(\w+)\}/g, (pattern, param) => { - const name = toCamelCase(prefix) + '_' + param; + const name = `${toCamelCase(prefix)}_${param}`; return params[param] ? `getResources().getString(R.string.${name})` : null; }); diff --git a/packages/local-cli/link/android/patches/applyPatch.js b/packages/local-cli/link/android/patches/applyPatch.js index fd17c80b2..51205e8e4 100644 --- a/packages/local-cli/link/android/patches/applyPatch.js +++ b/packages/local-cli/link/android/patches/applyPatch.js @@ -14,6 +14,6 @@ module.exports = function applyPatch(file, patch) { file, fs .readFileSync(file, 'utf8') - .replace(patch.pattern, match => `${match}${patch.patch}`), + .replace(patch.pattern, match => `${match}${patch.patch}`) ); }; diff --git a/packages/local-cli/link/android/patches/makeBuildPatch.js b/packages/local-cli/link/android/patches/makeBuildPatch.js index db8feb5a8..3572e09c4 100644 --- a/packages/local-cli/link/android/patches/makeBuildPatch.js +++ b/packages/local-cli/link/android/patches/makeBuildPatch.js @@ -12,7 +12,7 @@ const normalizeProjectName = require('./normalizeProjectName'); module.exports = function makeBuildPatch(name) { const normalizedProjectName = normalizeProjectName(name); const installPattern = new RegExp( - `\\s{4}(implementation)(\\(|\\s)(project)\\(\\\':${normalizedProjectName}\\\'\\)(\\)|\\s)`, + `\\s{4}(implementation)(\\(|\\s)(project)\\(\\':${normalizedProjectName}\\'\\)(\\)|\\s)` ); return { diff --git a/packages/local-cli/link/android/patches/makeImportPatch.js b/packages/local-cli/link/android/patches/makeImportPatch.js index 983f2a4e0..7f190d91d 100644 --- a/packages/local-cli/link/android/patches/makeImportPatch.js +++ b/packages/local-cli/link/android/patches/makeImportPatch.js @@ -10,6 +10,6 @@ module.exports = function makeImportPatch(packageImportPath) { return { pattern: 'import com.facebook.react.ReactApplication;', - patch: '\n' + packageImportPath, + patch: `\n${packageImportPath}`, }; }; diff --git a/packages/local-cli/link/android/patches/makePackagePatch.js b/packages/local-cli/link/android/patches/makePackagePatch.js index a4791ef5b..7c1698104 100644 --- a/packages/local-cli/link/android/patches/makePackagePatch.js +++ b/packages/local-cli/link/android/patches/makePackagePatch.js @@ -14,6 +14,6 @@ module.exports = function makePackagePatch(packageInstance, params, prefix) { return { pattern: 'new MainReactPackage()', - patch: ',\n ' + processedInstance, + patch: `,\n ${processedInstance}`, }; }; diff --git a/packages/local-cli/link/android/patches/makeSettingsPatch.js b/packages/local-cli/link/android/patches/makeSettingsPatch.js index a6bf7ca2b..43fc36f56 100644 --- a/packages/local-cli/link/android/patches/makeSettingsPatch.js +++ b/packages/local-cli/link/android/patches/makeSettingsPatch.js @@ -13,11 +13,11 @@ const normalizeProjectName = require('./normalizeProjectName'); module.exports = function makeSettingsPatch( name, androidConfig, - projectConfig, + projectConfig ) { - var projectDir = path.relative( + const projectDir = path.relative( path.dirname(projectConfig.settingsGradlePath), - androidConfig.sourceDir, + androidConfig.sourceDir ); const normalizedProjectName = normalizeProjectName(name); diff --git a/packages/local-cli/link/android/patches/makeStringsPatch.js b/packages/local-cli/link/android/patches/makeStringsPatch.js index efda88671..17838f624 100644 --- a/packages/local-cli/link/android/patches/makeStringsPatch.js +++ b/packages/local-cli/link/android/patches/makeStringsPatch.js @@ -11,14 +11,14 @@ const toCamelCase = require('lodash').camelCase; module.exports = function makeStringsPatch(params, prefix) { const values = Object.keys(params).map(param => { - const name = toCamelCase(prefix) + '_' + 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/packages/local-cli/link/android/patches/revokePatch.js b/packages/local-cli/link/android/patches/revokePatch.js index 070972e42..56e612660 100644 --- a/packages/local-cli/link/android/patches/revokePatch.js +++ b/packages/local-cli/link/android/patches/revokePatch.js @@ -12,6 +12,6 @@ const fs = require('fs'); module.exports = function revokePatch(file, patch) { fs.writeFileSync( file, - fs.readFileSync(file, 'utf8').replace(patch.patch, ''), + fs.readFileSync(file, 'utf8').replace(patch.patch, '') ); }; diff --git a/packages/local-cli/link/android/registerNativeModule.js b/packages/local-cli/link/android/registerNativeModule.js index 67ddfc7eb..1fe3484bd 100644 --- a/packages/local-cli/link/android/registerNativeModule.js +++ b/packages/local-cli/link/android/registerNativeModule.js @@ -18,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); @@ -32,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/packages/local-cli/link/android/unlinkAssets.js b/packages/local-cli/link/android/unlinkAssets.js index fc6f7db39..3f5c8bebd 100644 --- a/packages/local-cli/link/android/unlinkAssets.js +++ b/packages/local-cli/link/android/unlinkAssets.js @@ -24,7 +24,7 @@ module.exports = function unlinkAssetsAndroid(files, project) { const filePath = path.join( project.assetsPath, 'fonts', - path.basename(file), + path.basename(file) ); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); diff --git a/packages/local-cli/link/android/unregisterNativeModule.js b/packages/local-cli/link/android/unregisterNativeModule.js index 27aa977a3..53bbbc522 100644 --- a/packages/local-cli/link/android/unregisterNativeModule.js +++ b/packages/local-cli/link/android/unregisterNativeModule.js @@ -20,22 +20,22 @@ const makePackagePatch = require('./patches/makePackagePatch'); module.exports = function unregisterNativeAndroidModule( name, androidConfig, - projectConfig, + projectConfig ) { const buildPatch = makeBuildPatch(name); const strings = fs.readFileSync(projectConfig.stringsPath, 'utf8'); - var params = {}; + const params = {}; strings.replace( /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); @@ -43,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/packages/local-cli/link/getDependencyConfig.js b/packages/local-cli/link/getDependencyConfig.js index e241be317..673e2f1df 100644 --- a/packages/local-cli/link/getDependencyConfig.js +++ b/packages/local-cli/link/getDependencyConfig.js @@ -2,12 +2,15 @@ * @flow */ -'use strict'; +import type { + PlatformsT, + ContextT, + InquirerPromptT, + DependencyConfigT, +} from '../core/types.flow'; const path = require('path'); -import type { PlatformsT, ContextT, InquirerPromptT, DependencyConfigT } from '../core/types.flow'; - const getPackageConfiguration = require('../core/getPackageConfiguration'); const getParams = require('../core/getParams'); const getHooks = require('../core/getHooks'); @@ -32,13 +35,13 @@ module.exports = function getDependencyConfig( const folder = path.join(ctx.root, 'node_modules', packageName); const config = getPackageConfiguration(folder); - let platformConfigs = {ios: undefined, android: undefined}; + const platformConfigs = { ios: undefined, android: undefined }; - Object.keys(availablePlatforms) - .forEach(platform => { - platformConfigs[platform] = availablePlatforms[platform] - .dependencyConfig(folder, config[platform] || {}); - }); + Object.keys(availablePlatforms).forEach(platform => { + platformConfigs[platform] = availablePlatforms[ + platform + ].dependencyConfig(folder, config[platform] || {}); + }); return acc.concat({ config: platformConfigs, @@ -46,7 +49,7 @@ module.exports = function getDependencyConfig( path: folder, commands: getHooks(folder), assets: getAssets(folder), - params: getParams(folder) + params: getParams(folder), }); } catch (e) { return acc; diff --git a/packages/local-cli/link/getProjectConfig.js b/packages/local-cli/link/getProjectConfig.js index 690507cd7..905022193 100644 --- a/packages/local-cli/link/getProjectConfig.js +++ b/packages/local-cli/link/getProjectConfig.js @@ -2,8 +2,6 @@ * @flow */ -'use strict'; - import type { PlatformsT, ContextT, ProjectConfigT } from '../core/types.flow'; const getPackageConfiguration = require('../core/getPackageConfiguration'); @@ -13,16 +11,15 @@ module.exports = function getProjectConfig( availablePlatforms: PlatformsT ): ProjectConfigT { const config = getPackageConfiguration(ctx.root); - - let platformConfigs = {ios: undefined, android: undefined}; - Object.keys(availablePlatforms) - .forEach(platform => { - platformConfigs[platform] = availablePlatforms[platform] - .projectConfig(ctx.root, config[platform] || {}); - }); - + const platformConfigs = { ios: undefined, android: undefined }; + + Object.keys(availablePlatforms).forEach(platform => { + platformConfigs[platform] = availablePlatforms[platform].projectConfig( + ctx.root, + config[platform] || {} + ); + }); + return platformConfigs; }; - - \ No newline at end of file diff --git a/packages/local-cli/link/getProjectDependencies.js b/packages/local-cli/link/getProjectDependencies.js index 94c0cf2c3..f72e6e5bc 100644 --- a/packages/local-cli/link/getProjectDependencies.js +++ b/packages/local-cli/link/getProjectDependencies.js @@ -10,11 +10,15 @@ const path = require('path'); /** - * List of projects that should not be treated as projects to be linked. - * + * List of projects that should not be treated as projects to be linked. + * * That includes `react-native` itself and the CLI project (under its real and staging npm package). */ -const EXCLUDED_PROJECTS = ['react-native', 'react-native-local-cli', 'react-native-local-cli-preview']; +const EXCLUDED_PROJECTS = [ + 'react-native', + 'react-native-local-cli', + 'react-native-local-cli-preview', +]; /** * Returns an array of dependencies that should be linked/checked. @@ -22,6 +26,6 @@ const EXCLUDED_PROJECTS = ['react-native', 'react-native-local-cli', 'react-nati module.exports = function getProjectDependencies(cwd) { const pjson = require(path.join(cwd || process.cwd(), './package.json')); return Object.keys(pjson.dependencies || {}).filter( - name => EXCLUDED_PROJECTS.includes(name) === false, + name => EXCLUDED_PROJECTS.includes(name) === false ); }; diff --git a/packages/local-cli/link/groupFilesByType.js b/packages/local-cli/link/groupFilesByType.js index d35e8e59e..54cb8ef5d 100644 --- a/packages/local-cli/link/groupFilesByType.js +++ b/packages/local-cli/link/groupFilesByType.js @@ -7,7 +7,7 @@ * @format */ -const groupBy = require('lodash').groupBy; +const { groupBy } = require('lodash'); const mime = require('mime'); /** diff --git a/packages/local-cli/link/ios/addSharedLibraries.js b/packages/local-cli/link/ios/addSharedLibraries.js index c8050689d..a97e3f69a 100644 --- a/packages/local-cli/link/ios/addSharedLibraries.js +++ b/packages/local-cli/link/ios/addSharedLibraries.js @@ -19,7 +19,7 @@ module.exports = function addSharedLibraries(project, libraries) { const target = project.getFirstTarget().uuid; - for (var name of libraries) { - project.addFramework(name, {target}); + for (const name of libraries) { + project.addFramework(name, { target }); } }; diff --git a/packages/local-cli/link/ios/common/registerNativeModule.js b/packages/local-cli/link/ios/common/registerNativeModule.js index 8a86e6887..4b5d0ec86 100644 --- a/packages/local-cli/link/ios/common/registerNativeModule.js +++ b/packages/local-cli/link/ios/common/registerNativeModule.js @@ -14,7 +14,7 @@ module.exports = function registerNativeModule( name, dependencyConfig, params, - projectConfig, + projectConfig ) { if (projectConfig.podfile && dependencyConfig.podspec) { registerDependencyPods(name, dependencyConfig, projectConfig); diff --git a/packages/local-cli/link/ios/common/unregisterNativeModule.js b/packages/local-cli/link/ios/common/unregisterNativeModule.js index 69d25ea59..3cf4c718d 100644 --- a/packages/local-cli/link/ios/common/unregisterNativeModule.js +++ b/packages/local-cli/link/ios/common/unregisterNativeModule.js @@ -7,7 +7,7 @@ * @format */ -const compact = require('lodash').compact; +const { compact } = require('lodash'); const isInstalledIOS = require('../isInstalled'); const isInstalledPods = require('../../pods/isInstalled'); const unregisterDependencyIOS = require('../unregisterNativeModule'); @@ -17,7 +17,7 @@ module.exports = function unregisterNativeModule( name, dependencyConfig, projectConfig, - otherDependencies, + otherDependencies ) { const isIosInstalled = isInstalledIOS(projectConfig, dependencyConfig); const isPodInstalled = isInstalledPods(projectConfig, dependencyConfig); diff --git a/packages/local-cli/link/ios/copyAssets.js b/packages/local-cli/link/ios/copyAssets.js index 314b68b60..cca28d8ac 100644 --- a/packages/local-cli/link/ios/copyAssets.js +++ b/packages/local-cli/link/ios/copyAssets.js @@ -31,7 +31,7 @@ module.exports = function linkAssetsIOS(files, projectConfig) { .map(asset => project.addResourceFile(path.relative(projectConfig.sourceDir, asset), { target: project.getFirstTarget().uuid, - }), + }) ) .filter(file => file) // xcode returns false if file is already there .map(file => file.basename); diff --git a/packages/local-cli/link/ios/createGroupWithMessage.js b/packages/local-cli/link/ios/createGroupWithMessage.js index c353d9159..f89eb4299 100644 --- a/packages/local-cli/link/ios/createGroupWithMessage.js +++ b/packages/local-cli/link/ios/createGroupWithMessage.js @@ -19,14 +19,14 @@ const getGroup = require('./getGroup'); * Returns the existing or newly created group */ module.exports = function createGroupWithMessage(project, path) { - var group = getGroup(project, path); + let group = getGroup(project, path); if (!group) { group = createGroup(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/packages/local-cli/link/ios/getGroup.js b/packages/local-cli/link/ios/getGroup.js index c53e731d9..0d1925c36 100644 --- a/packages/local-cli/link/ios/getGroup.js +++ b/packages/local-cli/link/ios/getGroup.js @@ -29,8 +29,8 @@ module.exports = function getGroup(project, path) { return groups; } - for (var name of path.split('/')) { - var foundGroup = findGroup(groups, name); + for (const name of path.split('/')) { + const foundGroup = findGroup(groups, name); if (foundGroup) { groups = project.getPBXGroupByKey(foundGroup.value); diff --git a/packages/local-cli/link/ios/getHeaderSearchPath.js b/packages/local-cli/link/ios/getHeaderSearchPath.js index bd1b5f5c5..323c4e439 100644 --- a/packages/local-cli/link/ios/getHeaderSearchPath.js +++ b/packages/local-cli/link/ios/getHeaderSearchPath.js @@ -8,8 +8,7 @@ */ const path = require('path'); -const union = require('lodash').union; -const last = require('lodash').last; +const { last, union } = require('lodash'); /** * Given an array of directories, it returns the one that contains @@ -57,6 +56,6 @@ module.exports = function getHeaderSearchPath(sourceDir, headers) { ? `"$(SRCROOT)${path.sep}${path.relative(sourceDir, directories[0])}"` : `"$(SRCROOT)${path.sep}${path.relative( sourceDir, - getOuterDirectory(directories), + getOuterDirectory(directories) )}/**"`; }; diff --git a/packages/local-cli/link/ios/getPlist.js b/packages/local-cli/link/ios/getPlist.js index 61d0b5125..ee51c549b 100644 --- a/packages/local-cli/link/ios/getPlist.js +++ b/packages/local-cli/link/ios/getPlist.js @@ -8,8 +8,8 @@ */ const plistParser = require('plist'); -const getPlistPath = require('./getPlistPath'); const fs = require('fs'); +const getPlistPath = require('./getPlistPath'); /** * Returns Info.plist located in the iOS project diff --git a/packages/local-cli/link/ios/getPlistPath.js b/packages/local-cli/link/ios/getPlistPath.js index f8d570b9f..4fdbd0305 100644 --- a/packages/local-cli/link/ios/getPlistPath.js +++ b/packages/local-cli/link/ios/getPlistPath.js @@ -19,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/packages/local-cli/link/ios/getTargets.js b/packages/local-cli/link/ios/getTargets.js index 15f958598..17cdf9888 100644 --- a/packages/local-cli/link/ios/getTargets.js +++ b/packages/local-cli/link/ios/getTargets.js @@ -11,17 +11,19 @@ * Given xcodeproj it returns list of targets */ module.exports = function getTargets(project) { - let targets = project.getFirstProject().firstProject.targets; - let nativeTargetSection = project.pbxNativeTargetSection(); - return targets.map(function(target) { - let key = target.value; - let configurationListId = project.pbxNativeTargetSection()[key] + const { + firstProject: { targets }, + } = project.getFirstProject(); + const nativeTargetSection = project.pbxNativeTargetSection(); + return targets.map(target => { + const key = target.value; + const configurationListId = project.pbxNativeTargetSection()[key] .buildConfigurationList; - let configurationList = project.pbxXCConfigurationList()[ + const configurationList = project.pbxXCConfigurationList()[ configurationListId ]; - let buildConfigurationId = configurationList.buildConfigurations[0].value; - let buildConfiguration = project.pbxXCBuildConfigurationSection()[ + const buildConfigurationId = configurationList.buildConfigurations[0].value; + const buildConfiguration = project.pbxXCBuildConfigurationSection()[ buildConfigurationId ]; return { diff --git a/packages/local-cli/link/ios/index.js b/packages/local-cli/link/ios/index.js index aa31fd2ba..bff921b4b 100644 --- a/packages/local-cli/link/ios/index.js +++ b/packages/local-cli/link/ios/index.js @@ -7,7 +7,7 @@ * @format */ -module.exports = function() { +module.exports = function getIOSLinkConfig() { return { isInstalled: require('./common/isInstalled'), register: require('./common/registerNativeModule'), diff --git a/packages/local-cli/link/ios/mapHeaderSearchPaths.js b/packages/local-cli/link/ios/mapHeaderSearchPaths.js index 2754602d4..605241cce 100644 --- a/packages/local-cli/link/ios/mapHeaderSearchPaths.js +++ b/packages/local-cli/link/ios/mapHeaderSearchPaths.js @@ -30,7 +30,7 @@ module.exports = function headerSearchPathIter(project, func) { Object.keys(config) .filter(ref => ref.indexOf('_comment') === -1) .forEach(ref => { - const buildSettings = config[ref].buildSettings; + const { buildSettings } = config[ref]; const shouldVisitBuildSettings = (Array.isArray(buildSettings.OTHER_LDFLAGS) ? buildSettings.OTHER_LDFLAGS diff --git a/packages/local-cli/link/ios/registerNativeModule.js b/packages/local-cli/link/ios/registerNativeModule.js index b68230ce3..cd2ba13ea 100644 --- a/packages/local-cli/link/ios/registerNativeModule.js +++ b/packages/local-cli/link/ios/registerNativeModule.js @@ -10,6 +10,7 @@ const xcode = require('xcode'); const fs = require('fs'); const path = require('path'); +const { isEmpty } = require('lodash'); const addToHeaderSearchPaths = require('./addToHeaderSearchPaths'); const getHeadersInFolder = require('./getHeadersInFolder'); @@ -19,7 +20,6 @@ const createGroupWithMessage = require('./createGroupWithMessage'); const addFileToProject = require('./addFileToProject'); const addProjectToLibraries = require('./addProjectToLibraries'); const addSharedLibraries = require('./addSharedLibraries'); -const isEmpty = require('lodash').isEmpty; /** * Register native module IOS adds given dependency to project by adding @@ -30,7 +30,7 @@ const isEmpty = require('lodash').isEmpty; */ module.exports = function registerNativeModuleIOS( dependencyConfig, - projectConfig, + projectConfig ) { const project = xcode.project(projectConfig.pbxprojPath).parseSync(); const dependencyProject = xcode @@ -39,11 +39,11 @@ module.exports = function registerNativeModuleIOS( const libraries = createGroupWithMessage( project, - projectConfig.libraryFolder, + projectConfig.libraryFolder ); const file = addFileToProject( project, - path.relative(projectConfig.sourceDir, dependencyConfig.projectPath), + path.relative(projectConfig.sourceDir, dependencyConfig.projectPath) ); const targets = getTargets(project); @@ -51,7 +51,7 @@ module.exports = function registerNativeModuleIOS( addProjectToLibraries(libraries, file); getTargets(dependencyProject).forEach(product => { - var i; + let i; if (!product.isTVOS) { for (i = 0; i < targets.length; i++) { if (!targets[i].isTVOS) { @@ -79,7 +79,7 @@ module.exports = function registerNativeModuleIOS( if (!isEmpty(headers)) { addToHeaderSearchPaths( project, - getHeaderSearchPath(projectConfig.sourceDir, headers), + getHeaderSearchPath(projectConfig.sourceDir, headers) ); } diff --git a/packages/local-cli/link/ios/removeFromHeaderSearchPaths.js b/packages/local-cli/link/ios/removeFromHeaderSearchPaths.js index e7fc30fa1..10c6b3cfd 100644 --- a/packages/local-cli/link/ios/removeFromHeaderSearchPaths.js +++ b/packages/local-cli/link/ios/removeFromHeaderSearchPaths.js @@ -14,6 +14,6 @@ const mapHeaderSearchPaths = require('./mapHeaderSearchPaths'); */ module.exports = function addToHeaderSearchPaths(project, path) { mapHeaderSearchPaths(project, searchPaths => - searchPaths.filter(searchPath => searchPath !== path), + searchPaths.filter(searchPath => searchPath !== path) ); }; diff --git a/packages/local-cli/link/ios/removeFromPbxItemContainerProxySection.js b/packages/local-cli/link/ios/removeFromPbxItemContainerProxySection.js index b2277ce88..4cdc8a0c4 100644 --- a/packages/local-cli/link/ios/removeFromPbxItemContainerProxySection.js +++ b/packages/local-cli/link/ios/removeFromPbxItemContainerProxySection.js @@ -14,15 +14,13 @@ */ module.exports = function removeFromPbxItemContainerProxySection( project, - file, + file ) { const section = project.hash.project.objects.PBXContainerItemProxy; - for (var key of Object.keys(section)) { + for (const key of Object.keys(section)) { if (section[key].containerPortal === file.uuid) { delete section[key]; } } - - return; }; diff --git a/packages/local-cli/link/ios/removeFromPbxReferenceProxySection.js b/packages/local-cli/link/ios/removeFromPbxReferenceProxySection.js index 52f8056a5..e565e37a0 100644 --- a/packages/local-cli/link/ios/removeFromPbxReferenceProxySection.js +++ b/packages/local-cli/link/ios/removeFromPbxReferenceProxySection.js @@ -14,11 +14,9 @@ module.exports = function removeFromPbxReferenceProxySection(project, file) { const section = project.hash.project.objects.PBXReferenceProxy; - for (var key of Object.keys(section)) { + for (const key of Object.keys(section)) { if (section[key].path === file.basename) { delete section[key]; } } - - return; }; diff --git a/packages/local-cli/link/ios/removeFromProjectReferences.js b/packages/local-cli/link/ios/removeFromProjectReferences.js index 8a776bf72..2e532b5d0 100644 --- a/packages/local-cli/link/ios/removeFromProjectReferences.js +++ b/packages/local-cli/link/ios/removeFromProjectReferences.js @@ -18,10 +18,10 @@ * Otherwise returns null */ module.exports = function removeFromProjectReferences(project, file) { - const firstProject = project.getFirstProject().firstProject; + const { firstProject } = project.getFirstProject(); const projectRef = firstProject.projectReferences.find( - item => item.ProjectRef === file.uuid, + item => item.ProjectRef === file.uuid ); if (!projectRef) { @@ -30,7 +30,7 @@ module.exports = function removeFromProjectReferences(project, file) { firstProject.projectReferences.splice( firstProject.projectReferences.indexOf(projectRef), - 1, + 1 ); return projectRef; diff --git a/packages/local-cli/link/ios/removeProductGroup.js b/packages/local-cli/link/ios/removeProductGroup.js index f012ff25c..b491415e7 100644 --- a/packages/local-cli/link/ios/removeProductGroup.js +++ b/packages/local-cli/link/ios/removeProductGroup.js @@ -10,11 +10,9 @@ module.exports = function removeProductGroup(project, productGroupId) { const section = project.hash.project.objects.PBXGroup; - for (var key of Object.keys(section)) { + for (const key of Object.keys(section)) { if (key === productGroupId) { delete section[key]; } } - - return; }; diff --git a/packages/local-cli/link/ios/removeProjectFromLibraries.js b/packages/local-cli/link/ios/removeProjectFromLibraries.js index 0402d777a..e049584e5 100644 --- a/packages/local-cli/link/ios/removeProjectFromLibraries.js +++ b/packages/local-cli/link/ios/removeProjectFromLibraries.js @@ -3,8 +3,6 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - * - * @format */ /** @@ -15,7 +13,8 @@ * It's mainly due to limitations of `xcode` library. */ module.exports = function removeProjectFromLibraries(libraries, file) { + // eslint-disable-next-line no-param-reassign libraries.children = libraries.children.filter( - library => library.comment !== file.basename, + library => library.comment !== file.basename ); }; diff --git a/packages/local-cli/link/ios/removeSharedLibraries.js b/packages/local-cli/link/ios/removeSharedLibraries.js index 1a34b7c1a..825aa632f 100644 --- a/packages/local-cli/link/ios/removeSharedLibraries.js +++ b/packages/local-cli/link/ios/removeSharedLibraries.js @@ -14,7 +14,7 @@ module.exports = function removeSharedLibraries(project, libraries) { const target = project.getFirstTarget().uuid; - for (var name of libraries) { - project.removeFramework(name, {target}); + for (const name of libraries) { + project.removeFramework(name, { target }); } }; diff --git a/packages/local-cli/link/ios/unlinkAssets.js b/packages/local-cli/link/ios/unlinkAssets.js index 1df299fdd..55dbbe875 100644 --- a/packages/local-cli/link/ios/unlinkAssets.js +++ b/packages/local-cli/link/ios/unlinkAssets.js @@ -4,17 +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 */ const fs = require('fs-extra'); const path = require('path'); const xcode = require('xcode'); const log = require('npmlog'); +const { difference } = require('lodash'); + const groupFilesByType = require('../groupFilesByType'); const getPlist = require('./getPlist'); const writePlist = require('./writePlist'); -const difference = require('lodash').difference; /** * Unlinks assets from iOS project. Removes references for fonts from `Info.plist` @@ -26,33 +27,34 @@ module.exports = function unlinkAssetsIOS(files, projectConfig) { const plist = getPlist(project, projectConfig.sourceDir); if (!plist) { - return log.error( + 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" ); + return; } if (!project.pbxGroupByName('Resources')) { - return log.error( + 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." ); + return; } - const removeResourceFile = function(f) { + const removeResourceFiles = (f: string[] = []) => (f || []) .map(asset => project.removeResourceFile( path.relative(projectConfig.sourceDir, asset), - {target: project.getFirstTarget().uuid}, - ), + { target: project.getFirstTarget().uuid } + ) ) .map(file => file.basename); - }; - removeResourceFile(assets.image); + removeResourceFiles(assets.image); - const fonts = removeResourceFile(assets.font); + const fonts = removeResourceFiles(assets.font); plist.UIAppFonts = difference(plist.UIAppFonts || [], fonts); diff --git a/packages/local-cli/link/ios/unregisterNativeModule.js b/packages/local-cli/link/ios/unregisterNativeModule.js index c9b83a880..71b1f2ced 100644 --- a/packages/local-cli/link/ios/unregisterNativeModule.js +++ b/packages/local-cli/link/ios/unregisterNativeModule.js @@ -10,8 +10,7 @@ const xcode = require('xcode'); const path = require('path'); const fs = require('fs'); -const difference = require('lodash').difference; -const isEmpty = require('lodash').isEmpty; +const { difference, isEmpty } = require('lodash'); const getGroup = require('./getGroup'); const getTargets = require('./getTargets'); @@ -31,7 +30,7 @@ const removeSharedLibraries = require('./removeSharedLibraries'); module.exports = function unregisterNativeModule( dependencyConfig, projectConfig, - iOSDependencies, + iOSDependencies ) { const project = xcode.project(projectConfig.pbxprojPath).parseSync(); const dependencyProject = xcode @@ -42,7 +41,7 @@ module.exports = function unregisterNativeModule( const file = removeProjectFromProject( project, - path.relative(projectConfig.sourceDir, dependencyConfig.projectPath), + path.relative(projectConfig.sourceDir, dependencyConfig.projectPath) ); removeProjectFromLibraries(libraries, file); @@ -57,8 +56,8 @@ module.exports = function unregisterNativeModule( dependencyConfig.sharedLibraries, iOSDependencies.reduce( (libs, dependency) => libs.concat(dependency.sharedLibraries), - projectConfig.sharedLibraries, - ), + projectConfig.sharedLibraries + ) ); removeSharedLibraries(project, sharedLibraries); @@ -67,7 +66,7 @@ module.exports = function unregisterNativeModule( if (!isEmpty(headers)) { removeFromHeaderSearchPaths( project, - getHeaderSearchPath(projectConfig.sourceDir, headers), + getHeaderSearchPath(projectConfig.sourceDir, headers) ); } diff --git a/packages/local-cli/link/ios/writePlist.js b/packages/local-cli/link/ios/writePlist.js index 009de34e2..a0477bd48 100644 --- a/packages/local-cli/link/ios/writePlist.js +++ b/packages/local-cli/link/ios/writePlist.js @@ -8,8 +8,8 @@ */ const plistParser = require('plist'); -const getPlistPath = require('./getPlistPath'); const fs = require('fs'); +const getPlistPath = require('./getPlistPath'); /** * Writes to Info.plist located in the iOS project @@ -28,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/packages/local-cli/link/link.js b/packages/local-cli/link/link.js index 4e9aaf6ed..501bacb1b 100644 --- a/packages/local-cli/link/link.js +++ b/packages/local-cli/link/link.js @@ -8,12 +8,12 @@ * @flow */ +import type { ContextT } from '../core/types.flow'; + const log = require('npmlog'); const path = require('path'); -const uniqBy = require('lodash').uniqBy; -const flatten = require('lodash').flatten; +const { flatten, isEmpty, uniqBy } = require('lodash'); const chalk = require('chalk'); -const isEmpty = require('lodash').isEmpty; const promiseWaterfall = require('./promiseWaterfall'); const getProjectDependencies = require('./getProjectDependencies'); const getDependencyConfig = require('./getDependencyConfig'); @@ -24,13 +24,9 @@ const getProjectConfig = require('./getProjectConfig'); const findReactNativeScripts = require('../util/findReactNativeScripts'); -const getHooks = require('../core/getHooks'); -const getParams = require('../core/getParams'); const getAssets = require('../core/getAssets'); const getPlatforms = require('../core/getPlatforms'); -import type {ContextT} from '../core/types.flow'; - log.heading = 'rnpm-link'; const dedupeAssets = assets => uniqBy(assets, asset => path.basename(asset)); @@ -40,7 +36,7 @@ const linkDependency = async (platforms, project, dependency) => { Object.keys(platforms || {}).forEach(platform => { if (!project[platform] || !dependency.config[platform]) { - return null; + return; } const linkConfig = @@ -48,22 +44,22 @@ const linkDependency = async (platforms, project, dependency) => { platforms[platform].linkConfig && platforms[platform].linkConfig(); if (!linkConfig || !linkConfig.isInstalled || !linkConfig.register) { - return null; + return; } const isInstalled = linkConfig.isInstalled( project[platform], dependency.name, - dependency.config[platform], + dependency.config[platform] ); if (isInstalled) { log.info( chalk.grey( - `Platform '${platform}' module ${dependency.name} is already linked`, - ), + `Platform '${platform}' module ${dependency.name} is already linked` + ) ); - return null; + return; } log.info(`Linking ${dependency.name} ${platform} dependency`); @@ -74,13 +70,13 @@ const linkDependency = async (platforms, project, dependency) => { dependency.config[platform], params, // $FlowFixMe: We check if project[platform] exists on line 42 - project[platform], + project[platform] ); log.info( `Platform '${platform}' module ${ dependency.name - } has been successfully linked`, + } has been successfully linked` ); }); }; @@ -95,11 +91,11 @@ const linkAssets = (platforms, project, assets) => { platforms[platform] && platforms[platform].linkConfig && platforms[platform].linkConfig(); - + if (!linkConfig || !linkConfig.copyAssets || !project[platform]) { return; } - + log.info(`Linking assets to ${platform} project`); // $FlowFixMe: We check for existence of project[platform] on line 97. linkConfig.copyAssets(assets, project[platform]); @@ -123,13 +119,13 @@ function link(args: Array, ctx: ContextT) { } 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, + false ); if (!hasProjectConfig && findReactNativeScripts()) { throw new Error( @@ -137,7 +133,7 @@ function link(args: Array, ctx: ContextT) { '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.', + 'for more information.' ); } @@ -154,14 +150,14 @@ function link(args: Array, ctx: ContextT) { const dependencies = getDependencyConfig( ctx, platforms, - packageName ? [packageName] : getProjectDependencies(ctx.root), + packageName ? [packageName] : getProjectDependencies(ctx.root) ); const assets = dedupeAssets( dependencies.reduce( (acc, dependency) => acc.concat(dependency.assets), - getAssets(ctx.root), - ), + getAssets(ctx.root) + ) ); const tasks = flatten( @@ -169,7 +165,7 @@ function link(args: Array, ctx: ContextT) { () => promisify(dependency.commands.prelink || commandStub), () => linkDependency(platforms, project, dependency), () => promisify(dependency.commands.postlink || commandStub), - ]), + ]) ); tasks.push(() => linkAssets(platforms, project, assets)); @@ -177,7 +173,7 @@ function link(args: Array, ctx: ContextT) { 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/packages/local-cli/link/pods/addPodEntry.js b/packages/local-cli/link/pods/addPodEntry.js index e89716eb6..b535d3477 100644 --- a/packages/local-cli/link/pods/addPodEntry.js +++ b/packages/local-cli/link/pods/addPodEntry.js @@ -7,24 +7,24 @@ * @format */ -'use strict'; - module.exports = function addPodEntry( podLines, linesToAddEntry, podName, - nodePath, + 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)), + } + + if (Array.isArray(linesToAddEntry)) { + 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/packages/local-cli/link/pods/findLineToAddPod.js b/packages/local-cli/link/pods/findLineToAddPod.js index d6902838e..2a38e0464 100644 --- a/packages/local-cli/link/pods/findLineToAddPod.js +++ b/packages/local-cli/link/pods/findLineToAddPod.js @@ -7,11 +7,9 @@ * @format */ -'use strict'; - module.exports = function findLineToAddPod(podLines, firstTargetLine) { // match line with new target: target 'project_name' do (most likely target inside podfile main target) - const nextTarget = /target (\'|\")\w+(\'|\") do/g; + const nextTarget = /target ('|")\w+('|") do/g; // match line that has only 'end' (if we don't catch new target or function, this would mean this is end of current target) const endOfCurrentTarget = /^\s*end\s*$/g; // match function definition, like: post_install do |installer| (some Podfiles have function defined inside main target diff --git a/packages/local-cli/link/pods/findMarkedLinesInPodfile.js b/packages/local-cli/link/pods/findMarkedLinesInPodfile.js index 5df1c33ac..43710ab27 100644 --- a/packages/local-cli/link/pods/findMarkedLinesInPodfile.js +++ b/packages/local-cli/link/pods/findMarkedLinesInPodfile.js @@ -7,14 +7,13 @@ * @format */ -'use strict'; const MARKER_TEXT = '# Add new pods below this line'; 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/packages/local-cli/link/pods/findPodTargetLine.js b/packages/local-cli/link/pods/findPodTargetLine.js index 22070f8dd..5d34ae804 100644 --- a/packages/local-cli/link/pods/findPodTargetLine.js +++ b/packages/local-cli/link/pods/findPodTargetLine.js @@ -7,15 +7,10 @@ * @format */ -'use strict'; - 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', - ); + // match first target definition in file: target 'target_name' do + 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/packages/local-cli/link/pods/isInstalled.js b/packages/local-cli/link/pods/isInstalled.js index d7602d14d..35e484c70 100644 --- a/packages/local-cli/link/pods/isInstalled.js +++ b/packages/local-cli/link/pods/isInstalled.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const readPodfile = require('./readPodfile'); module.exports = function isInstalled(iOSProject, dependencyConfig) { @@ -17,8 +15,8 @@ module.exports = function isInstalled(iOSProject, dependencyConfig) { } // match line with pod declaration: pod 'dependencyPodName' (other possible parameters of pod are ignored) const dependencyRegExp = new RegExp( - 'pod\\s+(\'|")' + dependencyConfig.podspec + '(\'|")', - 'g', + `pod\\s+('|")${dependencyConfig.podspec}('|")`, + 'g' ); const podLines = readPodfile(iOSProject.podfile); for (let i = 0, len = podLines.length; i < len; i++) { diff --git a/packages/local-cli/link/pods/readPodfile.js b/packages/local-cli/link/pods/readPodfile.js index 281a0a0e4..0e86affa2 100644 --- a/packages/local-cli/link/pods/readPodfile.js +++ b/packages/local-cli/link/pods/readPodfile.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); module.exports = function readPodfile(podfilePath) { diff --git a/packages/local-cli/link/pods/registerNativeModule.js b/packages/local-cli/link/pods/registerNativeModule.js index f8e757b27..b8d96517e 100644 --- a/packages/local-cli/link/pods/registerNativeModule.js +++ b/packages/local-cli/link/pods/registerNativeModule.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const readPodfile = require('./readPodfile'); const findPodTargetLine = require('./findPodTargetLine'); const findLineToAddPod = require('./findLineToAddPod'); @@ -19,7 +17,7 @@ const savePodFile = require('./savePodFile'); module.exports = function registerNativeModulePods( name, dependencyConfig, - iOSProject, + iOSProject ) { const podLines = readPodfile(iOSProject.podfile); const linesToAddEntry = getLinesToAddEntry(podLines, iOSProject); @@ -27,12 +25,11 @@ module.exports = function registerNativeModulePods( savePodFile(iOSProject.podfile, podLines); }; -function getLinesToAddEntry(podLines, {projectName}) { +function getLinesToAddEntry(podLines, { projectName }) { const linesToAddPodWithMarker = findMarkedLinesInPodfile(podLines); if (linesToAddPodWithMarker.length > 0) { return linesToAddPodWithMarker; - } else { - const firstTargetLined = findPodTargetLine(podLines, projectName); - return findLineToAddPod(podLines, firstTargetLined); } + const firstTargetLined = findPodTargetLine(podLines, projectName); + return findLineToAddPod(podLines, firstTargetLined); } diff --git a/packages/local-cli/link/pods/removePodEntry.js b/packages/local-cli/link/pods/removePodEntry.js index 02ef4746f..006394320 100644 --- a/packages/local-cli/link/pods/removePodEntry.js +++ b/packages/local-cli/link/pods/removePodEntry.js @@ -7,15 +7,11 @@ * @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', + `\\n( |\\t)*pod\\s+("|')${podName}("|')(,\\s*(:[a-z]+\\s*=>)?\\s*(("|').*?("|')|\\[[\\s\\S]*?\\]))*\\n`, + 'g' ); return podfileContent.replace(podRegex, '\n'); }; diff --git a/packages/local-cli/link/pods/savePodFile.js b/packages/local-cli/link/pods/savePodFile.js index 640bb646f..adb3baf53 100644 --- a/packages/local-cli/link/pods/savePodFile.js +++ b/packages/local-cli/link/pods/savePodFile.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); module.exports = function savePodFile(podfilePath, podLines) { diff --git a/packages/local-cli/link/pods/unregisterNativeModule.js b/packages/local-cli/link/pods/unregisterNativeModule.js index 048e3e8de..235dd11c7 100644 --- a/packages/local-cli/link/pods/unregisterNativeModule.js +++ b/packages/local-cli/link/pods/unregisterNativeModule.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const removePodEntry = require('./removePodEntry'); diff --git a/packages/local-cli/link/pollParams.js b/packages/local-cli/link/pollParams.js index 6cf23020d..039160c33 100644 --- a/packages/local-cli/link/pollParams.js +++ b/packages/local-cli/link/pollParams.js @@ -7,12 +7,13 @@ * @format */ -var inquirer = require('inquirer'); +const inquirer = require('inquirer'); module.exports = questions => new Promise((resolve, reject) => { if (!questions) { - return resolve({}); + resolve({}); + return; } inquirer.prompt(questions).then(resolve, reject); diff --git a/packages/local-cli/link/promiseWaterfall.js b/packages/local-cli/link/promiseWaterfall.js index 0a2ddac88..b0f77e3b2 100644 --- a/packages/local-cli/link/promiseWaterfall.js +++ b/packages/local-cli/link/promiseWaterfall.js @@ -18,6 +18,6 @@ module.exports = function promiseWaterfall(tasks) { return tasks.reduce( (prevTaskPromise, task) => prevTaskPromise.then(task), - Promise.resolve(), + Promise.resolve() ); }; diff --git a/packages/local-cli/link/promisify.js b/packages/local-cli/link/promisify.js index 2605bf95e..3afb6870a 100644 --- a/packages/local-cli/link/promisify.js +++ b/packages/local-cli/link/promisify.js @@ -9,5 +9,5 @@ module.exports = func => new Promise((resolve, reject) => - func((err, res) => (err ? reject(err) : resolve(res))), + func((err, res) => (err ? reject(err) : resolve(res))) ); diff --git a/packages/local-cli/link/unlink.js b/packages/local-cli/link/unlink.js index fd8199fb4..b3cb03270 100644 --- a/packages/local-cli/link/unlink.js +++ b/packages/local-cli/link/unlink.js @@ -7,24 +7,20 @@ * @flow */ +import type { ContextT } from '../core/types.flow'; + const log = require('npmlog'); -const getProjectDependencies = require('./getProjectDependencies'); -const getDependencyConfig = require('./getDependencyConfig'); +const { flatten, isEmpty, difference } = require('lodash'); const getProjectConfig = require('./getProjectConfig'); - -const difference = require('lodash').difference; -const filter = require('lodash').filter; -const flatten = require('lodash').flatten; -const isEmpty = require('lodash').isEmpty; +const getDependencyConfig = require('./getDependencyConfig'); +const getProjectDependencies = require('./getProjectDependencies'); const promiseWaterfall = require('./promiseWaterfall'); const commandStub = require('./commandStub'); const promisify = require('./promisify'); const getPlatforms = require('../core/getPlatforms'); -import type { ContextT } from '../core/types.flow'; - log.heading = 'rnpm-link'; const unlinkDependency = ( @@ -32,7 +28,7 @@ const unlinkDependency = ( project, dependency, packageName, - otherDependencies, + otherDependencies ) => { Object.keys(platforms || {}).forEach(platform => { if (!project[platform] || !dependency.config[platform]) { @@ -50,7 +46,7 @@ const unlinkDependency = ( const isInstalled = linkConfig.isInstalled( project[platform], packageName, - dependency.config[platform], + dependency.config[platform] ); if (!isInstalled) { @@ -66,13 +62,13 @@ const unlinkDependency = ( dependency.config[platform], // $FlowFixMe: We check for existence on line 38 project[platform], - otherDependencies, + otherDependencies ); log.info( `Platform '${platform}' module ${ dependency.name - } has been successfully unlinked`, + } has been successfully unlinked` ); }); }; @@ -93,12 +89,16 @@ function unlink(args: Array, ctx: ContextT) { } 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); } - const allDependencies = getDependencyConfig(ctx, platforms, getProjectDependencies()); + const allDependencies = getDependencyConfig( + ctx, + platforms, + getProjectDependencies() + ); let otherDependencies; let dependency; @@ -110,7 +110,7 @@ function unlink(args: Array, ctx: ContextT) { } otherDependencies = [...allDependencies]; - dependency = otherDependencies.splice(idx, 1)[0]; + dependency = otherDependencies.splice(idx, 1)[0]; // eslint-disable-line prefer-destructuring } catch (err) { log.warn('ERRINVALIDPROJ', err.message); return Promise.reject(err); @@ -126,7 +126,7 @@ function unlink(args: Array, ctx: ContextT) { project, dependency, packageName, - otherDependencies, + otherDependencies ), () => promisify(dependency.commands.postunlink || commandStub), ]; @@ -137,11 +137,11 @@ function unlink(args: Array, ctx: ContextT) { // link const assets = difference( dependency.assets, - flatten(allDependencies, d => d.assets), + flatten(allDependencies, d => d.assets) ); if (isEmpty(assets)) { - return Promise.resolve(); + return; } Object.keys(platforms || {}).forEach(platform => { @@ -159,12 +159,12 @@ function unlink(args: Array, ctx: ContextT) { }); 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/packages/local-cli/logAndroid/logAndroid.js b/packages/local-cli/logAndroid/logAndroid.js index 322bc8eae..fc57e4e5e 100644 --- a/packages/local-cli/logAndroid/logAndroid.js +++ b/packages/local-cli/logAndroid/logAndroid.js @@ -3,46 +3,29 @@ * * 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'); -const child_process = require('child_process'); +const { spawnSync } = require('child_process'); /** * Starts adb logcat */ -function logAndroid() { - return new Promise((resolve, reject) => { - _logAndroid(resolve, reject); - }); -} - -function _logAndroid() { - try { - const adbPath = process.env.ANDROID_HOME - ? process.env.ANDROID_HOME + '/platform-tools/adb' - : 'adb'; +async function logAndroid() { + const adbPath = process.env.ANDROID_HOME + ? `${process.env.ANDROID_HOME}/platform-tools/adb` + : 'adb'; - const adbArgs = ['logcat', '*:S', 'ReactNative:V', 'ReactNativeJS:V']; + 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'}); + const log = 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?'), - ); - return Promise.reject(); + if (log.error !== null) { + throw log.error; } } diff --git a/packages/local-cli/logIOS/logIOS.js b/packages/local-cli/logIOS/logIOS.js index 9d9aa68fa..641dbe157 100644 --- a/packages/local-cli/logIOS/logIOS.js +++ b/packages/local-cli/logIOS/logIOS.js @@ -7,59 +7,41 @@ * @format */ -'use strict'; - const chalk = require('chalk'); -const child_process = require('child_process'); +const { execFileSync, spawnSync } = require('child_process'); const os = require('os'); const path = require('path'); +function findAvailableDevice(devices) { + for (const key of Object.keys(devices)) { + for (const device of devices[key]) { + if (device.availability === '(available)' && device.state === 'Booted') { + return device; + } + } + } + return null; +} + /** * Starts iOS device syslog tail */ -function logIOS() { - return new Promise((resolve, reject) => { - _logIOS(resolve, reject); - }); -} - -function _logIOS() { - let rawDevices; - - try { - rawDevices = child_process.execFileSync( - 'xcrun', - ['simctl', 'list', 'devices', '--json'], - {encoding: 'utf8'}, - ); - } catch (e) { - console.log( - chalk.red( - 'xcrun invocation failed. Please check that Xcode is installed.', - ), - ); - return Promise.reject(e); - } +async function logIOS() { + const rawDevices = execFileSync( + 'xcrun', + ['simctl', 'list', 'devices', '--json'], + { encoding: 'utf8' } + ); - const {devices} = JSON.parse(rawDevices); + const { devices } = JSON.parse(rawDevices); - const device = _findAvailableDevice(devices); + const device = findAvailableDevice(devices); if (device === undefined) { console.log(chalk.red('No active iOS device found')); - return Promise.reject(); + return; } - return tailDeviceLogs(device.udid); -} - -function _findAvailableDevice(devices) { - for (const key of Object.keys(devices)) { - for (const device of devices[key]) { - if (device.availability === '(available)' && device.state === 'Booted') { - return device; - } - } - } + tailDeviceLogs(device.udid); } function tailDeviceLogs(udid) { @@ -69,18 +51,15 @@ function tailDeviceLogs(udid) { 'Logs', 'CoreSimulator', udid, - 'asl', + 'asl' ); - const log = child_process.spawnSync( - 'syslog', - ['-w', '-F', 'std', '-d', logDir], - {stdio: 'inherit'}, - ); + const log = spawnSync('syslog', ['-w', '-F', 'std', '-d', logDir], { + stdio: 'inherit', + }); if (log.error !== null) { - console.log(chalk.red('syslog invocation failed.')); - return Promise.reject(log.error); + throw log.error; } } diff --git a/packages/local-cli/package.json b/packages/local-cli/package.json index dba501f07..b4aa4e334 100644 --- a/packages/local-cli/package.json +++ b/packages/local-cli/package.json @@ -57,7 +57,6 @@ "node-notifier": "^5.2.1", "npmlog": "^2.0.4", "opn": "^3.0.2", - "optimist": "^0.6.1", "plist": "^3.0.0", "promise": "^7.1.1", "semver": "^5.0.3", @@ -68,6 +67,7 @@ "xmldoc": "^0.4.0" }, "devDependencies": { + "@babel/plugin-transform-strict-mode": "^7.2.0", "babel-core": "7.0.0-bridge.0", "babel-jest": "24.0.0-alpha.6", "eslint": "^5.7.0", diff --git a/packages/local-cli/runAndroid/adb.js b/packages/local-cli/runAndroid/adb.js index 7846a4724..27f03054d 100644 --- a/packages/local-cli/runAndroid/adb.js +++ b/packages/local-cli/runAndroid/adb.js @@ -8,7 +8,7 @@ * @flow strict */ -const child_process = require('child_process'); +const { execSync } = require('child_process'); /** * Parses the output of the 'adb devices' command @@ -22,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 !== ''); + const words = lines[i].split(/[ ,\t]+/).filter(w => w !== ''); if (words[1] === 'device') { devices.push(words[0]); @@ -36,7 +36,7 @@ function parseDevicesResult(result: string): Array { */ function getDevices(): Array { try { - const devicesResult = child_process.execSync('adb devices'); + const devicesResult = execSync('adb devices'); return parseDevicesResult(devicesResult.toString()); } catch (e) { return []; @@ -44,6 +44,6 @@ function getDevices(): Array { } module.exports = { - parseDevicesResult: parseDevicesResult, - getDevices: getDevices, + parseDevicesResult, + getDevices, }; diff --git a/packages/local-cli/runAndroid/runAndroid.js b/packages/local-cli/runAndroid/runAndroid.js index f94caa266..92faaa293 100644 --- a/packages/local-cli/runAndroid/runAndroid.js +++ b/packages/local-cli/runAndroid/runAndroid.js @@ -4,20 +4,20 @@ * 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'; +/* eslint-disable consistent-return */ -const adb = require('./adb'); const chalk = require('chalk'); -const child_process = require('child_process'); +const { spawnSync, spawn, execFileSync } = require('child_process'); const fs = require('fs'); -const isPackagerRunning = require('../util/isPackagerRunning'); -const findReactNativeScripts = require('../util/findReactNativeScripts'); const isString = require('lodash/isString'); const path = require('path'); const Promise = require('promise'); +const findReactNativeScripts = require('../util/findReactNativeScripts'); +const isPackagerRunning = require('../util/isPackagerRunning'); +const adb = require('./adb'); // Verifies this is an Android project function checkAndroid(root) { @@ -31,16 +31,16 @@ function runAndroid(argv, config, args) { if (!checkAndroid(args.root)) { const reactNativeScriptsPath = findReactNativeScripts(); if (reactNativeScriptsPath) { - child_process.spawnSync( + 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?', - ), + 'Android project not found. Maybe run react-native android first?' + ) ); } return; @@ -55,7 +55,7 @@ function runAndroid(argv, config, args) { console.log(chalk.bold('JS server already running.')); } else if (result === 'unrecognized') { console.warn( - chalk.yellow('JS server not recognized, continuing with build...'), + chalk.yellow('JS server not recognized, continuing with build...') ); } else { // result == 'not_running' @@ -68,7 +68,7 @@ function runAndroid(argv, config, args) { function getAdbPath() { return process.env.ANDROID_HOME - ? process.env.ANDROID_HOME + '/platform-tools/adb' + ? `${process.env.ANDROID_HOME}/platform-tools/adb` : 'adb'; } @@ -85,7 +85,7 @@ function tryRunAdbReverse(packagerPort, device) { console.log(chalk.bold(`Running ${adbPath} ${adbArgs.join(' ')}`)); - child_process.execFileSync(adbPath, adbArgs, { + execFileSync(adbPath, adbArgs, { stdio: [process.stdin, process.stdout, process.stderr], }); } catch (e) { @@ -96,8 +96,9 @@ function tryRunAdbReverse(packagerPort, device) { function getPackageNameWithSuffix(appId, appIdSuffix, packageName) { if (appId) { return appId; - } else if (appIdSuffix) { - return packageName + '.' + appIdSuffix; + } + if (appIdSuffix) { + return `${packageName}.${appIdSuffix}`; } return packageName; @@ -115,7 +116,7 @@ function buildAndRun(args) { const packageNameWithSuffix = getPackageNameWithSuffix( args.appId, args.appIdSuffix, - packageName, + packageName ); const adbPath = getAdbPath(); @@ -126,18 +127,17 @@ function buildAndRun(args) { cmd, packageNameWithSuffix, packageName, - adbPath, + adbPath ); - } else { - console.log(chalk.red('Argument missing for parameter --deviceId')); } + console.log(chalk.red('Argument missing for parameter --deviceId')); } else { return runOnAllDevices( args, cmd, packageNameWithSuffix, packageName, - adbPath, + adbPath ); } } @@ -147,9 +147,9 @@ function runOnSpecificDevice( gradlew, packageNameWithSuffix, packageName, - adbPath, + adbPath ) { - let devices = adb.getDevices(); + const devices = adb.getDevices(); if (devices && devices.length > 0) { if (devices.indexOf(args.deviceId) !== -1) { buildApk(gradlew); @@ -158,12 +158,10 @@ function runOnSpecificDevice( args.deviceId, packageNameWithSuffix, packageName, - adbPath, + 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); } @@ -177,12 +175,12 @@ function buildApk(gradlew) { console.log(chalk.bold('Building the app...')); // using '-x lint' in order to ignore linting errors while building the apk - child_process.execFileSync(gradlew, ['build', '-x', 'lint'], { + execFileSync(gradlew, ['build', '-x', 'lint'], { 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'), + chalk.red('Could not build the app, read the error above for details.\n') ); } } @@ -196,18 +194,18 @@ function tryInstallAppOnDevice(args, device) { const adbArgs = ['-s', device, 'install', pathToApk]; console.log( chalk.bold( - `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`, - ), + `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}` + ) ); - child_process.execFileSync(adbPath, adbArgs, { + 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', - ), + 'Could not install the app on the device, read the error above for details.\n' + ) ); } } @@ -217,7 +215,7 @@ function tryLaunchAppOnDevice( packageNameWithSuffix, packageName, adbPath, - mainActivity, + mainActivity ) { try { const adbArgs = [ @@ -227,17 +225,17 @@ function tryLaunchAppOnDevice( 'am', 'start', '-n', - packageNameWithSuffix + '/' + packageName + '.' + mainActivity, + `${packageNameWithSuffix}/${packageName}.${mainActivity}`, ]; console.log( chalk.bold( - `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`, - ), + `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...` + ) ); - child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'}); + spawnSync(adbPath, adbArgs, { stdio: 'inherit' }); } catch (e) { console.log( - chalk.red('adb invocation failed. Do you have adb in your PATH?'), + chalk.red('adb invocation failed. Do you have adb in your PATH?') ); } } @@ -247,7 +245,7 @@ function installAndLaunchOnDevice( selectedDevice, packageNameWithSuffix, packageName, - adbPath, + adbPath ) { tryRunAdbReverse(args.port, selectedDevice); tryInstallAppOnDevice(args, selectedDevice); @@ -256,7 +254,7 @@ function installAndLaunchOnDevice( packageNameWithSuffix, packageName, adbPath, - args.mainActivity, + args.mainActivity ); } @@ -265,20 +263,20 @@ function runOnAllDevices( cmd, packageNameWithSuffix, packageName, - adbPath, + adbPath ) { try { const gradleArgs = []; if (args.variant) { gradleArgs.push( - 'install' + args.variant[0].toUpperCase() + args.variant.slice(1), + `install${args.variant[0].toUpperCase()}${args.variant.slice(1)}` ); } else if (args.flavor) { console.warn( - chalk.yellow('--flavor has been deprecated. Use --variant instead'), + chalk.yellow('--flavor has been deprecated. Use --variant instead') ); gradleArgs.push( - 'install' + args.flavor[0].toUpperCase() + args.flavor.slice(1), + `install${args.flavor[0].toUpperCase()}${args.flavor.slice(1)}` ); } else { gradleArgs.push('installDebug'); @@ -291,12 +289,12 @@ function runOnAllDevices( console.log( chalk.bold( `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join( - ' ', - )})...`, - ), + ' ' + )})...` + ) ); - child_process.execFileSync(cmd, gradleArgs, { + execFileSync(cmd, gradleArgs, { stdio: [process.stdin, process.stdout, process.stderr], }); } catch (e) { @@ -305,8 +303,8 @@ function runOnAllDevices( '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', - ), + '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 @@ -322,7 +320,7 @@ function runOnAllDevices( packageNameWithSuffix, packageName, adbPath, - args.mainActivity, + args.mainActivity ); }); } else { @@ -334,17 +332,17 @@ function runOnAllDevices( 'am', 'start', '-n', - packageNameWithSuffix + '/' + packageName + '.MainActivity', + `${packageNameWithSuffix}/${packageName}.MainActivity`, ]; console.log( chalk.bold( - `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`, - ), + `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...` + ) ); - child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'}); + spawnSync(adbPath, fallbackAdbArgs, { stdio: 'inherit' }); } catch (e) { console.log( - chalk.red('adb invocation failed. Do you have adb in your PATH?'), + 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 @@ -368,7 +366,7 @@ function startServerInNewWindow(port, terminal = process.env.REACT_TERMINAL) { // set up the launchpackager.(command|bat) file const scriptsDir = path.resolve(__dirname, '..', '..', 'scripts'); const launchPackagerScript = path.resolve(scriptsDir, scriptFile); - const procConfig = {cwd: scriptsDir}; + const procConfig = { cwd: scriptsDir }; // set up the .packager.(env|bat) file to ensure the packager starts on the right port const packagerEnvFile = path.join( @@ -376,7 +374,7 @@ function startServerInNewWindow(port, terminal = process.env.REACT_TERMINAL) { '..', '..', 'scripts', - packagerEnvFilename, + packagerEnvFilename ); // ensure we overwrite file by passing the 'w' flag @@ -387,40 +385,31 @@ function startServerInNewWindow(port, terminal = process.env.REACT_TERMINAL) { if (process.platform === 'darwin') { if (terminal) { - return child_process.spawnSync( + return spawnSync( 'open', ['-a', terminal, launchPackagerScript], - procConfig, + procConfig ); } - return child_process.spawnSync('open', [launchPackagerScript], procConfig); - } else if (process.platform === 'linux') { + return spawnSync('open', [launchPackagerScript], procConfig); + } + if (process.platform === 'linux') { if (terminal) { procConfig.detached = true; - return child_process.spawn( - terminal, - ['-e', 'sh ' + launchPackagerScript], - procConfig, - ); + return spawn(terminal, ['-e', `sh ${launchPackagerScript}`], procConfig); } // By default, the child shell process will be attached to the parent procConfig.detached = false; - return child_process.spawn('sh', [launchPackagerScript], procConfig); - } else if (/^win/.test(process.platform)) { + return spawn('sh', [launchPackagerScript], procConfig); + } + if (/^win/.test(process.platform)) { procConfig.detached = true; procConfig.stdio = 'ignore'; - return child_process.spawn( - 'cmd.exe', - ['/C', launchPackagerScript], - procConfig, - ); - } else { - console.log( - chalk.red( - `Cannot start the packager. Unknown platform ${process.platform}`, - ), - ); + return spawn('cmd.exe', ['/C', launchPackagerScript], procConfig); } + console.log( + chalk.red(`Cannot start the packager. Unknown platform ${process.platform}`) + ); } module.exports = { diff --git a/packages/local-cli/runIOS/__tests__/findMatchingSimulator-test.js b/packages/local-cli/runIOS/__tests__/findMatchingSimulator-test.js index 8b9a19552..f868c3484 100644 --- a/packages/local-cli/runIOS/__tests__/findMatchingSimulator-test.js +++ b/packages/local-cli/runIOS/__tests__/findMatchingSimulator-test.js @@ -9,8 +9,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../findMatchingSimulator'); const findMatchingSimulator = require('../findMatchingSimulator'); @@ -55,8 +53,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6', - ), + 'iPhone 6' + ) ).toEqual({ udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', name: 'iPhone 6', @@ -107,8 +105,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6', - ), + 'iPhone 6' + ) ).toEqual({ udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', name: 'iPhone 6', @@ -156,14 +154,14 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6', - ), + 'iPhone 6' + ) ).toEqual(null); }); it('should return null if an odd input', () => { expect(findMatchingSimulator('random string input', 'iPhone 6')).toEqual( - null, + null ); }); @@ -206,8 +204,8 @@ describe('findMatchingSimulator', () => { ], }, }, - null, - ), + null + ) ).toEqual({ udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', name: 'iPhone 5', @@ -216,7 +214,7 @@ describe('findMatchingSimulator', () => { }); }); - it('should return the first simulator in list if none is defined', () => { + it('should return the first simulator with the correct version in list if none is defined', () => { expect( findMatchingSimulator( { @@ -281,8 +279,8 @@ describe('findMatchingSimulator', () => { ], }, }, - null, - ), + null + ) ).toEqual({ udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB', name: 'iPhone 5', @@ -330,8 +328,8 @@ describe('findMatchingSimulator', () => { ], }, }, - null, - ), + null + ) ).toEqual({ udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', name: 'iPhone 6s', @@ -379,8 +377,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6', - ), + 'iPhone 6' + ) ).toEqual({ udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C', name: 'iPhone 6', @@ -454,8 +452,8 @@ describe('findMatchingSimulator', () => { ], }, }, - null, - ), + null + ) ).toEqual({ udid: '3A409DC5-5188-42A6-8598-3AA6F34607A5', name: 'iPhone 7', @@ -529,8 +527,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6s', - ), + 'iPhone 6s' + ) ).toEqual({ udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508', name: 'iPhone 6s', @@ -604,8 +602,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6s (10.0)', - ), + 'iPhone 6s (10.0)' + ) ).toEqual({ udid: 'CBBB8FB8-77AB-49A9-8297-4CCFE3189C22', name: 'iPhone 6s', @@ -673,8 +671,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'iPhone 6s (10.0)', - ), + 'iPhone 6s (10.0)' + ) ).toEqual(null); }); @@ -705,8 +703,8 @@ describe('findMatchingSimulator', () => { ], }, }, - 'Apple TV', - ), + 'Apple TV' + ) ).toEqual({ udid: '816C30EA-38EA-41AC-BFDA-96FB632D522E', name: 'Apple TV', diff --git a/packages/local-cli/runIOS/__tests__/findXcodeProject-test.js b/packages/local-cli/runIOS/__tests__/findXcodeProject-test.js index 8071d728f..7cac685b7 100644 --- a/packages/local-cli/runIOS/__tests__/findXcodeProject-test.js +++ b/packages/local-cli/runIOS/__tests__/findXcodeProject-test.js @@ -8,8 +8,6 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../findXcodeProject'); const findXcodeProject = require('../findXcodeProject'); @@ -25,7 +23,7 @@ describe('findXcodeProject', () => { 'PodFile', 'Podfile.lock', 'Pods', - ]), + ]) ).toEqual({ name: 'AwesomeApp.xcodeproj', isWorkspace: false, @@ -43,7 +41,7 @@ describe('findXcodeProject', () => { 'PodFile', 'Podfile.lock', 'Pods', - ]), + ]) ).toEqual({ name: 'AwesomeApp.xcworkspace', isWorkspace: true, @@ -59,7 +57,7 @@ describe('findXcodeProject', () => { 'PodFile', 'Podfile.lock', 'Pods', - ]), + ]) ).toEqual(null); }); }); diff --git a/packages/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js b/packages/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js index 8914b5937..206fbbe4e 100644 --- a/packages/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js +++ b/packages/local-cli/runIOS/__tests__/parseIOSDevicesList-test.js @@ -8,14 +8,12 @@ * @emails oncall+javascript_foundation */ -'use strict'; - jest.dontMock('../parseIOSDevicesList'); -var parseIOSDevicesList = require('../parseIOSDevicesList'); +const parseIOSDevicesList = require('../parseIOSDevicesList'); describe('parseIOSDevicesList', () => { it('parses typical output', () => { - var devices = parseIOSDevicesList( + const devices = parseIOSDevicesList( [ 'Known Devices:', 'Maxs MacBook Pro [11111111-1111-1111-1111-111111111111]', @@ -28,7 +26,7 @@ describe('parseIOSDevicesList', () => { 'Blank', 'System Usage', 'Zombies', - ].join('\n'), + ].join('\n') ); expect(devices).toEqual([ @@ -42,7 +40,7 @@ describe('parseIOSDevicesList', () => { it('ignores garbage', () => { expect(parseIOSDevicesList('Something went terribly wrong (-42)')).toEqual( - [], + [] ); }); }); diff --git a/packages/local-cli/runIOS/findMatchingSimulator.js b/packages/local-cli/runIOS/findMatchingSimulator.js index 30e2156d4..2de9d1c99 100644 --- a/packages/local-cli/runIOS/findMatchingSimulator.js +++ b/packages/local-cli/runIOS/findMatchingSimulator.js @@ -7,7 +7,7 @@ * @format */ -'use strict'; +/* eslint-disable */ /** * Takes in a parsed simulator list and a desired name, and returns an object with the matching simulator. The desired @@ -38,8 +38,8 @@ function findMatchingSimulator(simulators, simulatorString) { simulatorName = simulatorString; } - var match; - for (let version in devices) { + let match; + for (const version in devices) { // Making sure the version of the simulator is an iOS or tvOS (Removes Apple Watch, etc) if (!version.startsWith('iOS') && !version.startsWith('tvOS')) { continue; @@ -47,8 +47,8 @@ function findMatchingSimulator(simulators, simulatorString) { if (simulatorVersion && !version.endsWith(simulatorVersion)) { continue; } - for (let i in devices[version]) { - let simulator = devices[version][i]; + for (const i in devices[version]) { + const simulator = devices[version][i]; // Skipping non-available simulator if ( simulator.availability !== '(available)' && @@ -56,7 +56,7 @@ function findMatchingSimulator(simulators, simulatorString) { ) { continue; } - let booted = simulator.state === 'Booted'; + const booted = simulator.state === 'Booted'; if (booted && simulatorName === null) { return { udid: simulator.udid, diff --git a/packages/local-cli/runIOS/findXcodeProject.js b/packages/local-cli/runIOS/findXcodeProject.js index 318f11ec8..5e94e7928 100644 --- a/packages/local-cli/runIOS/findXcodeProject.js +++ b/packages/local-cli/runIOS/findXcodeProject.js @@ -8,8 +8,6 @@ * @flow strict */ -'use strict'; - const path = require('path'); type ProjectInfo = { diff --git a/packages/local-cli/runIOS/parseIOSDevicesList.js b/packages/local-cli/runIOS/parseIOSDevicesList.js index 0209c796b..a7628f3c0 100644 --- a/packages/local-cli/runIOS/parseIOSDevicesList.js +++ b/packages/local-cli/runIOS/parseIOSDevicesList.js @@ -8,8 +8,6 @@ * @flow strict */ -'use strict'; - type IOSDeviceInfo = { name: string, udid: string, @@ -25,10 +23,10 @@ function parseIOSDevicesList(text: string): Array { const device = line.match(/(.*?) \((.*?)\) \[(.*?)\]/); const noSimulator = line.match(/(.*?) \((.*?)\) \[(.*?)\] \((.*?)\)/); if (device != null && noSimulator == null) { - var name = device[1]; - var version = device[2]; - var udid = device[3]; - devices.push({udid, name, version}); + const name = device[1]; + const version = device[2]; + const udid = device[3]; + devices.push({ udid, name, version }); } }); diff --git a/packages/local-cli/runIOS/runIOS.js b/packages/local-cli/runIOS/runIOS.js index a7ecf7d6d..de61b8930 100644 --- a/packages/local-cli/runIOS/runIOS.js +++ b/packages/local-cli/runIOS/runIOS.js @@ -7,7 +7,7 @@ * @format */ -'use strict'; +/* eslint-disable */ const child_process = require('child_process'); const fs = require('fs'); @@ -16,6 +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) { let device; @@ -47,14 +48,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); const xcodeProject = findXcodeProject(fs.readdirSync('.')); @@ -64,18 +64,18 @@ function runIOS(argv, config, args) { const inferredSchemeName = path.basename( xcodeProject.name, - path.extname(xcodeProject.name), + path.extname(xcodeProject.name) ); const scheme = args.scheme || inferredSchemeName; console.log( `Found Xcode ${xcodeProject.isWorkspace ? 'workspace' : 'project'} ${ xcodeProject.name - }`, + }` ); const devices = parseIOSDevicesList( child_process.execFileSync('xcrun', ['instruments', '-s'], { encoding: 'utf8', - }), + }) ); if (args.device) { const selectedDevice = matchingDevice(devices, args.device); @@ -87,18 +87,15 @@ function runIOS(argv, config, args) { args.configuration, args.packager, args.verbose, - args.port, + args.port ); + } + if (devices && devices.length > 0) { + console.log(`Could not find device with the name: "${args.device}".`); + console.log('Choose one of the following:'); + printFoundDevices(devices); } else { - if (devices && devices.length > 0) { - console.log( - 'Could not find device with the name: "' + args.device + '".', - ); - console.log('Choose one of the following:'); - printFoundDevices(devices); - } else { - console.log('No iOS devices connected.'); - } + console.log('No iOS devices connected.'); } } else if (args.udid) { return runOnDeviceByUdid(args, scheme, xcodeProject, devices); @@ -117,16 +114,15 @@ function runOnDeviceByUdid(args, scheme, xcodeProject, devices) { args.configuration, args.packager, args.verbose, - args.port, + args.port ); + } + if (devices && devices.length > 0) { + console.log(`Could not find device with the udid: "${args.udid}".`); + console.log('Choose one of the following:'); + printFoundDevices(devices); } else { - if (devices && devices.length > 0) { - console.log('Could not find device with the udid: "' + args.udid + '".'); - console.log('Choose one of the following:'); - printFoundDevices(devices); - } else { - console.log('No iOS devices connected.'); - } + console.log('No iOS devices connected.'); } } @@ -137,8 +133,8 @@ function runOnSimulator(xcodeProject, args, scheme) { child_process.execFileSync( 'xcrun', ['simctl', 'list', '--json', 'devices'], - {encoding: 'utf8'}, - ), + { encoding: 'utf8' } + ) ); } catch (e) { throw new Error('Could not parse the simulator list output'); @@ -161,7 +157,7 @@ function runOnSimulator(xcodeProject, args, scheme) { * this flag has no effect. */ const activeDeveloperDir = child_process - .execFileSync('xcode-select', ['-p'], {encoding: 'utf8'}) + .execFileSync('xcode-select', ['-p'], { encoding: 'utf8' }) .trim(); child_process.execFileSync('open', [ `${activeDeveloperDir}/Applications/Simulator.app`, @@ -192,13 +188,13 @@ function runOnSimulator(xcodeProject, args, scheme) { args.configuration, args.packager, args.verbose, - args.port, - ).then(appName => resolve({udid: selectedSimulator.udid, appName})); - }).then(({udid, appName}) => { + args.port + ).then(appName => resolve({ udid: selectedSimulator.udid, appName })); + }).then(({ udid, appName }) => { if (!appName) { appName = scheme; } - let appPath = getBuildPath(args.configuration, appName); + const appPath = getBuildPath(args.configuration, appName); console.log(`Installing ${appPath}`); child_process.spawnSync('xcrun', ['simctl', 'install', udid, appPath], { stdio: 'inherit', @@ -208,7 +204,7 @@ function runOnSimulator(xcodeProject, args, scheme) { .execFileSync( '/usr/libexec/PlistBuddy', ['-c', 'Print:CFBundleIdentifier', path.join(appPath, 'Info.plist')], - {encoding: 'utf8'}, + { encoding: 'utf8' } ) .trim(); @@ -226,7 +222,7 @@ function runOnDevice( configuration, launchPackager, verbose, - port, + port ) { return buildProject( xcodeProject, @@ -235,7 +231,7 @@ function runOnDevice( configuration, launchPackager, verbose, - port, + port ).then(appName => { if (!appName) { appName = scheme; @@ -248,12 +244,12 @@ function runOnDevice( '--justlaunch', ]; console.log( - `installing and launching your app on ${selectedDevice.name}...`, + `installing and launching your app on ${selectedDevice.name}...` ); const iosDeployOutput = child_process.spawnSync( 'ios-deploy', iosDeployInstallArgs, - {encoding: 'utf8'}, + { encoding: 'utf8' } ); if (iosDeployOutput.error) { console.log(''); @@ -273,10 +269,10 @@ function buildProject( configuration = 'Debug', launchPackager = false, verbose, - port, + port ) { return new Promise((resolve, reject) => { - var xcodebuildArgs = [ + const xcodebuildArgs = [ xcodeProject.isWorkspace ? '-workspace' : '-project', xcodeProject.name, '-configuration', @@ -300,10 +296,10 @@ function buildProject( const buildProcess = child_process.spawn( 'xcodebuild', xcodebuildArgs, - getProcessOptions(launchPackager, port), + getProcessOptions(launchPackager, port) ); let buildOutput = ''; - buildProcess.stdout.on('data', function(data) { + buildProcess.stdout.on('data', data => { buildOutput += data.toString(); if (xcpretty) { xcpretty.stdin.write(data); @@ -311,23 +307,23 @@ function buildProject( console.log(data.toString()); } }); - buildProcess.stderr.on('data', function(data) { + buildProcess.stderr.on('data', data => { console.error(data.toString()); }); - buildProcess.on('close', function(code) { + buildProcess.on('close', code => { if (xcpretty) { 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, + // 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" + const 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 resolve(productNameMatch[1]); // 0 is the full match, 1 is the app name } return buildProcess.error ? reject(buildProcess.error) : resolve(); }); @@ -339,7 +335,7 @@ function matchingDevice(devices, deviceName) { console.log( `Using first available device ${ devices[0].name - } due to lack of name supplied.`, + } due to lack of name supplied.` ); return devices[0]; } @@ -367,19 +363,19 @@ function formattedDeviceName(simulator) { function printFoundDevices(devices) { for (let i = devices.length - 1; i >= 0; i--) { - console.log(devices[i].name + ' Udid: ' + devices[i].udid); + console.log(`${devices[i].name} Udid: ${devices[i].udid}`); } } 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 }, }; } diff --git a/packages/local-cli/server/middleware/MiddlewareManager.js b/packages/local-cli/server/middleware/MiddlewareManager.js index 8d1ec3835..c1c529432 100644 --- a/packages/local-cli/server/middleware/MiddlewareManager.js +++ b/packages/local-cli/server/middleware/MiddlewareManager.js @@ -17,7 +17,7 @@ const WebSocketServer = require('ws').Server; const indexPageMiddleware = require('./indexPage'); const copyToClipBoardMiddleware = require('./copyToClipBoardMiddleware'); -const getSecurityHeadersMiddleware = require('./getSecurityHeadersMiddleware'); +const getSecurityHeadersMiddleware = require('./getSecurityHeadersMiddleware'); const loadRawBodyMiddleware = require('./loadRawBodyMiddleware'); const openStackFrameInEditorMiddleware = require('./openStackFrameInEditorMiddleware'); const statusPageMiddleware = require('./statusPageMiddleware'); @@ -27,7 +27,7 @@ const getDevToolsMiddleware = require('./getDevToolsMiddleware'); type Options = { +watchFolders: $ReadOnlyArray, +host?: string, -} +}; type WebSocketProxy = { server: WebSocketServer, @@ -38,6 +38,7 @@ type Connect = $Call; module.exports = class MiddlewareManager { app: Connect; + options: Options; constructor(options: Options) { @@ -67,7 +68,7 @@ module.exports = class MiddlewareManager { attachDevToolsSocket(socket: WebSocketProxy) { this.app.use( - getDevToolsMiddleware(this.options, () => socket.isChromeConnected()), + getDevToolsMiddleware(this.options, () => socket.isChromeConnected()) ); - }; + } }; diff --git a/packages/local-cli/server/middleware/copyToClipBoardMiddleware.js b/packages/local-cli/server/middleware/copyToClipBoardMiddleware.js index 69a3171f9..0d6803bb4 100644 --- a/packages/local-cli/server/middleware/copyToClipBoardMiddleware.js +++ b/packages/local-cli/server/middleware/copyToClipBoardMiddleware.js @@ -7,18 +7,16 @@ * @format */ -'use strict'; - +const chalk = require('chalk'); const copyToClipBoard = require('../util/copyToClipBoard'); -var chalk = require('chalk'); /** * Handle the request from JS to copy contents onto host system clipboard. * This is only supported on Mac for now. */ -module.exports = function(req, res, next) { +module.exports = function copyMiddleware(req, res, next) { if (req.url === '/copy-to-clipboard') { - var ret = copyToClipBoard(req.rawBody); + const ret = copyToClipBoard(req.rawBody); if (!ret) { console.warn(chalk.red('Copy button is not supported on this platform!')); } diff --git a/packages/local-cli/server/middleware/getDevToolsMiddleware.js b/packages/local-cli/server/middleware/getDevToolsMiddleware.js index 812872752..dffcec451 100644 --- a/packages/local-cli/server/middleware/getDevToolsMiddleware.js +++ b/packages/local-cli/server/middleware/getDevToolsMiddleware.js @@ -6,23 +6,14 @@ * * @format */ -'use strict'; - const launchChrome = require('../util/launchChrome'); -const {exec} = require('child_process'); - function launchChromeDevTools(host, port, args = '') { const debuggerURL = `http://${host}:${port}/debugger-ui${args}`; console.log('Launching Dev Tools...'); launchChrome(debuggerURL); } -function escapePath(pathname) { - // " Can escape paths with spaces in OS X, Windows, and *nix - return `"${pathname}"`; -} - function launchDevTools({ host, port, watchFolders }, isChromeConnected) { // Explicit config always wins const customDebugger = process.env.REACT_DEBUGGER; @@ -34,24 +25,13 @@ function launchDevTools({ host, port, watchFolders }, isChromeConnected) { } } -function customDebugger({ watchFolders, customDebugger }) { - const folders = watchFolders.map(escapePath).join(' '); - const command = `${customDebugger} ${folders}`; - console.log('Starting custom debugger by executing:', command); - exec(command, function(error, stdout, stderr) { - if (error !== null) { - console.log('Error while starting custom debugger:', error); - } - }); -} - -module.exports = function(options, isChromeConnected) { - return function(req, res, next) { +module.exports = function getDevToolsMiddleware(options, isChromeConnected) { + return function devToolsMiddleware(req, res, next) { if (req.url === '/launch-safari-devtools') { // TODO: remove `console.log` and dev tools binary console.log( 'We removed support for Safari dev-tools. ' + - 'If you still need this, please let us know.', + 'If you still need this, please let us know.' ); } else if (req.url === '/launch-chrome-devtools') { // TODO: Remove this case in the future @@ -59,7 +39,7 @@ module.exports = function(options, isChromeConnected) { 'The method /launch-chrome-devtools is deprecated. You are ' + ' probably using an application created with an older CLI with the ' + ' packager of a newer CLI. Please upgrade your application: ' + - 'https://facebook.github.io/react-native/docs/upgrading.html', + 'https://facebook.github.io/react-native/docs/upgrading.html' ); launchDevTools(options, isChromeConnected); res.end('OK'); diff --git a/packages/local-cli/server/middleware/getSecurityHeadersMiddleware.js b/packages/local-cli/server/middleware/getSecurityHeadersMiddleware.js index d3bad6bf9..a0942683c 100644 --- a/packages/local-cli/server/middleware/getSecurityHeadersMiddleware.js +++ b/packages/local-cli/server/middleware/getSecurityHeadersMiddleware.js @@ -8,7 +8,7 @@ * @format */ -module.exports = function(req, res, next) { +module.exports = function getSecurityHeadersMiddleware(req, res, next) { const address = req.client.server.address(); // Block any cross origin request. diff --git a/packages/local-cli/server/middleware/indexPage.js b/packages/local-cli/server/middleware/indexPage.js index ee6fc61ad..7407bc20a 100644 --- a/packages/local-cli/server/middleware/indexPage.js +++ b/packages/local-cli/server/middleware/indexPage.js @@ -7,12 +7,10 @@ * @format */ -'use strict'; - const fs = require('fs'); const path = require('path'); -module.exports = function(req, res, next) { +module.exports = function indexPageMiddleware(req, res, next) { if (req.url === '/') { res.end(fs.readFileSync(path.join(__dirname, 'index.html'))); } else { diff --git a/packages/local-cli/server/middleware/loadRawBodyMiddleware.js b/packages/local-cli/server/middleware/loadRawBodyMiddleware.js index 553f04129..dd1d70962 100644 --- a/packages/local-cli/server/middleware/loadRawBodyMiddleware.js +++ b/packages/local-cli/server/middleware/loadRawBodyMiddleware.js @@ -7,17 +7,15 @@ * @format */ -'use strict'; - -module.exports = function(req, res, next) { +module.exports = function rawBodyMiddleware(req, res, next) { req.rawBody = ''; req.setEncoding('utf8'); - req.on('data', function(chunk) { + req.on('data', chunk => { req.rawBody += chunk; }); - req.on('end', function() { + req.on('end', () => { next(); }); }; diff --git a/packages/local-cli/server/middleware/openStackFrameInEditorMiddleware.js b/packages/local-cli/server/middleware/openStackFrameInEditorMiddleware.js index 36cc69ba0..0c53c55f1 100644 --- a/packages/local-cli/server/middleware/openStackFrameInEditorMiddleware.js +++ b/packages/local-cli/server/middleware/openStackFrameInEditorMiddleware.js @@ -7,12 +7,12 @@ * @format */ -'use strict'; - const launchEditor = require('../util/launchEditor'); -module.exports = function({watchFolders}) { - return function(req, res, next) { +module.exports = function getOpenStackFrameInEditorMiddleware({ + watchFolders, +}) { + return (req, res, next) => { if (req.url === '/open-stack-frame') { const frame = JSON.parse(req.rawBody); launchEditor(frame.file, frame.lineNumber, watchFolders); diff --git a/packages/local-cli/server/middleware/statusPageMiddleware.js b/packages/local-cli/server/middleware/statusPageMiddleware.js index b08539d57..00584ecbb 100644 --- a/packages/local-cli/server/middleware/statusPageMiddleware.js +++ b/packages/local-cli/server/middleware/statusPageMiddleware.js @@ -7,13 +7,11 @@ * @format */ -'use strict'; - /** * Status page so that anyone who needs to can verify that the packager is * running on 8081 and not another program / service. */ -module.exports = function(req, res, next) { +module.exports = function statusPageMiddleware(req, res, next) { if (req.url === '/status') { res.end('packager-status:running'); } else { diff --git a/packages/local-cli/server/middleware/systraceProfileMiddleware.js b/packages/local-cli/server/middleware/systraceProfileMiddleware.js index c66d6f7be..24c54024c 100644 --- a/packages/local-cli/server/middleware/systraceProfileMiddleware.js +++ b/packages/local-cli/server/middleware/systraceProfileMiddleware.js @@ -7,26 +7,22 @@ * @format */ -'use strict'; - const fs = require('fs'); -module.exports = function(req, res, next) { +module.exports = function systraceProfileMiddleware(req, res, next) { if (req.url !== '/systrace') { next(); return; } console.log('Dumping profile information...'); - var dumpName = '/tmp/dump_' + Date.now() + '.json'; + const dumpName = `/tmp/dump_${Date.now()}.json`; fs.writeFileSync(dumpName, req.rawBody); - var response = - '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 :)'; + const response = + `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 :)`; console.log(response); res.end(response); }; diff --git a/packages/local-cli/server/middleware/unless.js b/packages/local-cli/server/middleware/unless.js index e1aa78ac6..9d04f2f2f 100644 --- a/packages/local-cli/server/middleware/unless.js +++ b/packages/local-cli/server/middleware/unless.js @@ -7,14 +7,10 @@ * @format */ -'use strict'; - -module.exports = (url, middleware) => { - return (req, res, next) => { - if (req.url === url || req.url.startsWith(url + '/')) { - middleware(req, res, next); - } else { - next(); - } - }; +module.exports = (url, middleware) => (req, res, next) => { + if (req.url === url || req.url.startsWith(`${url}/`)) { + middleware(req, res, next); + } else { + next(); + } }; diff --git a/packages/local-cli/server/runServer.js b/packages/local-cli/server/runServer.js index 5daaa5204..e3da6e468 100644 --- a/packages/local-cli/server/runServer.js +++ b/packages/local-cli/server/runServer.js @@ -4,25 +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 + * @flow */ -'use strict'; +import type { ContextT } from '../core/types.flow'; const Metro = require('metro'); const { Terminal } = require('metro-core'); -const messageSocket = require('./util/messageSocket'); const morgan = require('morgan'); const path = require('path'); +const messageSocket = require('./util/messageSocket'); const webSocketProxy = require('./util/webSocketProxy'); const MiddlewareManager = require('./middleware/MiddlewareManager'); const loadMetroConfig = require('../util/loadMetroConfig'); -import type { ContextT } from '../core/types.flow'; - export type Args = {| assetExts?: string[], cert?: string, @@ -57,15 +55,17 @@ async function runServer(argv: *, ctx: ContextT, args: Args) { sourceExts: args.sourceExts, reporter, }); - + const middlewareManager = new MiddlewareManager({ host: args.host, - watchFolders: metroConfig.watchFolders + watchFolders: metroConfig.watchFolders, }); middlewareManager.getConnectInstance().use(morgan('combined')); - metroConfig.watchFolders.forEach(middlewareManager.serveStatic.bind(middlewareManager)); + metroConfig.watchFolders.forEach( + middlewareManager.serveStatic.bind(middlewareManager) + ); metroConfig.server.enhanceMiddleware = middleware => middlewareManager.getConnectInstance().use(middleware); @@ -80,7 +80,7 @@ async function runServer(argv: *, ctx: ContextT, args: Args) { const wsProxy = webSocketProxy.attachToServer( serverInstance, - '/debugger-proxy', + '/debugger-proxy' ); const ms = messageSocket.attachToServer(serverInstance, '/message'); middlewareManager.attachDevToolsSocket(wsProxy); diff --git a/packages/local-cli/server/server.js b/packages/local-cli/server/server.js index 8a4d950c0..c6eed0d37 100644 --- a/packages/local-cli/server/server.js +++ b/packages/local-cli/server/server.js @@ -8,12 +8,8 @@ * @flow */ -'use strict'; - const path = require('path'); -import type { ContextT } from '../core/types.flow'; - module.exports = { name: 'start', func: require('./runServer'), diff --git a/packages/local-cli/server/util/copyToClipBoard.js b/packages/local-cli/server/util/copyToClipBoard.js index e6b1bd7a1..ebc728ccc 100644 --- a/packages/local-cli/server/util/copyToClipBoard.js +++ b/packages/local-cli/server/util/copyToClipBoard.js @@ -7,32 +7,34 @@ * @format */ -'use strict'; +const { spawn } = require('child_process'); -var child_process = require('child_process'); -var spawn = child_process.spawn; -var path = require('path'); -var fs = require('fs'); +const path = require('path'); +const fs = require('fs'); const xsel = path.join(__dirname, 'external/xsel'); fs.chmodSync(xsel, '0755'); + /** * Copy the content to host system clipboard. */ function copyToClipBoard(content) { switch (process.platform) { - case 'darwin': - var child = spawn('pbcopy', []); + case 'darwin': { + const child = spawn('pbcopy', []); child.stdin.end(Buffer.from(content, 'utf8')); return true; - case 'win32': - var child = spawn('clip', []); + } + case 'win32': { + const child = spawn('clip', []); child.stdin.end(Buffer.from(content, 'utf8')); return true; - case 'linux': - var child = spawn(xsel, ['--clipboard', '--input']); + } + case 'linux': { + const child = spawn(xsel, ['--clipboard', '--input']); child.stdin.end(Buffer.from(content, 'utf8')); return true; + } default: return false; } diff --git a/packages/local-cli/server/util/jsPackagerClient.js b/packages/local-cli/server/util/jsPackagerClient.js index 08e6516f5..cf36357e4 100644 --- a/packages/local-cli/server/util/jsPackagerClient.js +++ b/packages/local-cli/server/util/jsPackagerClient.js @@ -7,11 +7,9 @@ * @format */ -'use strict'; - const WebSocket = require('ws'); -const parseMessage = require('./messageSocket').parseMessage; +const { parseMessage } = require('./messageSocket'); const PROTOCOL_VERSION = 2; const TARGET_SERVER = 'server'; @@ -37,12 +35,10 @@ class JsPackagerClient { // gracefully ignore wrong messages or broadcasts } else if (msgCallback === undefined) { console.warn(`Response with non-existing message id: '${message.id}'`); + } else if (message.error === undefined) { + msgCallback.resolve(message.result); } else { - if (message.error === undefined) { - msgCallback.resolve(message.result); - } else { - msgCallback.reject(message.error); - } + msgCallback.reject(message.error); } }); } @@ -52,23 +48,23 @@ class JsPackagerClient { () => new Promise((resolve, reject) => { const messageId = getMessageId(); - this.msgCallbacks.set(messageId, {resolve: resolve, reject: reject}); + this.msgCallbacks.set(messageId, { resolve, reject }); this.ws.send( JSON.stringify({ version: PROTOCOL_VERSION, - target: target, - method: method, + target, + method, id: messageId, - params: params, + params, }), error => { if (error !== undefined) { this.msgCallbacks.delete(messageId); reject(error); } - }, + } ); - }), + }) ); } @@ -79,9 +75,9 @@ class JsPackagerClient { this.ws.send( JSON.stringify({ version: PROTOCOL_VERSION, - target: target, - method: method, - params: params, + target, + method, + params, }), error => { if (error !== undefined) { @@ -89,9 +85,9 @@ class JsPackagerClient { } else { resolve(); } - }, + } ); - }), + }) ); } @@ -102,10 +98,13 @@ class JsPackagerClient { getPeers() { return new Promise((resolve, reject) => { this.sendRequest('getpeers', TARGET_SERVER, undefined).then(response => { - if (!response instanceof Map) { + if (!(response instanceof Map)) { reject( - 'Results received from server are of wrong format:\n' + - JSON.stringify(response), + new Error( + `Results received from server are of wrong format:\n${JSON.stringify( + response + )}` + ) ); } else { resolve(response); diff --git a/packages/local-cli/server/util/launchChrome.js b/packages/local-cli/server/util/launchChrome.js index 854ae20c8..67c449d2a 100644 --- a/packages/local-cli/server/util/launchChrome.js +++ b/packages/local-cli/server/util/launchChrome.js @@ -8,23 +8,17 @@ * @flow */ -'use strict'; - /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error * found when Flow v0.54 was deployed. To see the error delete this comment and * run Flow. */ const opn = require('opn'); -const execSync = require('child_process').execSync; +const { execSync } = require('child_process'); -function commandExistsUnixSync(commandName, callback) { +function commandExistsUnixSync(commandName) { try { - var stdout = execSync( - 'command -v ' + - commandName + - ' 2>/dev/null' + - " && { echo >&1 '" + - commandName + - " found'; exit 0; }", + const stdout = execSync( + `command -v ${commandName} 2>/dev/null` + + ` && { echo >&1 '${commandName} found'; exit 0; }` ); return !!stdout; } catch (error) { @@ -41,18 +35,19 @@ function getChromeAppName(): string { case 'linux': if (commandExistsUnixSync('google-chrome')) { return 'google-chrome'; - } else if (commandExistsUnixSync('chromium-browser')) { + } + if (commandExistsUnixSync('chromium-browser')) { return 'chromium-browser'; - } else { - return 'chromium'; } + return 'chromium'; + default: return 'google-chrome'; } } function launchChrome(url: string) { - opn(url, {app: [getChromeAppName()]}, function(err) { + opn(url, { app: [getChromeAppName()] }, err => { if (err) { console.error('Google Chrome exited with error:', err); } diff --git a/packages/local-cli/server/util/launchEditor.js b/packages/local-cli/server/util/launchEditor.js index ac965b085..211d5c80c 100644 --- a/packages/local-cli/server/util/launchEditor.js +++ b/packages/local-cli/server/util/launchEditor.js @@ -7,12 +7,10 @@ * @format */ -'use strict'; - -var chalk = require('chalk'); -var fs = require('fs'); -var path = require('path'); -var child_process = require('child_process'); +const chalk = require('chalk'); +const fs = require('fs'); +const path = require('path'); +const { execSync, spawn } = require('child_process'); const isAbsolutePath = require('absolute-path'); const shellQuote = require('shell-quote'); @@ -22,14 +20,15 @@ function isTerminalEditor(editor) { case 'emacs': case 'nano': return true; + default: + return false; } - return false; } // Map from full process name to binary that starts the process // We can't just re-use full process name, because it will spawn a new instance // of the app every time -var COMMON_EDITORS = { +const COMMON_EDITORS = { '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', @@ -58,7 +57,7 @@ function getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) { switch (path.basename(editor)) { case 'vim': case 'mvim': - return [fileName, '+' + lineNumber]; + return [fileName, `+${lineNumber}`]; case 'atom': case 'Atom': case 'Atom Beta': @@ -69,26 +68,26 @@ function getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) { case 'appcode': case 'charm': case 'idea': - return [fileName + ':' + lineNumber]; + return [`${fileName}:${lineNumber}`]; case 'joe': case 'emacs': case 'emacsclient': - return ['+' + lineNumber, fileName]; + return [`+${lineNumber}`, fileName]; case 'rmate': case 'mate': case 'mine': return ['--line', lineNumber, fileName]; case 'code': return addWorkspaceToArgumentsIfExists( - ['-g', fileName + ':' + lineNumber], - workspace, + ['-g', `${fileName}:${lineNumber}`], + workspace ); + // For all others, drop the lineNumber until we have + // a mapping above, since providing the lineNumber incorrectly + // can result in errors or confusing behavior. + default: + return [fileName]; } - - // For all others, drop the lineNumber until we have - // a mapping above, since providing the lineNumber incorrectly - // can result in errors or confusing behavior. - return [fileName]; } function guessEditor() { @@ -101,10 +100,10 @@ function guessEditor() { // Potentially we could use similar technique for Windows and Linux if (process.platform === 'darwin') { try { - var output = child_process.execSync('ps x').toString(); - var processNames = Object.keys(COMMON_EDITORS); - for (var i = 0; i < processNames.length; i++) { - var processName = processNames[i]; + const output = execSync('ps x').toString(); + const processNames = Object.keys(COMMON_EDITORS); + for (let i = 0; i < processNames.length; i++) { + const processName = processNames[i]; if (output.indexOf(processName) !== -1) { return [COMMON_EDITORS[processName]]; } @@ -117,7 +116,8 @@ function guessEditor() { // Last resort, use old skool env vars if (process.env.VISUAL) { return [process.env.VISUAL]; - } else if (process.env.EDITOR) { + } + if (process.env.EDITOR) { return [process.env.EDITOR]; } @@ -128,7 +128,7 @@ function printInstructions(title) { console.log( [ '', - chalk.bgBlue.white.bold(' ' + title + ' '), + 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 ', @@ -136,26 +136,26 @@ function printInstructions(title) { ' export REACT_EDITOR=atom to your ~/.bashrc or ~/.zshrc depending on ', ' which shell you use.', '', - ].join('\n'), + ].join('\n') ); } function transformToAbsolutePathIfNeeded(pathName) { if (!isAbsolutePath(pathName)) { - pathName = path.resolve(process.cwd(), pathName); + return path.resolve(process.cwd(), pathName); } return pathName; } function findRootForFile(projectRoots, fileName) { - fileName = transformToAbsolutePathIfNeeded(fileName); + const absoluteFileName = transformToAbsolutePathIfNeeded(fileName); return projectRoots.find(root => { - root = transformToAbsolutePathIfNeeded(root); - return fileName.startsWith(root + path.sep); + const absoluteRoot = transformToAbsolutePathIfNeeded(root); + return absoluteFileName.startsWith(absoluteRoot + path.sep); }); } -var _childProcess = null; +let _childProcess = null; function launchEditor(fileName, lineNumber, projectRoots) { if (!fs.existsSync(fileName)) { return; @@ -167,16 +167,16 @@ function launchEditor(fileName, lineNumber, projectRoots) { return; } - let [editor, ...args] = guessEditor(); + let [editor, ...args] = guessEditor(); // eslint-disable-line prefer-const if (!editor) { printInstructions('PRO TIP'); return; } - var workspace = findRootForFile(projectRoots, fileName); + const workspace = findRootForFile(projectRoots, fileName); if (lineNumber) { args = args.concat( - getArgumentsForLineNumber(editor, fileName, lineNumber, workspace), + getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) ); } else { args.push(fileName); @@ -192,23 +192,21 @@ function launchEditor(fileName, lineNumber, projectRoots) { ) { console.log(); console.log( - chalk.red( - 'Could not open ' + path.basename(fileName) + ' in the editor.', - ), + chalk.red(`Could not open ${path.basename(fileName)} in the editor.`) ); console.log(); console.log( 'When running on Windows, file names are checked against a whitelist ' + 'to protect against remote code execution attacks. File names may ' + 'consist only of alphanumeric characters (all languages), periods, ' + - 'dashes, slashes, and underscores.', + 'dashes, slashes, and underscores.' ); console.log(); return; } console.log( - 'Opening ' + chalk.underline(fileName) + ' with ' + chalk.bold(editor), + `Opening ${chalk.underline(fileName)} with ${chalk.bold(editor)}` ); if (_childProcess && isTerminalEditor(editor)) { @@ -221,15 +219,13 @@ 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 = spawn('cmd.exe', ['/C', editor].concat(args), { + stdio: 'inherit', + }); } else { - _childProcess = child_process.spawn(editor, args, {stdio: 'inherit'}); + _childProcess = spawn(editor, args, { stdio: 'inherit' }); } - _childProcess.on('exit', function(errorCode) { + _childProcess.on('exit', errorCode => { _childProcess = null; if (errorCode) { @@ -238,7 +234,7 @@ function launchEditor(fileName, lineNumber, projectRoots) { } }); - _childProcess.on('error', function(error) { + _childProcess.on('error', error => { console.log(chalk.red(error.message)); printInstructions('How to fix:'); }); diff --git a/packages/local-cli/server/util/messageSocket.js b/packages/local-cli/server/util/messageSocket.js index a151f7916..30b02da90 100644 --- a/packages/local-cli/server/util/messageSocket.js +++ b/packages/local-cli/server/util/messageSocket.js @@ -3,14 +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 */ -'use strict'; - const url = require('url'); const WebSocketServer = require('ws').Server; + const PROTOCOL_VERSION = 2; const notifier = require('node-notifier'); @@ -25,10 +22,10 @@ function parseMessage(data, binary) { return message; } console.error( - 'Received message had wrong protocol version: ' + message.version, + `Received message had wrong protocol version: ${message.version}` ); } catch (e) { - console.error('Failed to parse the message as JSON:\n' + data); + console.error(`Failed to parse the message as JSON:\n${data}`); } return undefined; } @@ -50,7 +47,7 @@ function isRequest(message) { function isResponse(message) { return ( typeof message.id === 'object' && - typeof message.id.requestId !== undefined && + typeof message.id.requestId !== 'undefined' && typeof message.id.clientId === 'string' && (message.result !== undefined || message.error !== undefined) ); @@ -58,8 +55,8 @@ function isResponse(message) { function attachToServer(server, path) { const wss = new WebSocketServer({ - server: server, - path: path, + server, + path, }); const clients = new Map(); let nextClientId = 0; @@ -67,7 +64,9 @@ function attachToServer(server, path) { function getClientWs(clientId) { const clientWs = clients.get(clientId); if (clientWs === undefined) { - throw `could not find id "${clientId}" while forwarding request`; + throw new Error( + `could not find id "${clientId}" while forwarding request` + ); } return clientWs; } @@ -94,14 +93,14 @@ function attachToServer(server, path) { } catch (e) { console.error( `Failed to send broadcast to client: '${otherId}' ` + - `due to:\n ${e.toString()}`, + `due to:\n ${e.toString()}` ); } } } } - wss.on('connection', function(clientWs) { + wss.on('connection', clientWs => { const clientId = `client#${nextClientId++}`; function handleCaughtError(message, error) { @@ -117,22 +116,22 @@ 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, + 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()}`, + `\ndue to error: ${e.toString()}` ); } } @@ -153,15 +152,15 @@ function attachToServer(server, path) { }); break; default: - throw `unknown method: ${message.method}`; + throw new Error(`unknown method: ${message.method}`); } clientWs.send( JSON.stringify({ version: PROTOCOL_VERSION, - result: result, + result, id: message.id, - }), + }) ); } @@ -174,8 +173,8 @@ function attachToServer(server, path) { id: message.id === undefined ? undefined - : {requestId: message.id, clientId: clientId}, - }), + : { requestId: message.id, clientId }, + }) ); } @@ -186,15 +185,18 @@ function attachToServer(server, path) { result: message.result, error: message.error, id: message.id.requestId, - }), + }) ); } clients.set(clientId, clientWs); - clientWs.onclose = clientWs.onerror = () => { - clientWs.onmessage = null; + const onCloseHandler = () => { + clientWs.onmessage = null; // eslint-disable-line no-param-reassign clients.delete(clientId); }; + clientWs.onclose = onCloseHandler; // eslint-disable-line no-param-reassign + clientWs.onerror = onCloseHandler; // eslint-disable-line no-param-reassign + // eslint-disable-next-line no-param-reassign clientWs.onmessage = event => { const message = parseMessage(event.data, event.binary); if (message === undefined) { @@ -214,7 +216,7 @@ function attachToServer(server, path) { } else if (isResponse(message)) { forwardResponse(message); } else { - throw 'Invalid message, did not match the protocol'; + throw new Error('Invalid message, did not match the protocol'); } } catch (e) { handleCaughtError(message, e.toString()); @@ -224,12 +226,12 @@ function attachToServer(server, path) { return { broadcast: (method, params) => { - handleSendBroadcast(null, {method: method, params: params}); + handleSendBroadcast(null, { method, params }); }, }; } module.exports = { - attachToServer: attachToServer, - parseMessage: parseMessage, + attachToServer, + parseMessage, }; diff --git a/packages/local-cli/server/util/webSocketProxy.js b/packages/local-cli/server/util/webSocketProxy.js index 097a5de53..a7d0c8a9d 100644 --- a/packages/local-cli/server/util/webSocketProxy.js +++ b/packages/local-cli/server/util/webSocketProxy.js @@ -7,15 +7,15 @@ * @format */ -'use strict'; - function attachToServer(server, path) { - var WebSocketServer = require('ws').Server; - var wss = new WebSocketServer({ - server: server, - path: path, + const WebSocketServer = require('ws').Server; + const wss = new WebSocketServer({ + server, + path, }); - var debuggerSocket, clientSocket; + + let debuggerSocket; + let clientSocket; function send(dest, message) { if (!dest) { @@ -30,8 +30,20 @@ function attachToServer(server, path) { } } - wss.on('connection', function(ws) { - const {url} = ws.upgradeReq; + const debuggerSocketCloseHandler = () => { + debuggerSocket = null; + if (clientSocket) { + clientSocket.close(1011, 'Debugger was disconnected'); + } + }; + + const clientSocketCloseHandler = () => { + clientSocket = null; + send(debuggerSocket, JSON.stringify({ method: '$disconnected' })); + }; + + wss.on('connection', ws => { + const { url } = ws.upgradeReq; if (url.indexOf('role=debugger') > -1) { if (debuggerSocket) { @@ -39,24 +51,20 @@ function attachToServer(server, path) { return; } debuggerSocket = ws; - debuggerSocket.onerror = debuggerSocket.onclose = () => { - debuggerSocket = null; - if (clientSocket) { - clientSocket.close(1011, 'Debugger was disconnected'); - } - }; - debuggerSocket.onmessage = ({data}) => send(clientSocket, data); + debuggerSocket.onerror = debuggerSocketCloseHandler; + debuggerSocket.onclose = debuggerSocketCloseHandler; + debuggerSocket.onmessage = ({ data }) => send(clientSocket, data); } else if (url.indexOf('role=client') > -1) { if (clientSocket) { - clientSocket.onerror = clientSocket.onclose = clientSocket.onmessage = null; + clientSocket.onerror = null; + clientSocket.onclose = null; + clientSocket.onmessage = null; clientSocket.close(1011, 'Another client connected'); } clientSocket = ws; - clientSocket.onerror = clientSocket.onclose = () => { - clientSocket = null; - send(debuggerSocket, JSON.stringify({method: '$disconnected'})); - }; - clientSocket.onmessage = ({data}) => send(debuggerSocket, data); + clientSocket.onerror = clientSocketCloseHandler; + clientSocket.onclose = clientSocketCloseHandler; + clientSocket.onmessage = ({ data }) => send(debuggerSocket, data); } else { ws.close(1011, 'Missing role param'); } @@ -64,12 +72,12 @@ function attachToServer(server, path) { return { server: wss, - isChromeConnected: function() { + isChromeConnected() { return !!debuggerSocket; }, }; } module.exports = { - attachToServer: attachToServer, + attachToServer, }; diff --git a/packages/local-cli/templates/HelloWorld/App.js b/packages/local-cli/templates/HelloWorld/App.js index bb4823295..dd74fbabe 100644 --- a/packages/local-cli/templates/HelloWorld/App.js +++ b/packages/local-cli/templates/HelloWorld/App.js @@ -7,8 +7,8 @@ * @lint-ignore-every XPLATJSCOPYRIGHT1 */ -import React, {Component} from 'react'; -import {Platform, StyleSheet, Text, View} from 'react-native'; +import React, { Component } from 'react'; +import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', diff --git a/packages/local-cli/templates/HelloWorld/__tests__/App-test.js b/packages/local-cli/templates/HelloWorld/__tests__/App-test.js index a79ec3d58..cde09261e 100644 --- a/packages/local-cli/templates/HelloWorld/__tests__/App-test.js +++ b/packages/local-cli/templates/HelloWorld/__tests__/App-test.js @@ -5,10 +5,10 @@ import 'react-native'; import React from 'react'; +import renderer from 'react-test-renderer'; import App from '../App'; // Note: test renderer must be required after react-native. -import renderer from 'react-test-renderer'; it('renders correctly', () => { renderer.create(); diff --git a/packages/local-cli/templates/HelloWorld/index.js b/packages/local-cli/templates/HelloWorld/index.js index 3ac66525d..ad1dc02b6 100644 --- a/packages/local-cli/templates/HelloWorld/index.js +++ b/packages/local-cli/templates/HelloWorld/index.js @@ -3,8 +3,8 @@ * @lint-ignore-every XPLATJSCOPYRIGHT1 */ -import {AppRegistry} from 'react-native'; +import { AppRegistry } from 'react-native'; import App from './App'; -import {name as appName} from './app.json'; +import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App); diff --git a/packages/local-cli/upgrade/upgrade.js b/packages/local-cli/upgrade/upgrade.js index 202afe52c..fdaad1b04 100644 --- a/packages/local-cli/upgrade/upgrade.js +++ b/packages/local-cli/upgrade/upgrade.js @@ -7,13 +7,11 @@ * @format */ -'use strict'; - const chalk = require('chalk'); -const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace'); const fs = require('fs'); const path = require('path'); const semver = require('semver'); +const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace'); /** * Migrate application to a new version of React Native. @@ -28,7 +26,7 @@ function validateAndUpgrade() { const projectDir = process.cwd(); const packageJSON = JSON.parse( - fs.readFileSync(path.resolve(projectDir, 'package.json'), 'utf8'), + fs.readFileSync(path.resolve(projectDir, 'package.json'), 'utf8') ); warn( @@ -38,14 +36,14 @@ function validateAndUpgrade() { '- Go back to the old version of React Native\n' + '- Run "npm install -g react-native-git-upgrade"\n' + '- Run "react-native-git-upgrade"\n' + - 'See https://facebook.github.io/react-native/docs/upgrading.html', + 'See https://facebook.github.io/react-native/docs/upgrading.html' ); const projectName = packageJSON.name; if (!projectName) { warn( 'Your project needs to have a name, declared in package.json, ' + - 'such as "name": "AwesomeApp". Please add a project name. Aborting.', + 'such as "name": "AwesomeApp". Please add a project name. Aborting.' ); return; } @@ -54,7 +52,7 @@ function validateAndUpgrade() { if (!version) { warn( 'Your "package.json" file doesn\'t seem to declare "react-native" as ' + - 'a dependency. Nothing to upgrade. Aborting.', + 'a dependency. Nothing to upgrade. Aborting.' ); return; } @@ -63,7 +61,7 @@ function validateAndUpgrade() { warn( 'Some major releases introduce breaking changes.\n' + 'Please use a caret version number in your "package.json" file \n' + - 'to avoid breakage. Use e.g. react-native: ^0.38.0. Aborting.', + 'to avoid breakage. Use e.g. react-native: ^0.38.0. Aborting.' ); return; } @@ -71,15 +69,15 @@ function validateAndUpgrade() { const installed = JSON.parse( fs.readFileSync( path.resolve(projectDir, 'node_modules/react-native/package.json'), - 'utf8', - ), + 'utf8' + ) ); if (!semver.satisfies(installed.version, version)) { warn( 'react-native version in "package.json" doesn\'t match ' + 'the installed version in "node_modules".\n' + - 'Try running "npm install" to fix this. Aborting.', + 'Try running "npm install" to fix this. Aborting.' ); return; } @@ -89,21 +87,17 @@ function validateAndUpgrade() { if (!semver.valid(v)) { warn( "A valid version number for 'react-native' is not specified in your " + - "'package.json' file. Aborting.", + "'package.json' file. Aborting." ); return; } console.log( - 'Upgrading project to react-native v' + - installed.version + - '\n' + - 'Check out the release notes and breaking changes: ' + - 'https://github.com/facebook/react-native/releases/tag/v' + - semver.major(v) + - '.' + - semver.minor(v) + - '.0', + `Upgrading project to react-native v${installed.version}\n` + + `Check out the release notes and breaking changes: ` + + `https://github.com/facebook/react-native/releases/tag/v${semver.major( + v + )}.${semver.minor(v)}.0` ); // >= v0.21.0, we require react to be a peer dependency @@ -112,7 +106,7 @@ function validateAndUpgrade() { 'Your "package.json" file doesn\'t seem to have "react" as a dependency.\n' + '"react" was changed from a dependency to a peer dependency in react-native v0.21.0.\n' + 'Therefore, it\'s necessary to include "react" in your project\'s dependencies.\n' + - 'Please run "npm install --save react", then re-run "react-native upgrade".\n', + 'Please run "npm install --save react", then re-run "react-native upgrade".\n' ); return; } @@ -124,18 +118,15 @@ function validateAndUpgrade() { 'to do it automatically.\n' + 'Just run:\n' + '"npm install -g rnpm && npm install rnpm-plugin-upgrade@0.26 --save-dev", ' + - 'then run "rnpm upgrade".', + 'then run "rnpm upgrade".' ); } - return new Promise(resolve => { - upgradeProjectFiles(projectDir, projectName); - console.log( - 'Successfully upgraded this project to react-native v' + - installed.version, - ); - resolve(); - }); + upgradeProjectFiles(projectDir, projectName); + + console.log( + `Successfully upgraded this project to react-native v${installed.version}` + ); } /** @@ -149,11 +140,11 @@ function upgradeProjectFiles(projectDir, projectName) { 'react-native', 'local-cli', 'templates', - 'HelloWorld', + 'HelloWorld' ), projectDir, projectName, - {upgrade: true}, + { upgrade: true } ); } diff --git a/packages/local-cli/util/PackageManager.js b/packages/local-cli/util/PackageManager.js index fe0783ec7..d6e9cda86 100644 --- a/packages/local-cli/util/PackageManager.js +++ b/packages/local-cli/util/PackageManager.js @@ -7,10 +7,9 @@ * @format */ -'use strict'; - -const spawnSync = require('child_process').spawnSync; +const { spawnSync } = require('child_process'); const yarn = require('../util/yarn'); + const spawnOpts = { stdio: 'inherit', stdin: 'inherit', @@ -52,7 +51,7 @@ function callYarnOrNpm(yarnCommand, npmCommand) { function add(packageName) { return callYarnOrNpm( `yarn add ${packageName}`, - `npm install ${packageName} --save`, + `npm install ${packageName} --save` ); } @@ -64,11 +63,11 @@ function add(packageName) { function remove(packageName) { return callYarnOrNpm( `yarn remove ${packageName}`, - `npm uninstall --save ${packageName}`, + `npm uninstall --save ${packageName}` ); } module.exports = { - add: add, - remove: remove, + add, + remove, }; diff --git a/packages/local-cli/util/__mocks__/log.js b/packages/local-cli/util/__mocks__/log.js index 330cae48f..33dbe25a2 100644 --- a/packages/local-cli/util/__mocks__/log.js +++ b/packages/local-cli/util/__mocks__/log.js @@ -7,7 +7,5 @@ * @format */ -'use strict'; - module.exports.out = () => jest.fn(); module.exports.err = () => jest.fn(); diff --git a/packages/local-cli/util/assertRequiredOptions.js b/packages/local-cli/util/assertRequiredOptions.js index 379ad1fc1..bddd4ebe3 100644 --- a/packages/local-cli/util/assertRequiredOptions.js +++ b/packages/local-cli/util/assertRequiredOptions.js @@ -7,10 +7,8 @@ * @format */ -'use strict'; - -const {Option} = require('commander'); -const {camelCase} = require('lodash'); +const { Option } = require('commander'); +const { camelCase } = require('lodash'); // Commander.js has a 2 years old open issue to support <...> syntax // for options. Until that gets merged, we run the checks manually diff --git a/packages/local-cli/util/copyAndReplace.js b/packages/local-cli/util/copyAndReplace.js index d0d4eb15a..67ade61c8 100644 --- a/packages/local-cli/util/copyAndReplace.js +++ b/packages/local-cli/util/copyAndReplace.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const path = require('path'); @@ -31,7 +29,7 @@ function copyAndReplace( srcPath, destPath, replacements, - contentChangedCallback, + contentChangedCallback ) { if (fs.lstatSync(srcPath).isDirectory()) { if (!fs.existsSync(destPath)) { @@ -73,13 +71,9 @@ function copyAndReplace( // Text file const srcPermissions = fs.statSync(srcPath).mode; let content = fs.readFileSync(srcPath, 'utf8'); - Object.keys(replacements).forEach( - regex => - (content = content.replace( - new RegExp(regex, 'g'), - replacements[regex], - )), - ); + Object.keys(replacements).forEach(regex => { + content = content.replace(new RegExp(regex, 'g'), replacements[regex]); + }); let shouldOverwrite = 'overwrite'; if (contentChangedCallback) { @@ -88,7 +82,7 @@ function copyAndReplace( try { const origContent = fs.readFileSync(destPath, 'utf8'); if (content !== origContent) { - //console.log('Content changed: ' + destPath); + // console.log('Content changed: ' + destPath); contentChanged = 'changed'; } } catch (err) { @@ -116,16 +110,16 @@ function copyBinaryFile(srcPath, destPath, cb) { let cbCalled = false; const srcPermissions = fs.statSync(srcPath).mode; const readStream = fs.createReadStream(srcPath); - readStream.on('error', function(err) { + readStream.on('error', err => { done(err); }); const writeStream = fs.createWriteStream(destPath, { mode: srcPermissions, }); - writeStream.on('error', function(err) { + writeStream.on('error', err => { done(err); }); - writeStream.on('close', function(ex) { + writeStream.on('close', () => { done(); }); readStream.pipe(writeStream); diff --git a/packages/local-cli/util/findReactNativeScripts.js b/packages/local-cli/util/findReactNativeScripts.js index 5d43e2948..0bacfc209 100644 --- a/packages/local-cli/util/findReactNativeScripts.js +++ b/packages/local-cli/util/findReactNativeScripts.js @@ -8,8 +8,6 @@ * @flow strict */ -'use strict'; - const path = require('path'); const fs = require('fs'); @@ -17,7 +15,7 @@ function findReactNativeScripts(): ?string { const executablePath = path.resolve( 'node_modules', '.bin', - 'react-native-scripts', + 'react-native-scripts' ); if (fs.existsSync(executablePath)) { return executablePath; diff --git a/packages/local-cli/util/findSymlinkedModules.js b/packages/local-cli/util/findSymlinkedModules.js index a88b41f08..c64b65d7f 100644 --- a/packages/local-cli/util/findSymlinkedModules.js +++ b/packages/local-cli/util/findSymlinkedModules.js @@ -32,7 +32,7 @@ const fs = require('fs'); */ module.exports = function findSymlinkedModules( projectRoot: string, - ignoredRoots?: Array = [], + ignoredRoots?: Array = [] ) { const nodeModuleRoot = path.join(projectRoot, 'node_modules'); const resolvedSymlinks = findModuleSymlinks(nodeModuleRoot, [ @@ -44,7 +44,7 @@ module.exports = function findSymlinkedModules( function findModuleSymlinks( modulesPath: string, - ignoredPaths: Array = [], + ignoredPaths: Array = [] ): Array { if (!fs.existsSync(modulesPath)) { return []; @@ -58,7 +58,7 @@ function findModuleSymlinks( if (folderName.startsWith('@')) { const scopedModuleFolders = fs.readdirSync(folderPath); maybeSymlinkPaths.push( - ...scopedModuleFolders.map(name => path.join(folderPath, name)), + ...scopedModuleFolders.map(name => path.join(folderPath, name)) ); } else { maybeSymlinkPaths.push(folderPath); @@ -76,9 +76,9 @@ function findModuleSymlinks( findModuleSymlinks(path.join(symlinkPath, 'node_modules'), [ ...ignoredPaths, ...symlinks, - ]), + ]) ), - [], + [] ); return [...new Set([...symlinks, ...nestedSymlinks])]; @@ -89,7 +89,7 @@ function resolveSymlinkPaths(maybeSymlinkPaths, ignoredPaths) { if (fs.lstatSync(maybeSymlinkPath).isSymbolicLink()) { const resolved = path.resolve( path.dirname(maybeSymlinkPath), - fs.readlinkSync(maybeSymlinkPath), + fs.readlinkSync(maybeSymlinkPath) ); if (ignoredPaths.indexOf(resolved) === -1 && fs.existsSync(resolved)) { links.push(resolved); diff --git a/packages/local-cli/util/findSymlinksPaths.js b/packages/local-cli/util/findSymlinksPaths.js deleted file mode 100644 index 5efa20e88..000000000 --- a/packages/local-cli/util/findSymlinksPaths.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) Facebook, Inc. and its affiliates. - * - * 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'); -const fs = require('fs'); - -/** - * Find and resolve symlinks in `lookupFolder`. - * Ignore any descendants of the paths in `ignoredRoots`. - */ -module.exports = function findSymlinksPaths(lookupFolder, ignoredRoots) { - const timeStart = Date.now(); - const folders = fs.readdirSync(lookupFolder); - - const resolvedSymlinks = []; - folders.forEach(folder => { - const visited = []; - - let symlink = path.resolve(lookupFolder, folder); - while (fs.lstatSync(symlink).isSymbolicLink()) { - const index = visited.indexOf(symlink); - if (index !== -1) { - throw Error( - 'Infinite symlink recursion detected:\n ' + - visited.slice(index).join('\n '), - ); - } - - visited.push(symlink); - symlink = path.resolve(path.dirname(symlink), fs.readlinkSync(symlink)); - } - - if (visited.length && !rootExists(ignoredRoots, symlink)) { - resolvedSymlinks.push(symlink); - } - }); - - const timeEnd = Date.now(); - console.log( - `Scanning ${ - folders.length - } folders for symlinks in ${lookupFolder} (${timeEnd - timeStart}ms)`, - ); - - return resolvedSymlinks; -}; - -function rootExists(roots, child) { - return roots.some(root => isDescendant(root, child)); -} - -function isDescendant(root, child) { - return root === child || child.startsWith(root + path.sep); -} diff --git a/packages/local-cli/util/isInstalledGlobally.js b/packages/local-cli/util/isInstalledGlobally.js index c817a0812..ac17baaad 100644 --- a/packages/local-cli/util/isInstalledGlobally.js +++ b/packages/local-cli/util/isInstalledGlobally.js @@ -15,11 +15,10 @@ module.exports = function isInstalledGlobally() { const path = require('path'); // On Windows, assume we are installed globally if we can't find a // package.json above node_modules. - return !fs.existsSync(path.join(__dirname, '../../../package.json'), ); - } else { - // On non-windows, assume we are installed globally if we are called from - // outside of the node_mobules/.bin/react-native executable. - var script = process.argv[1]; - return script.indexOf('node_modules/.bin/react-native') === -1; + return !fs.existsSync(path.join(__dirname, '../../../package.json')); } + // On non-windows, assume we are installed globally if we are called from + // outside of the node_mobules/.bin/react-native executable. + const script = process.argv[1]; + return script.indexOf('node_modules/.bin/react-native') === -1; }; diff --git a/packages/local-cli/util/isPackagerRunning.js b/packages/local-cli/util/isPackagerRunning.js index f8c33e584..57d2be844 100644 --- a/packages/local-cli/util/isPackagerRunning.js +++ b/packages/local-cli/util/isPackagerRunning.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fetch = require('node-fetch'); /** @@ -25,11 +23,10 @@ function isPackagerRunning(packagerPort = process.env.RCT_METRO_PORT || 8081) { res => res .text() - .then( - body => - body === 'packager-status:running' ? 'running' : 'unrecognized', + .then(body => + body === 'packager-status:running' ? 'running' : 'unrecognized' ), - () => 'not_running', + () => 'not_running' ); } diff --git a/packages/local-cli/util/isValidPackageName.js b/packages/local-cli/util/isValidPackageName.js index 45a02319c..03f9fbf26 100644 --- a/packages/local-cli/util/isValidPackageName.js +++ b/packages/local-cli/util/isValidPackageName.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - function isValidPackageName(name) { return name.match(/^[$A-Z_][0-9A-Z_$]*$/i); } diff --git a/packages/local-cli/util/loadMetroConfig.js b/packages/local-cli/util/loadMetroConfig.js index 8bb68c843..275b6694a 100644 --- a/packages/local-cli/util/loadMetroConfig.js +++ b/packages/local-cli/util/loadMetroConfig.js @@ -1,25 +1,24 @@ /** * @flow */ -'use strict'; +/* eslint-disable no-param-reassign */ +/** + * Configuration file of Metro. + */ +import type { ConfigT } from 'metro-config/src/configTypes.flow'; -const findSymlinkedModules = require('./findSymlinkedModules'); const path = require('path'); -const {createBlacklist} = require('metro'); -const {loadConfig} = require('metro-config'); +const { createBlacklist } = require('metro'); +const { loadConfig } = require('metro-config'); +const findSymlinkedModules = require('./findSymlinkedModules'); const findPlugins = require('../core/findPlugins'); -/** - * Configuration file of Metro. - */ -import type {ConfigT} from 'metro-config/src/configTypes.flow'; - -const resolveSymlinksForRoots = (roots) => +const resolveSymlinksForRoots = roots => roots.reduce( (arr, rootPath) => arr.concat(findSymlinkedModules(rootPath, roots)), - [...roots], + [...roots] ); const getWatchFolders = () => { @@ -30,26 +29,27 @@ const getWatchFolders = () => { return []; }; -const getBlacklistRE = () => { - return createBlacklist([/.*\/__fixtures__\/.*/]); -}; +const getBlacklistRE = () => createBlacklist([/.*\/__fixtures__\/.*/]); /** * Default configuration - * + * * @todo(grabbou): As a separate PR, haste.platforms should be added before "native". * Otherwise, a.native.js will not load on Windows or other platforms */ const getDefaultConfig = (root: string) => { const plugins = findPlugins(root); - return ({ + return { resolver: { resolverMainFields: ['react-native', 'browser', 'main'], blacklistRE: getBlacklistRE(), platforms: ['ios', 'android', 'native', ...plugins.haste.platforms], - providesModuleNodeModules: ['react-native', ...plugins.haste.providesModuleNodeModules], - hasteImplModulePath: require.resolve('react-native/jest/hasteImpl') + providesModuleNodeModules: [ + 'react-native', + ...plugins.haste.providesModuleNodeModules, + ], + hasteImplModulePath: require.resolve('react-native/jest/hasteImpl'), }, serializer: { getModulesRunBeforeMainModule: () => [ @@ -62,10 +62,12 @@ const getDefaultConfig = (root: string) => { }, transformer: { babelTransformerPath: require.resolve('metro/src/reactNativeTransformer'), - assetRegistryPath: require.resolve('react-native/Libraries/Image/AssetRegistry') + assetRegistryPath: require.resolve( + 'react-native/Libraries/Image/AssetRegistry' + ), }, watchFolders: getWatchFolders(), - }); + }; }; export type ConfigOptionsT = { @@ -74,13 +76,13 @@ export type ConfigOptionsT = { resetCache?: boolean, watchFolders?: string[], sourceExts?: string[], - reporter?: any, + reporter?: any, // eslint-disable-line flowtype/no-weak-types config?: string, }; /** - * Overwrites Metro configuration with options. - * + * Overwrites Metro configuration with options. + * * This ensures that options are always taking precedence over other * configuration present. */ @@ -100,24 +102,21 @@ const overwriteWithOptions = (config: ConfigT, options: ConfigOptionsT) => { if (options.resetCache) { config.resetCache = options.resetCache; } - + if (options.watchFolders) { config.watchFolders = options.watchFolders; } - if ( - options.sourceExts - && options.sourceExts !== config.resolver.sourceExts - ) { + if (options.sourceExts && options.sourceExts !== config.resolver.sourceExts) { config.resolver.sourceExts = options.sourceExts.concat( - config.resolver.sourceExts, + config.resolver.sourceExts ); } }; /** * Loads Metro Config and applies `options` on top of the resolved config. - * + * * This allows the CLI to always overwrite the file settings. */ module.exports = async function load( @@ -125,11 +124,14 @@ module.exports = async function load( options?: ConfigOptionsT = {} ): Promise { const defaultConfig = getDefaultConfig(projectRoot); - - const config = await loadConfig({ - cwd: projectRoot, - config: options.config - }, defaultConfig); + + const config = await loadConfig( + { + cwd: projectRoot, + config: options.config, + }, + defaultConfig + ); if (options) { overwriteWithOptions(config, options); diff --git a/packages/local-cli/util/parseCommandLine.js b/packages/local-cli/util/parseCommandLine.js deleted file mode 100644 index e0d58308a..000000000 --- a/packages/local-cli/util/parseCommandLine.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * Wrapper on-top of `optimist` in order to properly support boolean flags - * and have a slightly less awkward API. - * - * Usage example: - * var argv = parseCommandLine([{ - * command: 'web', - * description: 'Run in a web browser instead of iOS', - * default: true - * }]) - * - * NOTE: This file is used internally at Facebook and not in `local-cli` itself. - * No changes should be made to this file without prior discussion with FB team. - * - * @format - */ - -'use strict'; - -var optimistModule = require('optimist'); - -function parseCommandLine(config, args) { - var optimist = new optimistModule(); - args = args || process.argv; - // optimist default API requires you to write the command name three time - // This is a small wrapper to accept an object instead - for (var i = 0; i < config.length; ++i) { - if (config[i].type === 'string') { - optimist.string(config[i].command); - } else { - optimist.boolean(config[i].command); - } - - optimist - .default(config[i].command, config[i].default) - .describe(config[i].command, config[i].description); - - if (config[i].required) { - optimist.demand(config[i].command); - } - } - var argv = optimist.parse(args); - - // optimist doesn't have support for --dev=false, instead it returns 'false' - for (var i = 0; i < config.length; ++i) { - var command = config[i].command; - if (argv[command] === undefined) { - argv[command] = config[i].default; - } - if (argv[command] === 'true') { - argv[command] = true; - } - if (argv[command] === 'false') { - argv[command] = false; - } - if (config[i].type === 'string') { - // According to https://github.com/substack/node-optimist#numbers, - // every argument that looks like a number should be converted to one. - var strValue = argv[command]; - var numValue = strValue ? Number(strValue) : undefined; - if (typeof numValue === 'number' && !isNaN(numValue)) { - argv[command] = numValue; - } - } - } - - // Show --help - if (argv.help || argv.h) { - optimist.showHelp(); - process.exit(); - } - - return argv; -} - -module.exports = parseCommandLine; diff --git a/packages/local-cli/util/walk.js b/packages/local-cli/util/walk.js index b7658dbb8..743c87e84 100644 --- a/packages/local-cli/util/walk.js +++ b/packages/local-cli/util/walk.js @@ -7,8 +7,6 @@ * @format */ -'use strict'; - const fs = require('fs'); const path = require('path'); @@ -17,10 +15,9 @@ function walk(current) { return [current]; } - const files = fs.readdirSync(current).map(child => { - child = path.join(current, child); - return walk(child); - }); + const files = fs + .readdirSync(current) + .map(child => walk(path.join(current, child))); return [].concat.apply([current], files); } diff --git a/packages/local-cli/util/yarn.js b/packages/local-cli/util/yarn.js index b5f73bee6..37ce21bbe 100644 --- a/packages/local-cli/util/yarn.js +++ b/packages/local-cli/util/yarn.js @@ -7,9 +7,7 @@ * @format */ -'use strict'; - -const execSync = require('child_process').execSync; +const { execSync } = require('child_process'); const fs = require('fs'); const path = require('path'); const semver = require('semver'); @@ -34,11 +32,10 @@ function getYarnVersionIfAvailable() { try { if (semver.gte(yarnVersion, '0.16.0')) { return yarnVersion; - } else { - return null; } + return null; } catch (error) { - console.error('Cannot parse yarn version: ' + yarnVersion); + console.error(`Cannot parse yarn version: ${yarnVersion}`); return null; } } @@ -55,6 +52,6 @@ function isGlobalCliUsingYarn(projectDir) { } module.exports = { - getYarnVersionIfAvailable: getYarnVersionIfAvailable, - isGlobalCliUsingYarn: isGlobalCliUsingYarn, + getYarnVersionIfAvailable, + isGlobalCliUsingYarn, }; diff --git a/yarn.lock b/yarn.lock index 9fb21203d..b9a20282e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -627,6 +627,13 @@ "@babel/helper-plugin-utils" "^7.0.0" "@babel/helper-regex" "^7.0.0" +"@babel/plugin-transform-strict-mode@^7.2.0": + version "7.2.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-strict-mode/-/plugin-transform-strict-mode-7.2.0.tgz#1aff4b99ce987b47152566a987e9469e47b96626" + integrity sha512-BJ5BF9+9zWTVCLe+nfLSfHUC0V/ly+ipMxVUdFjwlHFJ+Ue8WudbNh0ddzN0NnAQX5Kg0uk+DgRoGOJdnfNJgg== + dependencies: + "@babel/helper-plugin-utils" "^7.0.0" + "@babel/plugin-transform-template-literals@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.0.0.tgz#084f1952efe5b153ddae69eb8945f882c7a97c65" @@ -779,6 +786,22 @@ lodash "^4.17.10" to-fast-properties "^2.0.0" +"@callstack/eslint-config@^3.0.2": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@callstack/eslint-config/-/eslint-config-3.0.2.tgz#e40fcf73749aa8fb0b83bf243a2d6fdbc416fbd2" + integrity sha512-Frzn1E/egdqppp/2OLi76SMa6Z3yv4oRDjXDdYPCPtEJDyjzUh2lfTpURqziKbACUexTXMxAA+XMN0BSJ9RgUw== + dependencies: + babel-eslint "^10.0.1" + eslint-config-airbnb "^17.1.0" + eslint-config-prettier "^3.0.1" + eslint-plugin-flowtype "^3.0.0" + eslint-plugin-import "^2.14.0" + eslint-plugin-jest "^21.21.0" + eslint-plugin-jsx-a11y "^6.1.1" + eslint-plugin-prettier "^3.0.0" + eslint-plugin-react "^7.5.1" + prettier "^1.14.2" + abab@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.0.tgz#aba0ab4c5eee2d4c79d3487d85450fb2376ebb0f" @@ -927,6 +950,14 @@ argparse@^1.0.7: dependencies: sprintf-js "~1.0.2" +aria-query@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-3.0.0.tgz#65b3fcc1ca1155a8c9ae64d6eee297f15d5133cc" + integrity sha1-ZbP8wcoRVajJrmTW7uKX8V1RM8w= + dependencies: + ast-types-flow "0.0.7" + commander "^2.11.0" + arr-diff@^1.0.1: version "1.1.0" resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-1.1.0.tgz#687c32758163588fef7de7b36fabe495eb1a399a" @@ -964,6 +995,14 @@ array-filter@~0.0.0: version "0.0.1" resolved "https://registry.yarnpkg.com/array-filter/-/array-filter-0.0.1.tgz#7da8cf2e26628ed732803581fd21f67cacd2eeec" +array-includes@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.0.3.tgz#184b48f62d92d7452bb31b323165c7f8bd02266d" + integrity sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0= + dependencies: + define-properties "^1.1.2" + es-abstract "^1.7.0" + array-map@~0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/array-map/-/array-map-0.0.0.tgz#88a2bab73d1cf7bcd5c1b118a003f66f665fa662" @@ -1021,6 +1060,11 @@ assign-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" +ast-types-flow@0.0.7, ast-types-flow@^0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/ast-types-flow/-/ast-types-flow-0.0.7.tgz#f70b735c6bca1a5c9c22d982c3e39e7feba3bdad" + integrity sha1-9wtzXGvKGlycItmCw+Oef+ujva0= + astral-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" @@ -1055,6 +1099,13 @@ aws4@^1.8.0: version "1.8.0" resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f" +axobject-query@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-2.0.2.tgz#ea187abe5b9002b377f925d8bf7d1c561adf38f9" + integrity sha512-MCeek8ZH7hKyO1rWUbKNQBbl4l2eY0ntk7OGi+q0RlafrCnfPxC06WZA+uebCfmYp4mNU9jRBP1AhGyf8+W3ww== + dependencies: + ast-types-flow "0.0.7" + babel-code-frame@^6.26.0: version "6.26.0" resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" @@ -1091,6 +1142,18 @@ babel-core@^6.0.0, babel-core@^6.26.0: slash "^1.0.0" source-map "^0.5.7" +babel-eslint@^10.0.1: + version "10.0.1" + resolved "https://registry.yarnpkg.com/babel-eslint/-/babel-eslint-10.0.1.tgz#919681dc099614cd7d31d45c8908695092a1faed" + integrity sha512-z7OT1iNV+TjOwHNLLyJk+HN+YVWX+CLE6fPD2SymJZOZQBs+QIexFjhm4keGTm8MW9xr4EC9Q0PbaLB24V5GoQ== + dependencies: + "@babel/code-frame" "^7.0.0" + "@babel/parser" "^7.0.0" + "@babel/traverse" "^7.0.0" + "@babel/types" "^7.0.0" + eslint-scope "3.7.1" + eslint-visitor-keys "^1.0.0" + babel-generator@^6.18.0, babel-generator@^6.26.0: version "6.26.1" resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.1.tgz#1844408d3b8f0d35a404ea7ac180f087a601bd90" @@ -1523,7 +1586,7 @@ combined-stream@^1.0.6, combined-stream@~1.0.6: dependencies: delayed-stream "~1.0.0" -commander@^2.9.0: +commander@^2.11.0, commander@^2.9.0: version "2.19.0" resolved "https://registry.yarnpkg.com/commander/-/commander-2.19.0.tgz#f6198aa84e5b83c46054b94ddedbfed5ee9ff12a" @@ -1587,6 +1650,11 @@ console-control-strings@^1.0.0, console-control-strings@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" +contains-path@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" + integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo= + convert-source-map@^1.1.0, convert-source-map@^1.4.0, convert-source-map@^1.5.1: version "1.6.0" resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.6.0.tgz#51b537a8c43e0f04dec1993bffcdd504e758ac20" @@ -1659,6 +1727,11 @@ cycle@1.0.x: version "1.0.3" resolved "https://registry.yarnpkg.com/cycle/-/cycle-1.0.3.tgz#21e80b2be8580f98b468f379430662b046c34ad2" +damerau-levenshtein@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/damerau-levenshtein/-/damerau-levenshtein-1.0.4.tgz#03191c432cb6eea168bb77f3a55ffdccb8978514" + integrity sha1-AxkcQyy27qFou3fzpV/9zLiXhRQ= + dashdash@^1.12.0: version "1.14.1" resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" @@ -1798,6 +1871,14 @@ diff@^3.2.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" +doctrine@1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" + integrity sha1-N53Ocw9hZvds76TmcHoVmwLFpvo= + dependencies: + esutils "^2.0.2" + isarray "^1.0.0" + doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -1829,6 +1910,11 @@ electron-to-chromium@^1.3.82: version "1.3.83" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.83.tgz#74584eb0972bb6777811c5d68d988c722f5e6666" +emoji-regex@^6.5.1: + version "6.5.1" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-6.5.1.tgz#9baea929b155565c11ea41c6626eaa65cef992c2" + integrity sha512-PAHp6TxrCy7MGMFidro8uikr+zlJJKJ/Q6mm2ExZ7HwkyR9lSVFfE3kt36qcwa24BQL7y0G9axycGjK1A/0uNQ== + encodeurl@~1.0.1, encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" @@ -1862,7 +1948,7 @@ errorhandler@^1.5.0: accepts "~1.3.3" escape-html "~1.0.3" -es-abstract@^1.5.1: +es-abstract@^1.5.1, es-abstract@^1.6.1, es-abstract@^1.7.0: version "1.12.0" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.12.0.tgz#9dbbdd27c6856f0001421ca18782d786bf8a6165" dependencies: @@ -1899,6 +1985,120 @@ escodegen@^1.9.1: optionalDependencies: source-map "~0.6.1" +eslint-config-airbnb-base@^13.1.0: + version "13.1.0" + resolved "https://registry.yarnpkg.com/eslint-config-airbnb-base/-/eslint-config-airbnb-base-13.1.0.tgz#b5a1b480b80dfad16433d6c4ad84e6605052c05c" + integrity sha512-XWwQtf3U3zIoKO1BbHh6aUhJZQweOwSt4c2JrPDg9FP3Ltv3+YfEv7jIDB8275tVnO/qOHbfuYg3kzw6Je7uWw== + dependencies: + eslint-restricted-globals "^0.1.1" + object.assign "^4.1.0" + object.entries "^1.0.4" + +eslint-config-airbnb@^17.1.0: + version "17.1.0" + resolved "https://registry.yarnpkg.com/eslint-config-airbnb/-/eslint-config-airbnb-17.1.0.tgz#3964ed4bc198240315ff52030bf8636f42bc4732" + integrity sha512-R9jw28hFfEQnpPau01NO5K/JWMGLi6aymiF6RsnMURjTk+MqZKllCqGK/0tOvHkPi/NWSSOU2Ced/GX++YxLnw== + dependencies: + eslint-config-airbnb-base "^13.1.0" + object.assign "^4.1.0" + object.entries "^1.0.4" + +eslint-config-prettier@^3.0.1: + version "3.3.0" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-3.3.0.tgz#41afc8d3b852e757f06274ed6c44ca16f939a57d" + integrity sha512-Bc3bh5bAcKNvs3HOpSi6EfGA2IIp7EzWcg2tS4vP7stnXu/J1opihHDM7jI9JCIckyIDTgZLSWn7J3HY0j2JfA== + dependencies: + get-stdin "^6.0.0" + +eslint-import-resolver-node@^0.3.1: + version "0.3.2" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.2.tgz#58f15fb839b8d0576ca980413476aab2472db66a" + integrity sha512-sfmTqJfPSizWu4aymbPr4Iidp5yKm8yDkHp+Ir3YiTHiiDfxh69mOUsmiqW6RZ9zRXFaF64GtYmN7e+8GHBv6Q== + dependencies: + debug "^2.6.9" + resolve "^1.5.0" + +eslint-module-utils@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.2.0.tgz#b270362cd88b1a48ad308976ce7fa54e98411746" + integrity sha1-snA2LNiLGkitMIl2zn+lTphBF0Y= + dependencies: + debug "^2.6.8" + pkg-dir "^1.0.0" + +eslint-plugin-flowtype@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-flowtype/-/eslint-plugin-flowtype-3.2.0.tgz#824364ed5940a404b91326fdb5a313a2a74760df" + integrity sha512-baJmzngM6UKbEkJ5OY3aGw2zjXBt5L2QKZvTsOlXX7yHKIjNRrlJx2ods8Rng6EdqPR9rVNIQNYHpTs0qfn2qA== + dependencies: + lodash "^4.17.10" + +eslint-plugin-import@^2.14.0: + version "2.14.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.14.0.tgz#6b17626d2e3e6ad52cfce8807a845d15e22111a8" + integrity sha512-FpuRtniD/AY6sXByma2Wr0TXvXJ4nA/2/04VPlfpmUDPOpOY264x+ILiwnrk/k4RINgDAyFZByxqPUbSQ5YE7g== + dependencies: + contains-path "^0.1.0" + debug "^2.6.8" + doctrine "1.5.0" + eslint-import-resolver-node "^0.3.1" + eslint-module-utils "^2.2.0" + has "^1.0.1" + lodash "^4.17.4" + minimatch "^3.0.3" + read-pkg-up "^2.0.0" + resolve "^1.6.0" + +eslint-plugin-jest@^21.21.0: + version "21.27.2" + resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-21.27.2.tgz#2a795b7c3b5e707df48a953d651042bd01d7b0a8" + integrity sha512-0E4OIgBJVlAmf1KfYFtZ3gYxgUzC5Eb3Jzmrc9ikI1OY+/cM8Kh72Ti7KfpeHNeD3HJNf9SmEfmvQLIz44Hrhw== + +eslint-plugin-jsx-a11y@^6.1.1: + version "6.1.2" + resolved "https://registry.yarnpkg.com/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.1.2.tgz#69bca4890b36dcf0fe16dd2129d2d88b98f33f88" + integrity sha512-7gSSmwb3A+fQwtw0arguwMdOdzmKUgnUcbSNlo+GjKLAQFuC2EZxWqG9XHRI8VscBJD5a8raz3RuxQNFW+XJbw== + dependencies: + aria-query "^3.0.0" + array-includes "^3.0.3" + ast-types-flow "^0.0.7" + axobject-query "^2.0.1" + damerau-levenshtein "^1.0.4" + emoji-regex "^6.5.1" + has "^1.0.3" + jsx-ast-utils "^2.0.1" + +eslint-plugin-prettier@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.0.0.tgz#f6b823e065f8c36529918cdb766d7a0e975ec30c" + integrity sha512-4g11opzhqq/8+AMmo5Vc2Gn7z9alZ4JqrbZ+D4i8KlSyxeQhZHlmIrY8U9Akf514MoEhogPa87Jgkq87aZ2Ohw== + dependencies: + prettier-linter-helpers "^1.0.0" + +eslint-plugin-react@^7.5.1: + version "7.11.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.11.1.tgz#c01a7af6f17519457d6116aa94fc6d2ccad5443c" + integrity sha512-cVVyMadRyW7qsIUh3FHp3u6QHNhOgVrLQYdQEB1bPWBsgbNCHdFAeNMquBMCcZJu59eNthX053L70l7gRt4SCw== + dependencies: + array-includes "^3.0.3" + doctrine "^2.1.0" + has "^1.0.3" + jsx-ast-utils "^2.0.1" + prop-types "^15.6.2" + +eslint-restricted-globals@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/eslint-restricted-globals/-/eslint-restricted-globals-0.1.1.tgz#35f0d5cbc64c2e3ed62e93b4b1a7af05ba7ed4d7" + integrity sha1-NfDVy8ZMLj7WLpO0saevBbp+1Nc= + +eslint-scope@3.7.1: + version "3.7.1" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-3.7.1.tgz#3d63c3edfda02e06e01a452ad88caacc7cdcb6e8" + integrity sha1-PWPD7f2gLgbgGkUq2IyqzHzctug= + dependencies: + esrecurse "^4.1.0" + estraverse "^4.1.1" + eslint-scope@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.0.tgz#50bf3071e9338bcdc43331794a0cb533f0136172" @@ -1914,6 +2114,49 @@ eslint-visitor-keys@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d" +eslint@^5.10.0: + version "5.10.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-5.10.0.tgz#24adcbe92bf5eb1fc2d2f2b1eebe0c5e0713903a" + integrity sha512-HpqzC+BHULKlnPwWae9MaVZ5AXJKpkxCVXQHrFaRw3hbDj26V/9ArYM4Rr/SQ8pi6qUPLXSSXC4RBJlyq2Z2OQ== + dependencies: + "@babel/code-frame" "^7.0.0" + ajv "^6.5.3" + chalk "^2.1.0" + cross-spawn "^6.0.5" + debug "^4.0.1" + doctrine "^2.1.0" + eslint-scope "^4.0.0" + eslint-utils "^1.3.1" + eslint-visitor-keys "^1.0.0" + espree "^5.0.0" + esquery "^1.0.1" + esutils "^2.0.2" + file-entry-cache "^2.0.0" + functional-red-black-tree "^1.0.1" + glob "^7.1.2" + globals "^11.7.0" + ignore "^4.0.6" + imurmurhash "^0.1.4" + inquirer "^6.1.0" + js-yaml "^3.12.0" + json-stable-stringify-without-jsonify "^1.0.1" + levn "^0.3.0" + lodash "^4.17.5" + minimatch "^3.0.4" + mkdirp "^0.5.1" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.2" + pluralize "^7.0.0" + progress "^2.0.0" + regexpp "^2.0.1" + require-uncached "^1.0.3" + semver "^5.5.1" + strip-ansi "^4.0.0" + strip-json-comments "^2.0.1" + table "^5.0.2" + text-table "^0.2.0" + eslint@^5.7.0: version "5.8.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-5.8.0.tgz#91fbf24f6e0471e8fdf681a4d9dd1b2c9f28309b" @@ -1965,6 +2208,15 @@ espree@^4.0.0: acorn-jsx "^5.0.0" eslint-visitor-keys "^1.0.0" +espree@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-5.0.0.tgz#fc7f984b62b36a0f543b13fb9cd7b9f4a7f5b65c" + integrity sha512-1MpUfwsdS9MMoN7ZXqAr9e9UKdVHDcvrJpyx7mm1WuQlx/ygErEQBzgi5Nh5qBHIoYweprhtMkTCb9GhcAIcsA== + dependencies: + acorn "^6.0.2" + acorn-jsx "^5.0.0" + eslint-visitor-keys "^1.0.0" + esprima@^3.1.3: version "3.1.3" resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633" @@ -2174,6 +2426,11 @@ fast-deep-equal@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz#7b05218ddf9667bf7f370bf7fdb2cb15fdd0aa49" +fast-diff@^1.1.2: + version "1.2.0" + resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03" + integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w== + fast-json-stable-stringify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" @@ -2386,7 +2643,7 @@ fsevents@^1.2.3: nan "^2.9.2" node-pre-gyp "^0.10.0" -function-bind@^1.1.1: +function-bind@^1.1.0, function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" @@ -2421,6 +2678,11 @@ get-caller-file@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a" +get-stdin@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-6.0.0.tgz#9e09bf712b360ab9225e812048f71fde9c89657b" + integrity sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g== + get-stream@^3.0.0: version "3.0.0" resolved "http://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14" @@ -2569,7 +2831,7 @@ has-values@^1.0.0: is-number "^3.0.0" kind-of "^4.0.0" -has@^1.0.1: +has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" dependencies: @@ -2918,7 +3180,7 @@ is-windows@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" -isarray@1.0.0, isarray@~1.0.0: +isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" @@ -3474,6 +3736,13 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.10.0" +jsx-ast-utils@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.0.1.tgz#e801b1b39985e20fffc87b40e3748080e2dcac7f" + integrity sha1-6AGxs5mF4g//yHtA43SAgOLcrH8= + dependencies: + array-includes "^3.0.3" + kind-of@^1.1.0: version "1.1.0" resolved "http://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz#140a3d2d41a36d2efcfa9377b62c24f8495a5c44" @@ -4316,7 +4585,7 @@ object-copy@^0.1.0: define-property "^0.2.5" kind-of "^3.0.3" -object-keys@^1.0.12: +object-keys@^1.0.11, object-keys@^1.0.12: version "1.0.12" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.0.12.tgz#09c53855377575310cca62f55bb334abff7b3ed2" @@ -4326,6 +4595,26 @@ object-visit@^1.0.0: dependencies: isobject "^3.0.0" +object.assign@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" + integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== + dependencies: + define-properties "^1.1.2" + function-bind "^1.1.1" + has-symbols "^1.0.0" + object-keys "^1.0.11" + +object.entries@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.0.4.tgz#1bf9a4dd2288f5b33f3a993d257661f05d161a5f" + integrity sha1-G/mk3SKI9bM/Opk9JXZh8F0WGl8= + dependencies: + define-properties "^1.1.2" + es-abstract "^1.6.1" + function-bind "^1.1.0" + has "^1.0.1" + object.getownpropertydescriptors@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz#8758c846f5b407adab0f236e0986f14b051caa16" @@ -4527,7 +4816,7 @@ path-key@^2.0.0, path-key@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" -path-parse@^1.0.5: +path-parse@^1.0.5, path-parse@^1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" @@ -4577,6 +4866,13 @@ pirates@^4.0.0: dependencies: node-modules-regexp "^1.0.0" +pkg-dir@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" + integrity sha1-ektQio1bstYp1EcFb/TpyTFM89Q= + dependencies: + find-up "^1.0.0" + pkg-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-2.0.0.tgz#f6d5d1109e19d63edf428e0bd57e12777615334b" @@ -4643,6 +4939,18 @@ preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" +prettier-linter-helpers@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" + integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== + dependencies: + fast-diff "^1.1.2" + +prettier@^1.14.2: + version "1.15.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.15.3.tgz#1feaac5bdd181237b54dbe65d874e02a1472786a" + integrity sha512-gAU9AGAPMaKb3NNSUUuhhFAS7SCO4ALTN4nRIn6PJ075Qd28Yn2Ig2ahEJWdJwJmlEBTUfC7mMUSFy8MwsOCfg== + pretty-format@24.0.0-alpha.6, pretty-format@^24.0.0-alpha.6: version "24.0.0-alpha.6" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.0.0-alpha.6.tgz#25ad2fa46b342d6278bf241c5d2114d4376fbac1" @@ -4703,7 +5011,7 @@ prompts@^1.1.0: kleur "^2.0.1" sisteransi "^1.0.0" -prop-types@^15.5.8: +prop-types@^15.5.8, prop-types@^15.6.2: version "15.6.2" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.6.2.tgz#05d5ca77b4453e985d60fc7ff8c859094a497102" integrity sha512-3pboPvLiWD7dkI3qf3KbUe6hKFKa52w+AE0VCqECtf+QHAKgOL37tTaNCnuX1nAAQ4ZhyP+kYVKf8rLmJ/feDQ== @@ -5070,6 +5378,13 @@ resolve@^1.3.2, resolve@^1.5.0, resolve@^1.8.1: dependencies: path-parse "^1.0.5" +resolve@^1.6.0: + version "1.9.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.9.0.tgz#a14c6fdfa8f92a7df1d996cb7105fa744658ea06" + integrity sha512-TZNye00tI67lwYvzxCxHGjwTNlUV70io54/Ed4j6PscB8xVfuBJpRenI/o6dVk0cY0PYTY27AgCoGGxRnYuItQ== + dependencies: + path-parse "^1.0.6" + restore-cursor@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf"