diff --git a/packages/cli-hermes/src/profileHermes/index.ts b/packages/cli-hermes/src/profileHermes/index.ts index 6ab7da33b..47818a8fd 100644 --- a/packages/cli-hermes/src/profileHermes/index.ts +++ b/packages/cli-hermes/src/profileHermes/index.ts @@ -43,7 +43,7 @@ export default { func: profileHermes, options: [ { - name: '--filename [string]', + name: '--filename ', description: 'File name of the profile to be downloaded, eg. sampling-profiler-trace8593107139682635366.cpuprofile', }, @@ -53,7 +53,7 @@ export default { 'Pulls the original Hermes tracing profile without any transformation', }, { - name: '--sourcemap-path [string]', + name: '--sourcemap-path ', description: 'The local path to your source map file, eg. /tmp/sourcemap.json', }, @@ -62,9 +62,9 @@ export default { description: 'Generates the JS bundle and source map', }, { - name: '--port [number]', + name: '--port ', default: process.env.RCT_METRO_PORT || 8081, - parse: (val: number) => String(val), + parse: Number, }, ], examples: [ diff --git a/packages/cli-types/src/index.ts b/packages/cli-types/src/index.ts index e574a580b..93099a2d4 100644 --- a/packages/cli-types/src/index.ts +++ b/packages/cli-types/src/index.ts @@ -21,12 +21,12 @@ export type CommandFunction = ( args: Args, ) => Promise | void; -export type OptionValue = string | boolean | number; +export type OptionValue = string | boolean | number | OptionValue[]; export type CommandOption OptionValue> = { name: string; - description?: string; - parse?: (val: string) => any; + description: string; + parse?: (val: string) => OptionValue; default?: OptionValue | T; }; diff --git a/packages/cli/package.json b/packages/cli/package.json index a3f0b57ac..8fc7d813d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -35,7 +35,7 @@ "@react-native-community/cli-types": "^5.0.1-alpha.0", "chalk": "^3.0.0", "command-exists": "^1.2.8", - "commander": "^2.19.0", + "commander": "^6.2.0", "cosmiconfig": "^5.1.0", "deepmerge": "^3.2.0", "envinfo": "^7.7.2", diff --git a/packages/cli/src/commands/bundle/bundleCommandLineArgs.ts b/packages/cli/src/commands/bundle/bundleCommandLineArgs.ts index 51fc1ee7d..29ed72bd2 100644 --- a/packages/cli/src/commands/bundle/bundleCommandLineArgs.ts +++ b/packages/cli/src/commands/bundle/bundleCommandLineArgs.ts @@ -35,12 +35,12 @@ export default [ 'Path to the root JS file, either absolute or relative to JS root', }, { - name: '--platform [string]', + name: '--platform ', description: 'Either "ios" or "android"', default: 'ios', }, { - name: '--transformer [string]', + name: '--transformer ', description: 'Specify a custom transformer to be used', }, { @@ -63,26 +63,26 @@ export default [ 'File name where to store the resulting bundle, ex. /tmp/groups.bundle', }, { - name: '--bundle-encoding [string]', + name: '--bundle-encoding ', description: 'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).', default: 'utf8', }, { - name: '--max-workers [number]', + name: '--max-workers ', description: 'Specifies the maximum number of workers the worker-pool ' + 'will spawn for transforming files. This defaults to the number of the ' + 'cores available on your machine.', - parse: (workers: string) => Number(workers), + parse: Number, }, { - name: '--sourcemap-output [string]', + name: '--sourcemap-output ', description: 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map', }, { - name: '--sourcemap-sources-root [string]', + name: '--sourcemap-sources-root ', description: "Path to make sourcemap's sources entries relative to, ex. /root/dir", }, @@ -92,12 +92,12 @@ export default [ default: false, }, { - name: '--assets-dest [string]', + name: '--assets-dest ', description: 'Directory name where to store assets referenced in the bundle', }, { - name: '--unstable-transform-profile [string]', + name: '--unstable-transform-profile ', description: 'Experimental, transform JS for a specific JS engine. Currently supported: hermes, hermes-canary, default', }, @@ -113,7 +113,7 @@ export default [ default: false, }, { - name: '--config [string]', + name: '--config ', description: 'Path to the CLI configuration file', parse: (val: string) => path.resolve(val), }, diff --git a/packages/cli/src/commands/init/index.ts b/packages/cli/src/commands/init/index.ts index b3d254b5f..e5c766748 100644 --- a/packages/cli/src/commands/init/index.ts +++ b/packages/cli/src/commands/init/index.ts @@ -8,11 +8,11 @@ export default { 'Initialize a new React Native project named in a directory of the same name.', options: [ { - name: '--version [string]', + name: '--version ', description: 'Shortcut for `--template react-native@version`', }, { - name: '--template [string]', + name: '--template ', description: 'Uses a custom template. Valid arguments are the ones supported by `yarn add [package]` or `npm install [package]`, if you are using `--npm` option', }, @@ -21,11 +21,11 @@ export default { description: 'Forces using npm for initialization', }, { - name: '--directory [string]', + name: '--directory ', description: 'Uses a custom directory instead of ``.', }, { - name: '--title [string]', + name: '--title ', description: 'Uses a custom app title name for application', }, { diff --git a/packages/cli/src/commands/link/link.ts b/packages/cli/src/commands/link/link.ts index 7cd384549..350cbd546 100644 --- a/packages/cli/src/commands/link/link.ts +++ b/packages/cli/src/commands/link/link.ts @@ -93,14 +93,12 @@ export default { name: 'link [packageName]', options: [ { - name: '--platforms [list]', + name: '--platforms ', description: 'Scope linking to specified platforms', - parse: (val: string) => val.toLowerCase().split(','), }, { - name: '--all [boolean]', + name: '--all', description: 'Link all native modules and assets', - parse: (val: string) => val.toLowerCase().split(','), }, ], }; diff --git a/packages/cli/src/commands/start/start.ts b/packages/cli/src/commands/start/start.ts index e30bc44fa..dc0d6fe76 100644 --- a/packages/cli/src/commands/start/start.ts +++ b/packages/cli/src/commands/start/start.ts @@ -15,47 +15,44 @@ export default { description: 'starts the webserver', options: [ { - name: '--port [number]', - parse: (val: string) => Number(val), + name: '--port ', + default: process.env.RCT_METRO_PORT || 8081, + parse: Number, }, { - name: '--host [string]', + name: '--host ', default: '', }, { - name: '--projectRoot [path]', + name: '--projectRoot ', description: 'Path to a custom project root', parse: (val: string) => path.resolve(val), }, { - name: '--watchFolders [list]', + name: '--watchFolders ', description: 'Specify any additional folders to be added to the watch list', - parse: (val: string) => - val.split(',').map((folder: string) => path.resolve(folder)), }, { - name: '--assetPlugins [list]', + name: '--assetPlugins ', description: 'Specify any additional asset plugins to be used by the packager by full filepath', - parse: (val: string) => val.split(','), }, { - name: '--sourceExts [list]', + name: '--sourceExts ', description: 'Specify any additional source extensions to be used by the packager', - parse: (val: string) => val.split(','), }, { - name: '--max-workers [number]', + name: '--max-workers ', description: 'Specifies the maximum number of workers the worker-pool ' + 'will spawn for transforming files. This defaults to the number of the ' + 'cores available on your machine.', - parse: (workers: string) => Number(workers), + parse: Number, }, { - name: '--transformer [string]', + name: '--transformer ', description: 'Specify a custom transformer to be used', }, { @@ -63,7 +60,7 @@ export default { description: 'Removes cached files', }, { - name: '--custom-log-reporter-path, --customLogReporterPath [string]', + name: '--custom-log-reporter-path, --customLogReporterPath ', description: 'Path to a JavaScript file that exports a log reporter as a replacement for TerminalReporter', }, @@ -76,15 +73,15 @@ export default { description: 'Enables https connections to the server', }, { - name: '--key [path]', + name: '--key ', description: 'Path to custom SSL key', }, { - name: '--cert [path]', + name: '--cert ', description: 'Path to custom SSL cert', }, { - name: '--config [string]', + name: '--config ', description: 'Path to the CLI configuration file', parse: (val: string) => path.resolve(val), }, diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 127d51ac4..5ad811028 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -4,38 +4,75 @@ import commander from 'commander'; import leven from 'leven'; import path from 'path'; -import {Command, Config} from '@react-native-community/cli-types'; +import {Command, Config, DetachedCommand, OptionValue} from '@react-native-community/cli-types'; import {logger, CLIError} from '@react-native-community/cli-tools'; import {detachedCommands, projectCommands} from './commands'; import init from './commands/init/initCompat'; -import assertRequiredOptions from './tools/assertRequiredOptions'; import loadConfig from './tools/config'; const pkgJson = require('../package.json'); +/** + * Default `commander` settings + */ +commander + .storeOptionsAsProperties(false) + .name('react-native') + .usage(' [options]'); + +/** + * Setting `version` will make `--version` automatically available throughout the CLI + */ +commander.version(pkgJson.version); + +/** + * Verbose mode support + */ commander - .usage(' [options]') - .option('--version', 'Print CLI version') - .option('--verbose', 'Increase logging verbosity'); + .option('--verbose', 'Increase logging verbosity') + .on('option:verbose', () => { + logger.setVerbose(true); + }) + +/** + * Handler that gets executed when CLI is run with no command or an unknown + * command is passed + */ +commander.on('command:*', ([cmdName]) => { + if (!cmdName) { + commander.outputHelp(); + return; + } + + const suggestion = commander.commands + .map(cmd => cmd.name()) + .find(cmd => leven(cmd, cmdName) < cmd.length * 0.4); + + logger.error( + `Unrecognized command "${chalk.bold(cmdName)}". ${suggestion ? `Did you mean "${suggestion}"?` : ''}` + ); + + logger.info( + `Run ${chalk.bold( + '"react-native --help"', + )} to see a list of all available commands.`, + ); -commander.arguments('').action((cmd) => { - printUnknownCommand(cmd); process.exit(1); }); +/** + * Custom error handler for the CLI exceptions + */ const handleError = (err: Error) => { logger.enable(); - if (commander.verbose) { - logger.error(err.message); - } else { - // Some error messages (esp. custom ones) might have `.` at the end already. - const message = err.message.replace(/\.$/, ''); - logger.error(`${message}.`); - } + + logger.error(err.message); if (err.stack) { logger.log(err.stack); } + if (!commander.verbose) { logger.info( chalk.dim( @@ -45,133 +82,51 @@ const handleError = (err: Error) => { ), ); } - process.exit(1); -}; - -/** - * Custom printHelpInformation command inspired by internal Commander.js - * one modified to suit our needs - */ -function printHelpInformation( - this: commander.Command, - examples: Command['examples'], - pkg: Command['pkg'], -) { - let cmdName = this._name; - const argsList = (this._args as Array<{required: boolean; name: string}>) - .map((arg) => (arg.required ? `<${arg.name}>` : `[${arg.name}]`)) - .join(' '); - - if (this._alias) { - cmdName = `${cmdName}|${this._alias}`; - } - - const sourceInformation = pkg - ? [`${chalk.bold('Source:')} ${pkg.name}@${pkg.version}`, ''] - : []; - - let output = [ - chalk.bold(`react-native ${cmdName} ${argsList}`), - this._description ? `\n${this._description}\n` : '', - ...sourceInformation, - `${chalk.bold('Options:')}`, - this.optionHelp().replace(/^/gm, ' '), - ]; - - if (examples && examples.length > 0) { - const formattedUsage = examples - .map((example) => ` ${example.desc}: \n ${chalk.cyan(example.cmd)}`) - .join('\n\n'); - output = output.concat([chalk.bold('\nExample usage:'), formattedUsage]); - } - - return output.join('\n').concat('\n'); -} - -function printUnknownCommand(cmdName: string) { - const availableCommands = commander.commands.map((cmd: any) => cmd._name); - const suggestion = availableCommands.find((cmd: string) => { - return leven(cmd, cmdName) < cmd.length * 0.4; - }); - let errorMsg = `Unrecognized command "${chalk.bold(cmdName)}".`; - if (suggestion) { - errorMsg += ` Did you mean "${suggestion}"?`; - } - if (cmdName) { - logger.error(errorMsg); - logger.info( - `Run ${chalk.bold( - '"react-native --help"', - )} to see a list of all available commands.`, - ); - } else { - commander.outputHelp(); - } + process.exit(1); } /** - * Custom type assertion needed for the `makeCommand` conditional - * types to be properly resolved. - */ -const isDetachedCommand = ( - command: Command, -): command is Command => { - return command.detached === true; -}; - -/** - * Attaches a new command onto global `commander` instance. - * - * Note that this function takes additional argument of `Config` type in case - * passed `command` needs it for its execution. + * Registers a new command within Commander interface */ -function attachCommand( - command: Command, - ...rest: IsDetached extends false ? [Config] : [] -): void { - const options = command.options || []; - const cmd = commander - .command(command.name) - .action(async function handleAction( - this: commander.Command, - ...args: string[] - ) { - const passedOptions = this.opts(); - const argv = Array.from(args).slice(0, -1); - - try { - assertRequiredOptions(options, passedOptions); - if (isDetachedCommand(command)) { - await command.func(argv, passedOptions); - } else { - await command.func(argv, rest[0] as Config, passedOptions); - } - } catch (error) { - handleError(error); - } - }); +function registerCommand(...[command, config]: [DetachedCommand] | [Command, Config]): commander.Command { + const cmd = commander.command(command.name); if (command.description) { cmd.description(command.description); } - cmd.helpInformation = printHelpInformation.bind( - cmd, - command.examples, - command.pkg, - ); + /** + * Extend built-in help information by displaying examples, if defined + */ + cmd.on('--help', () => { + if (!command.examples) { + return; + } + + console.log('\nExample usage:'); + + for (const example of command.examples) { + console.log(` ${example.desc}: \n $ react-native ${example.cmd}\n`); + } + }); + /** + * Register options for every command + */ for (const opt of command.options || []) { - cmd.option( + cmd.option( opt.name, opt.description, - opt.parse || ((val: any) => val), + opt.parse || (val => val), typeof opt.default === 'function' - ? opt.default(rest[0] as Config) - : opt.default, + // @ts-ignore + ? opt.default(config) + : opt.default ); } + + return cmd; } async function run() { @@ -183,15 +138,13 @@ async function run() { } async function setupAndRun() { - // Commander is not available yet - // when we run `config`, we don't want to output anything to the console. We // expect it to return valid JSON if (process.argv.includes('config')) { logger.disable(); } - logger.setVerbose(process.argv.includes('--verbose')); + logger.enable(); // We only have a setup script for UNIX envs currently if (process.platform !== 'win32') { @@ -213,16 +166,28 @@ async function setupAndRun() { } for (const command of detachedCommands) { - attachCommand(command); + registerCommand(command) + .action(async (cmd, args) => { + try { + await command.func(args, cmd.opts()); + } catch (error) { + handleError(error); + } + }); } try { const config = loadConfig(); - logger.enable(); - for (const command of [...projectCommands, ...config.commands]) { - attachCommand(command, config); + registerCommand(command, config) + .action(async (cmd, args) => { + try { + await command.func(args, config, cmd.opts()); + } catch (error) { + handleError(error); + } + }); } } catch (error) { /** @@ -243,17 +208,6 @@ async function setupAndRun() { } commander.parse(process.argv); - - if (commander.rawArgs.length === 2) { - commander.outputHelp(); - } - - // We handle --version as a special case like this because both `commander` - // and `yargs` append it to every command and we don't want to do that. - // E.g. outside command `init` has --version flag and we want to preserve it. - if (commander.args.length === 0 && commander.rawArgs.includes('--version')) { - console.log(pkgJson.version); - } } const bin = require.resolve('./bin'); diff --git a/packages/cli/src/tools/assertRequiredOptions.ts b/packages/cli/src/tools/assertRequiredOptions.ts deleted file mode 100644 index 909851a0d..000000000 --- a/packages/cli/src/tools/assertRequiredOptions.ts +++ /dev/null @@ -1,38 +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 - */ -import {Option} from 'commander'; -import {camelCase} from 'lodash'; -import {CommandOption} from '@react-native-community/cli-types'; - -type PassedOptions = { - [key: string]: unknown; -}; - -// Commander.js has a 2 years old open issue to support <...> syntax -// for options. Until that gets merged, we run the checks manually -// https://github.com/tj/commander.js/issues/230 -export default function assertRequiredOptions( - options: CommandOption[], - passedOptions: PassedOptions, -) { - options.forEach((opt) => { - const option = new Option(opt.name); - - if (!option.required) { - return; - } - - const name = camelCase(option.long); - - if (!passedOptions[name]) { - // Provide commander.js like error message - throw new Error(`Option "${option.long}" is missing`); - } - }); -} diff --git a/packages/platform-android/src/commands/runAndroid/index.ts b/packages/platform-android/src/commands/runAndroid/index.ts index aba543a02..a0ac7d8da 100644 --- a/packages/platform-android/src/commands/runAndroid/index.ts +++ b/packages/platform-android/src/commands/runAndroid/index.ts @@ -318,39 +318,39 @@ export default { func: runAndroid, options: [ { - name: '--root [string]', + name: '--root ', description: '[DEPRECATED - root is discovered automatically] Override the root directory for the android build (which contains the android directory)', default: '', }, { - name: '--variant [string]', + name: '--variant ', description: "Specify your app's build variant", default: 'debug', }, { - name: '--appFolder [string]', + name: '--appFolder ', description: '[DEPRECATED – use "project.android.appName" in react-native.config.js] Specify a different application folder name for the android source. If not, we assume is "app"', }, { - name: '--appId [string]', + name: '--appId ', description: 'Specify an applicationId to launch after build. If not specified, `package` from AndroidManifest.xml will be used.', default: '', }, { - name: '--appIdSuffix [string]', + name: '--appIdSuffix ', description: 'Specify an applicationIdSuffix to launch after build.', default: '', }, { - name: '--main-activity [string]', + name: '--main-activity ', description: 'Name of the activity to start', default: 'MainActivity', }, { - name: '--deviceId [string]', + name: '--deviceId ', description: 'builds your app and starts it on a specific device/simulator with the ' + 'given device id (listed by running "adb devices" on the command line).', @@ -360,20 +360,19 @@ export default { description: 'Do not launch packager while building', }, { - name: '--port [number]', + name: '--port ', default: process.env.RCT_METRO_PORT || 8081, - parse: (val: string) => Number(val), + parse: Number, }, { - name: '--terminal [string]', + name: '--terminal ', description: 'Launches the Metro Bundler in a new window using the specified terminal path.', default: getDefaultUserTerminal(), }, { - name: '--tasks [list]', + name: '--tasks ', description: 'Run custom Gradle tasks. By default it\'s "installDebug"', - parse: (val: string) => val.split(','), }, { name: '--no-jetifier', diff --git a/packages/platform-ios/src/commands/runIOS/index.ts b/packages/platform-ios/src/commands/runIOS/index.ts index 45d1c23ad..68b88c5c4 100644 --- a/packages/platform-ios/src/commands/runIOS/index.ts +++ b/packages/platform-ios/src/commands/runIOS/index.ts @@ -557,35 +557,35 @@ export default { ], options: [ { - name: '--simulator [string]', + name: '--simulator ', description: 'Explicitly set simulator to use. Optionally include iOS version between ' + 'parenthesis at the end to match an exact version: "iPhone 6 (10.0)"', default: 'iPhone 12', }, { - name: '--configuration [string]', + name: '--configuration ', description: 'Explicitly set the scheme configuration to use', default: 'Debug', }, { - name: '--scheme [string]', + name: '--scheme ', description: 'Explicitly set Xcode scheme to use', }, { - name: '--project-path [string]', + name: '--project-path ', description: 'Path relative to project root where the Xcode project ' + '(.xcodeproj) lives.', default: 'ios', }, { - name: '--device [string]', + name: '--device ', description: 'Explicitly set device to use by name. The value is not required if you have a single device connected.', }, { - name: '--udid [string]', + name: '--udid ', description: 'Explicitly set device to use by udid', }, { @@ -599,10 +599,10 @@ export default { { name: '--port [number]', default: process.env.RCT_METRO_PORT || 8081, - parse: (val: string) => Number(val), + parse: Number, }, { - name: '--terminal [string]', + name: '--terminal ', description: 'Launches the Metro Bundler in a new window using the specified terminal path.', default: getDefaultUserTerminal, diff --git a/yarn.lock b/yarn.lock index ef088285a..1e47ac307 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3867,6 +3867,11 @@ commander@^2.11.0, commander@^2.19.0, commander@^2.20.0, commander@~2.20.3: resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== +commander@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-6.2.0.tgz#b990bfb8ac030aedc6d11bc04d1488ffef56db75" + integrity sha512-zP4jEKbe8SHzKJYQmq8Y9gYjtO/POJLgIdKgV7B9qNmABVFVc+ctqSX6iXh4mCpJfRBOabiZ2YKPg8ciDw6C+Q== + commander@~2.13.0: version "2.13.0" resolved "https://registry.yarnpkg.com/commander/-/commander-2.13.0.tgz#6964bca67685df7c1f1430c584f07d7597885b9c"