command.js
This file
Path
lib/command.js
1,810 lines · 56.1 KiB · JavaScript
Last changed by
Refactor classes into files (#1522)John Geebefore adoption08245cc
History of this fileTake it
Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1–1810why, one step back1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');56const { Argument, humanReadableArgName } = require('./argument.js');7const { CommanderError } = require('./error.js');8const { Help } = require('./help.js');9const { Option, splitOptionFlags } = require('./option.js');1011// @ts-check1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 this.commands = [];23 this.options = [];24 this.parent = null;25 this._allowUnknownOption = false;26 this._allowExcessArguments = true;27 this._args = [];28 this.rawArgs = null;29 this._scriptPath = null;30 this._name = name || '';31 this._optionValues = {};32 this._storeOptionsAsProperties = false;33 this._actionHandler = null;34 this._executableHandler = false;35 this._executableFile = null; // custom name for executable36 this._defaultCommandName = null;37 this._exitCallback = null;38 this._aliases = [];39 this._combineFlagAndOptionalValue = true;40 this._description = '';41 this._argsDescription = undefined; // legacy42 this._enablePositionalOptions = false;43 this._passThroughOptions = false;44 this._lifeCycleHooks = {}; // a hash of arrays4546 // see .configureOutput() for docs47 this._outputConfiguration = {48 writeOut: (str) => process.stdout.write(str),49 writeErr: (str) => process.stderr.write(str),50 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,51 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,52 outputError: (str, write) => write(str)53 };5455 this._hidden = false;56 this._hasHelpOption = true;57 this._helpFlags = '-h, --help';58 this._helpDescription = 'display help for command';59 this._helpShortFlag = '-h';60 this._helpLongFlag = '--help';61 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false62 this._helpCommandName = 'help';63 this._helpCommandnameAndArgs = 'help [command]';64 this._helpCommandDescription = 'display help for command';65 this._helpConfiguration = {};66 }6768 /**69 * Define a command.70 *71 * There are two styles of command: pay attention to where to put the description.72 *73 * Examples:74 *75 * // Command implemented using action handler (description is supplied separately to `.command`)76 * program77 * .command('clone <source> [destination]')78 * .description('clone a repository into a newly created directory')79 * .action((source, destination) => {80 * console.log('clone command called');81 * });82 *83 * // Command implemented using separate executable file (description is second parameter to `.command`)84 * program85 * .command('start <service>', 'start named service')86 * .command('stop [service]', 'stop named service, or all if no name supplied');87 *88 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`89 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)90 * @param {Object} [execOpts] - configuration options (for executable)91 * @return {Command} returns new command for action handler, or `this` for executable command92 */9394 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {95 let desc = actionOptsOrExecDesc;96 let opts = execOpts;97 if (typeof desc === 'object' && desc !== null) {98 opts = desc;99 desc = null;100 }101 opts = opts || {};102 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);103 const cmd = this.createCommand(name);104105 if (desc) {106 cmd.description(desc);107 cmd._executableHandler = true;108 }109 if (opts.isDefault) this._defaultCommandName = cmd._name;110111 cmd._outputConfiguration = this._outputConfiguration;112113 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden114 cmd._hasHelpOption = this._hasHelpOption;115 cmd._helpFlags = this._helpFlags;116 cmd._helpDescription = this._helpDescription;117 cmd._helpShortFlag = this._helpShortFlag;118 cmd._helpLongFlag = this._helpLongFlag;119 cmd._helpCommandName = this._helpCommandName;120 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;121 cmd._helpCommandDescription = this._helpCommandDescription;122 cmd._helpConfiguration = this._helpConfiguration;123 cmd._exitCallback = this._exitCallback;124 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;125 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;126 cmd._allowExcessArguments = this._allowExcessArguments;127 cmd._enablePositionalOptions = this._enablePositionalOptions;128129 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor130 if (args) cmd.arguments(args);131 this.commands.push(cmd);132 cmd.parent = this;133134 if (desc) return this;135 return cmd;136 };137138 /**139 * Factory routine to create a new unattached command.140 *141 * See .command() for creating an attached subcommand, which uses this routine to142 * create the command. You can override createCommand to customise subcommands.143 *144 * @param {string} [name]145 * @return {Command} new command146 */147148 createCommand(name) {149 return new Command(name);150 };151152 /**153 * You can customise the help with a subclass of Help by overriding createHelp,154 * or by overriding Help properties using configureHelp().155 *156 * @return {Help}157 */158159 createHelp() {160 return Object.assign(new Help(), this.configureHelp());161 };162163 /**164 * You can customise the help by overriding Help properties using configureHelp(),165 * or with a subclass of Help by overriding createHelp().166 *167 * @param {Object} [configuration] - configuration options168 * @return {Command|Object} `this` command for chaining, or stored configuration169 */170171 configureHelp(configuration) {172 if (configuration === undefined) return this._helpConfiguration;173174 this._helpConfiguration = configuration;175 return this;176 }177178 /**179 * The default output goes to stdout and stderr. You can customise this for special180 * applications. You can also customise the display of errors by overriding outputError.181 *182 * The configuration properties are all functions:183 *184 * // functions to change where being written, stdout and stderr185 * writeOut(str)186 * writeErr(str)187 * // matching functions to specify width for wrapping help188 * getOutHelpWidth()189 * getErrHelpWidth()190 * // functions based on what is being written out191 * outputError(str, write) // used for displaying errors, and not used for displaying help192 *193 * @param {Object} [configuration] - configuration options194 * @return {Command|Object} `this` command for chaining, or stored configuration195 */196197 configureOutput(configuration) {198 if (configuration === undefined) return this._outputConfiguration;199200 Object.assign(this._outputConfiguration, configuration);201 return this;202 }203204 /**205 * Add a prepared subcommand.206 *207 * See .command() for creating an attached subcommand which inherits settings from its parent.208 *209 * @param {Command} cmd - new subcommand210 * @param {Object} [opts] - configuration options211 * @return {Command} `this` command for chaining212 */213214 addCommand(cmd, opts) {215 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');216217 // To keep things simple, block automatic name generation for deeply nested executables.218 // Fail fast and detect when adding rather than later when parsing.219 function checkExplicitNames(commandArray) {220 commandArray.forEach((cmd) => {221 if (cmd._executableHandler && !cmd._executableFile) {222 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);223 }224 checkExplicitNames(cmd.commands);225 });226 }227 checkExplicitNames(cmd.commands);228229 opts = opts || {};230 if (opts.isDefault) this._defaultCommandName = cmd._name;231 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation232233 this.commands.push(cmd);234 cmd.parent = this;235 return this;236 };237238 /**239 * Factory routine to create a new unattached argument.240 *241 * See .argument() for creating an attached argument, which uses this routine to242 * create the argument. You can override createArgument to return a custom argument.243 *244 * @param {string} name245 * @param {string} [description]246 * @return {Argument} new argument247 */248249 createArgument(name, description) {250 return new Argument(name, description);251 };252253 /**254 * Define argument syntax for command.255 *256 * The default is that the argument is required, and you can explicitly257 * indicate this with <> around the name. Put [] around the name for an optional argument.258 *259 * @example260 *261 * program.argument('<input-file>');262 * program.argument('[output-file]');263 *264 * @param {string} name265 * @param {string} [description]266 * @param {Function|*} [fn] - custom argument processing function267 * @param {*} [defaultValue]268 * @return {Command} `this` command for chaining269 */270 argument(name, description, fn, defaultValue) {271 const argument = this.createArgument(name, description);272 if (typeof fn === 'function') {273 argument.default(defaultValue).argParser(fn);274 } else {275 argument.default(fn);276 }277 this.addArgument(argument);278 return this;279 }280281 /**282 * Define argument syntax for command, adding multiple at once (without descriptions).283 *284 * See also .argument().285 *286 * @example287 *288 * program.arguments('<cmd> [env]');289 *290 * @param {string} names291 * @return {Command} `this` command for chaining292 */293294 arguments(names) {295 names.split(/ +/).forEach((detail) => {296 this.argument(detail);297 });298 return this;299 };300301 /**302 * Define argument syntax for command, adding a prepared argument.303 *304 * @param {Argument} argument305 * @return {Command} `this` command for chaining306 */307 addArgument(argument) {308 const previousArgument = this._args.slice(-1)[0];309 if (previousArgument && previousArgument.variadic) {310 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);311 }312 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {313 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);314 }315 this._args.push(argument);316 return this;317 }318319 /**320 * Override default decision whether to add implicit help command.321 *322 * addHelpCommand() // force on323 * addHelpCommand(false); // force off324 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details325 *326 * @return {Command} `this` command for chaining327 */328329 addHelpCommand(enableOrNameAndArgs, description) {330 if (enableOrNameAndArgs === false) {331 this._addImplicitHelpCommand = false;332 } else {333 this._addImplicitHelpCommand = true;334 if (typeof enableOrNameAndArgs === 'string') {335 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];336 this._helpCommandnameAndArgs = enableOrNameAndArgs;337 }338 this._helpCommandDescription = description || this._helpCommandDescription;339 }340 return this;341 };342343 /**344 * @return {boolean}345 * @api private346 */347348 _hasImplicitHelpCommand() {349 if (this._addImplicitHelpCommand === undefined) {350 return this.commands.length && !this._actionHandler && !this._findCommand('help');351 }352 return this._addImplicitHelpCommand;353 };354355 /**356 * Add hook for life cycle event.357 *358 * @param {string} event359 * @param {Function} listener360 * @return {Command} `this` command for chaining361 */362363 hook(event, listener) {364 const allowedValues = ['preAction', 'postAction'];365 if (!allowedValues.includes(event)) {366 throw new Error(`Unexpected value for event passed to hook : '${event}'.367Expecting one of '${allowedValues.join("', '")}'`);368 }369 if (this._lifeCycleHooks[event]) {370 this._lifeCycleHooks[event].push(listener);371 } else {372 this._lifeCycleHooks[event] = [listener];373 }374 return this;375 }376377 /**378 * Register callback to use as replacement for calling process.exit.379 *380 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing381 * @return {Command} `this` command for chaining382 */383384 exitOverride(fn) {385 if (fn) {386 this._exitCallback = fn;387 } else {388 this._exitCallback = (err) => {389 if (err.code !== 'commander.executeSubCommandAsync') {390 throw err;391 } else {392 // Async callback from spawn events, not useful to throw.393 }394 };395 }396 return this;397 };398399 /**400 * Call process.exit, and _exitCallback if defined.401 *402 * @param {number} exitCode exit code for using with process.exit403 * @param {string} code an id string representing the error404 * @param {string} message human-readable description of the error405 * @return never406 * @api private407 */408409 _exit(exitCode, code, message) {410 if (this._exitCallback) {411 this._exitCallback(new CommanderError(exitCode, code, message));412 // Expecting this line is not reached.413 }414 process.exit(exitCode);415 };416417 /**418 * Register callback `fn` for the command.419 *420 * Examples:421 *422 * program423 * .command('help')424 * .description('display verbose help')425 * .action(function() {426 * // output help here427 * });428 *429 * @param {Function} fn430 * @return {Command} `this` command for chaining431 */432433 action(fn) {434 const listener = (args) => {435 // The .action callback takes an extra parameter which is the command or options.436 const expectedArgsCount = this._args.length;437 const actionArgs = args.slice(0, expectedArgsCount);438 if (this._storeOptionsAsProperties) {439 actionArgs[expectedArgsCount] = this; // backwards compatible "options"440 } else {441 actionArgs[expectedArgsCount] = this.opts();442 }443 actionArgs.push(this);444445 return fn.apply(this, actionArgs);446 };447 this._actionHandler = listener;448 return this;449 };450451 /**452 * Factory routine to create a new unattached option.453 *454 * See .option() for creating an attached option, which uses this routine to455 * create the option. You can override createOption to return a custom option.456 *457 * @param {string} flags458 * @param {string} [description]459 * @return {Option} new option460 */461462 createOption(flags, description) {463 return new Option(flags, description);464 };465466 /**467 * Add an option.468 *469 * @param {Option} option470 * @return {Command} `this` command for chaining471 */472 addOption(option) {473 const oname = option.name();474 const name = option.attributeName();475476 let defaultValue = option.defaultValue;477478 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value479 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {480 // when --no-foo we make sure default is true, unless a --foo option is already defined481 if (option.negate) {482 const positiveLongFlag = option.long.replace(/^--no-/, '--');483 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;484 }485 // preassign only if we have a default486 if (defaultValue !== undefined) {487 this.setOptionValue(name, defaultValue);488 }489 }490491 // register the option492 this.options.push(option);493494 // when it's passed assign the value495 // and conditionally invoke the callback496 this.on('option:' + oname, (val) => {497 const oldValue = this.getOptionValue(name);498499 // custom processing500 if (val !== null && option.parseArg) {501 try {502 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);503 } catch (err) {504 if (err.code === 'commander.invalidArgument') {505 const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;506 this._displayError(err.exitCode, err.code, message);507 }508 throw err;509 }510 } else if (val !== null && option.variadic) {511 val = option._concatValue(val, oldValue);512 }513514 // unassigned or boolean value515 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {516 // if no value, negate false, and we have a default, then use it!517 if (val == null) {518 this.setOptionValue(name, option.negate519 ? false520 : defaultValue || true);521 } else {522 this.setOptionValue(name, val);523 }524 } else if (val !== null) {525 // reassign526 this.setOptionValue(name, option.negate ? false : val);527 }528 });529530 return this;531 }532533 /**534 * Internal implementation shared by .option() and .requiredOption()535 *536 * @api private537 */538 _optionEx(config, flags, description, fn, defaultValue) {539 const option = this.createOption(flags, description);540 option.makeOptionMandatory(!!config.mandatory);541 if (typeof fn === 'function') {542 option.default(defaultValue).argParser(fn);543 } else if (fn instanceof RegExp) {544 // deprecated545 const regex = fn;546 fn = (val, def) => {547 const m = regex.exec(val);548 return m ? m[0] : def;549 };550 option.default(defaultValue).argParser(fn);551 } else {552 option.default(fn);553 }554555 return this.addOption(option);556 }557558 /**559 * Define option with `flags`, `description` and optional560 * coercion `fn`.561 *562 * The `flags` string contains the short and/or long flags,563 * separated by comma, a pipe or space. The following are all valid564 * all will output this way when `--help` is used.565 *566 * "-p, --pepper"567 * "-p|--pepper"568 * "-p --pepper"569 *570 * Examples:571 *572 * // simple boolean defaulting to undefined573 * program.option('-p, --pepper', 'add pepper');574 *575 * program.pepper576 * // => undefined577 *578 * --pepper579 * program.pepper580 * // => true581 *582 * // simple boolean defaulting to true (unless non-negated option is also defined)583 * program.option('-C, --no-cheese', 'remove cheese');584 *585 * program.cheese586 * // => true587 *588 * --no-cheese589 * program.cheese590 * // => false591 *592 * // required argument593 * program.option('-C, --chdir <path>', 'change the working directory');594 *595 * --chdir /tmp596 * program.chdir597 * // => "/tmp"598 *599 * // optional argument600 * program.option('-c, --cheese [type]', 'add cheese [marble]');601 *602 * @param {string} flags603 * @param {string} [description]604 * @param {Function|*} [fn] - custom option processing function or default value605 * @param {*} [defaultValue]606 * @return {Command} `this` command for chaining607 */608609 option(flags, description, fn, defaultValue) {610 return this._optionEx({}, flags, description, fn, defaultValue);611 };612613 /**614 * Add a required option which must have a value after parsing. This usually means615 * the option must be specified on the command line. (Otherwise the same as .option().)616 *617 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.618 *619 * @param {string} flags620 * @param {string} [description]621 * @param {Function|*} [fn] - custom option processing function or default value622 * @param {*} [defaultValue]623 * @return {Command} `this` command for chaining624 */625626 requiredOption(flags, description, fn, defaultValue) {627 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);628 };629630 /**631 * Alter parsing of short flags with optional values.632 *633 * Examples:634 *635 * // for `.option('-f,--flag [value]'):636 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour637 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`638 *639 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.640 */641 combineFlagAndOptionalValue(combine = true) {642 this._combineFlagAndOptionalValue = !!combine;643 return this;644 };645646 /**647 * Allow unknown options on the command line.648 *649 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown650 * for unknown options.651 */652 allowUnknownOption(allowUnknown = true) {653 this._allowUnknownOption = !!allowUnknown;654 return this;655 };656657 /**658 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.659 *660 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown661 * for excess arguments.662 */663 allowExcessArguments(allowExcess = true) {664 this._allowExcessArguments = !!allowExcess;665 return this;666 };667668 /**669 * Enable positional options. Positional means global options are specified before subcommands which lets670 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.671 * The default behaviour is non-positional and global options may appear anywhere on the command line.672 *673 * @param {Boolean} [positional=true]674 */675 enablePositionalOptions(positional = true) {676 this._enablePositionalOptions = !!positional;677 return this;678 };679680 /**681 * Pass through options that come after command-arguments rather than treat them as command-options,682 * so actual command-options come before command-arguments. Turning this on for a subcommand requires683 * positional options to have been enabled on the program (parent commands).684 * The default behaviour is non-positional and options may appear before or after command-arguments.685 *686 * @param {Boolean} [passThrough=true]687 * for unknown options.688 */689 passThroughOptions(passThrough = true) {690 this._passThroughOptions = !!passThrough;691 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {692 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');693 }694 return this;695 };696697 /**698 * Whether to store option values as properties on command object,699 * or store separately (specify false). In both cases the option values can be accessed using .opts().700 *701 * @param {boolean} [storeAsProperties=true]702 * @return {Command} `this` command for chaining703 */704705 storeOptionsAsProperties(storeAsProperties = true) {706 this._storeOptionsAsProperties = !!storeAsProperties;707 if (this.options.length) {708 throw new Error('call .storeOptionsAsProperties() before adding options');709 }710 return this;711 };712713 /**714 * Retrieve option value.715 *716 * @param {string} key717 * @return {Object} value718 */719720 getOptionValue(key) {721 if (this._storeOptionsAsProperties) {722 return this[key];723 }724 return this._optionValues[key];725 };726727 /**728 * Store option value.729 *730 * @param {string} key731 * @param {Object} value732 * @return {Command} `this` command for chaining733 */734735 setOptionValue(key, value) {736 if (this._storeOptionsAsProperties) {737 this[key] = value;738 } else {739 this._optionValues[key] = value;740 }741 return this;742 };743744 /**745 * Get user arguments implied or explicit arguments.746 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.747 *748 * @api private749 */750751 _prepareUserArgs(argv, parseOptions) {752 if (argv !== undefined && !Array.isArray(argv)) {753 throw new Error('first parameter to parse must be array or undefined');754 }755 parseOptions = parseOptions || {};756757 // Default to using process.argv758 if (argv === undefined) {759 argv = process.argv;760 // @ts-ignore: unknown property761 if (process.versions && process.versions.electron) {762 parseOptions.from = 'electron';763 }764 }765 this.rawArgs = argv.slice();766767 // make it a little easier for callers by supporting various argv conventions768 let userArgs;769 switch (parseOptions.from) {770 case undefined:771 case 'node':772 this._scriptPath = argv[1];773 userArgs = argv.slice(2);774 break;775 case 'electron':776 // @ts-ignore: unknown property777 if (process.defaultApp) {778 this._scriptPath = argv[1];779 userArgs = argv.slice(2);780 } else {781 userArgs = argv.slice(1);782 }783 break;784 case 'user':785 userArgs = argv.slice(0);786 break;787 default:788 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);789 }790 if (!this._scriptPath && require.main) {791 this._scriptPath = require.main.filename;792 }793794 // Guess name, used in usage in help.795 this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));796797 return userArgs;798 }799800 /**801 * Parse `argv`, setting options and invoking commands when defined.802 *803 * The default expectation is that the arguments are from node and have the application as argv[0]804 * and the script being run in argv[1], with user parameters after that.805 *806 * Examples:807 *808 * program.parse(process.argv);809 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions810 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]811 *812 * @param {string[]} [argv] - optional, defaults to process.argv813 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron814 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'815 * @return {Command} `this` command for chaining816 */817818 parse(argv, parseOptions) {819 const userArgs = this._prepareUserArgs(argv, parseOptions);820 this._parseCommand([], userArgs);821822 return this;823 };824825 /**826 * Parse `argv`, setting options and invoking commands when defined.827 *828 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.829 *830 * The default expectation is that the arguments are from node and have the application as argv[0]831 * and the script being run in argv[1], with user parameters after that.832 *833 * Examples:834 *835 * await program.parseAsync(process.argv);836 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions837 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]838 *839 * @param {string[]} [argv]840 * @param {Object} [parseOptions]841 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'842 * @return {Promise}843 */844845 async parseAsync(argv, parseOptions) {846 const userArgs = this._prepareUserArgs(argv, parseOptions);847 await this._parseCommand([], userArgs);848849 return this;850 };851852 /**853 * Execute a sub-command executable.854 *855 * @api private856 */857858 _executeSubCommand(subcommand, args) {859 args = args.slice();860 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.861 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];862863 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.864 this._checkForMissingMandatoryOptions();865866 // Want the entry script as the reference for command name and directory for searching for other files.867 let scriptPath = this._scriptPath;868 // Fallback in case not set, due to how Command created or called.869 if (!scriptPath && require.main) {870 scriptPath = require.main.filename;871 }872873 let baseDir;874 try {875 const resolvedLink = fs.realpathSync(scriptPath);876 baseDir = path.dirname(resolvedLink);877 } catch (e) {878 baseDir = '.'; // dummy, probably not going to find executable!879 }880881 // name of the subcommand, like `pm-install`882 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;883 if (subcommand._executableFile) {884 bin = subcommand._executableFile;885 }886887 const localBin = path.join(baseDir, bin);888 if (fs.existsSync(localBin)) {889 // prefer local `./<bin>` to bin in the $PATH890 bin = localBin;891 } else {892 // Look for source files.893 sourceExt.forEach((ext) => {894 if (fs.existsSync(`${localBin}${ext}`)) {895 bin = `${localBin}${ext}`;896 }897 });898 }899 launchWithNode = sourceExt.includes(path.extname(bin));900901 let proc;902 if (process.platform !== 'win32') {903 if (launchWithNode) {904 args.unshift(bin);905 // add executable arguments to spawn906 args = incrementNodeInspectorPort(process.execArgv).concat(args);907908 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });909 } else {910 proc = childProcess.spawn(bin, args, { stdio: 'inherit' });911 }912 } else {913 args.unshift(bin);914 // add executable arguments to spawn915 args = incrementNodeInspectorPort(process.execArgv).concat(args);916 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });917 }918919 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];920 signals.forEach((signal) => {921 // @ts-ignore922 process.on(signal, () => {923 if (proc.killed === false && proc.exitCode === null) {924 proc.kill(signal);925 }926 });927 });928929 // By default terminate process when spawned process terminates.930 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!931 const exitCallback = this._exitCallback;932 if (!exitCallback) {933 proc.on('close', process.exit.bind(process));934 } else {935 proc.on('close', () => {936 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));937 });938 }939 proc.on('error', (err) => {940 // @ts-ignore941 if (err.code === 'ENOENT') {942 const executableMissing = `'${bin}' does not exist943 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead944 - if the default executable name is not suitable, use the executableFile option to supply a custom name`;945 throw new Error(executableMissing);946 // @ts-ignore947 } else if (err.code === 'EACCES') {948 throw new Error(`'${bin}' not executable`);949 }950 if (!exitCallback) {951 process.exit(1);952 } else {953 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');954 wrappedError.nestedError = err;955 exitCallback(wrappedError);956 }957 });958959 // Store the reference to the child process960 this.runningCommand = proc;961 };962963 /**964 * @api private965 */966967 _dispatchSubcommand(commandName, operands, unknown) {968 const subCommand = this._findCommand(commandName);969 if (!subCommand) this.help({ error: true });970971 if (subCommand._executableHandler) {972 this._executeSubCommand(subCommand, operands.concat(unknown));973 } else {974 return subCommand._parseCommand(operands, unknown);975 }976 };977978 /**979 * Package arguments (this.args) for passing to action handler based980 * on declared arguments (this._args).981 *982 * @api private983 */984985 _getActionArguments() {986 const myParseArg = (argument, value, previous) => {987 // Extra processing for nice error message on parsing failure.988 let parsedValue = value;989 if (value !== null && argument.parseArg) {990 try {991 parsedValue = argument.parseArg(value, previous);992 } catch (err) {993 if (err.code === 'commander.invalidArgument') {994 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;995 this._displayError(err.exitCode, err.code, message);996 }997 throw err;998 }999 }1000 return parsedValue;1001 };10021003 const actionArgs = [];1004 this._args.forEach((declaredArg, index) => {1005 let value = declaredArg.defaultValue;1006 if (declaredArg.variadic) {1007 // Collect together remaining arguments for passing together as an array.1008 if (index < this.args.length) {1009 value = this.args.slice(index);1010 if (declaredArg.parseArg) {1011 value = value.reduce((processed, v) => {1012 return myParseArg(declaredArg, v, processed);1013 }, declaredArg.defaultValue);1014 }1015 } else if (value === undefined) {1016 value = [];1017 }1018 } else if (index < this.args.length) {1019 value = this.args[index];1020 if (declaredArg.parseArg) {1021 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1022 }1023 }1024 actionArgs[index] = value;1025 });1026 return actionArgs;1027 }10281029 /**1030 * Once we have a promise we chain, but call synchronously until then.1031 *1032 * @param {Promise|undefined} promise1033 * @param {Function} fn1034 * @return {Promise|undefined}1035 */10361037 _chainOrCall(promise, fn) {1038 // thenable1039 if (promise && promise.then && typeof promise.then === 'function') {1040 // already have a promise, chain callback1041 return promise.then(() => fn());1042 }1043 // callback might return a promise1044 return fn();1045 }10461047 /**1048 *1049 * @param {Promise|undefined} promise1050 * @param {string} event1051 * @return {Promise|undefined}1052 * @api private1053 */10541055 _chainOrCallHooks(promise, event) {1056 let result = promise;1057 const hooks = [];1058 getCommandAndParents(this)1059 .reverse()1060 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1061 .forEach(hookedCommand => {1062 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1063 hooks.push({ hookedCommand, callback });1064 });1065 });1066 if (event === 'postAction') {1067 hooks.reverse();1068 }10691070 hooks.forEach((hookDetail) => {1071 result = this._chainOrCall(result, () => {1072 return hookDetail.callback(hookDetail.hookedCommand, this);1073 });1074 });1075 return result;1076 }10771078 /**1079 * Process arguments in context of this command.1080 * Returns action result, in case it is a promise.1081 *1082 * @api private1083 */10841085 _parseCommand(operands, unknown) {1086 const parsed = this.parseOptions(unknown);1087 operands = operands.concat(parsed.operands);1088 unknown = parsed.unknown;1089 this.args = operands.concat(unknown);10901091 if (operands && this._findCommand(operands[0])) {1092 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1093 }1094 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1095 if (operands.length === 1) {1096 this.help();1097 }1098 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1099 }1100 if (this._defaultCommandName) {1101 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1102 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1103 }1104 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1105 // probably missing subcommand and no handler, user needs help (and exit)1106 this.help({ error: true });1107 }11081109 outputHelpIfRequested(this, parsed.unknown);1110 this._checkForMissingMandatoryOptions();11111112 // We do not always call this check to avoid masking a "better" error, like unknown command.1113 const checkForUnknownOptions = () => {1114 if (parsed.unknown.length > 0) {1115 this.unknownOption(parsed.unknown[0]);1116 }1117 };1118 const checkNumberOfArguments = () => {1119 // too few1120 this._args.forEach((arg, i) => {1121 if (arg.required && this.args[i] == null) {1122 this.missingArgument(arg.name());1123 }1124 });1125 // too many1126 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1127 return;1128 }1129 if (this.args.length > this._args.length) {1130 this._excessArguments(this.args);1131 }1132 };11331134 const commandEvent = `command:${this.name()}`;1135 if (this._actionHandler) {1136 checkForUnknownOptions();1137 checkNumberOfArguments();11381139 let actionResult;1140 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1141 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this._getActionArguments()));1142 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1143 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1144 return actionResult;1145 }1146 if (this.parent && this.parent.listenerCount(commandEvent)) {1147 checkForUnknownOptions();1148 checkNumberOfArguments();1149 this.parent.emit(commandEvent, operands, unknown); // legacy1150 } else if (operands.length) {1151 if (this._findCommand('*')) { // legacy default command1152 return this._dispatchSubcommand('*', operands, unknown);1153 }1154 if (this.listenerCount('command:*')) {1155 // skip option check, emit event for possible misspelling suggestion1156 this.emit('command:*', operands, unknown);1157 } else if (this.commands.length) {1158 this.unknownCommand();1159 } else {1160 checkForUnknownOptions();1161 checkNumberOfArguments();1162 }1163 } else if (this.commands.length) {1164 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1165 this.help({ error: true });1166 } else {1167 checkForUnknownOptions();1168 checkNumberOfArguments();1169 // fall through for caller to handle after calling .parse()1170 }1171 };11721173 /**1174 * Find matching command.1175 *1176 * @api private1177 */1178 _findCommand(name) {1179 if (!name) return undefined;1180 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1181 };11821183 /**1184 * Return an option matching `arg` if any.1185 *1186 * @param {string} arg1187 * @return {Option}1188 * @api private1189 */11901191 _findOption(arg) {1192 return this.options.find(option => option.is(arg));1193 };11941195 /**1196 * Display an error message if a mandatory option does not have a value.1197 * Lazy calling after checking for help flags from leaf subcommand.1198 *1199 * @api private1200 */12011202 _checkForMissingMandatoryOptions() {1203 // Walk up hierarchy so can call in subcommand after checking for displaying help.1204 for (let cmd = this; cmd; cmd = cmd.parent) {1205 cmd.options.forEach((anOption) => {1206 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1207 cmd.missingMandatoryOptionValue(anOption);1208 }1209 });1210 }1211 };12121213 /**1214 * Parse options from `argv` removing known options,1215 * and return argv split into operands and unknown arguments.1216 *1217 * Examples:1218 *1219 * argv => operands, unknown1220 * --known kkk op => [op], []1221 * op --known kkk => [op], []1222 * sub --unknown uuu op => [sub], [--unknown uuu op]1223 * sub -- --unknown uuu op => [sub --unknown uuu op], []1224 *1225 * @param {String[]} argv1226 * @return {{operands: String[], unknown: String[]}}1227 */12281229 parseOptions(argv) {1230 const operands = []; // operands, not options or values1231 const unknown = []; // first unknown option and remaining unknown args1232 let dest = operands;1233 const args = argv.slice();12341235 function maybeOption(arg) {1236 return arg.length > 1 && arg[0] === '-';1237 }12381239 // parse options1240 let activeVariadicOption = null;1241 while (args.length) {1242 const arg = args.shift();12431244 // literal1245 if (arg === '--') {1246 if (dest === unknown) dest.push(arg);1247 dest.push(...args);1248 break;1249 }12501251 if (activeVariadicOption && !maybeOption(arg)) {1252 this.emit(`option:${activeVariadicOption.name()}`, arg);1253 continue;1254 }1255 activeVariadicOption = null;12561257 if (maybeOption(arg)) {1258 const option = this._findOption(arg);1259 // recognised option, call listener to assign value with possible custom processing1260 if (option) {1261 if (option.required) {1262 const value = args.shift();1263 if (value === undefined) this.optionMissingArgument(option);1264 this.emit(`option:${option.name()}`, value);1265 } else if (option.optional) {1266 let value = null;1267 // historical behaviour is optional value is following arg unless an option1268 if (args.length > 0 && !maybeOption(args[0])) {1269 value = args.shift();1270 }1271 this.emit(`option:${option.name()}`, value);1272 } else { // boolean flag1273 this.emit(`option:${option.name()}`);1274 }1275 activeVariadicOption = option.variadic ? option : null;1276 continue;1277 }1278 }12791280 // Look for combo options following single dash, eat first one if known.1281 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1282 const option = this._findOption(`-${arg[1]}`);1283 if (option) {1284 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1285 // option with value following in same argument1286 this.emit(`option:${option.name()}`, arg.slice(2));1287 } else {1288 // boolean option, emit and put back remainder of arg for further processing1289 this.emit(`option:${option.name()}`);1290 args.unshift(`-${arg.slice(2)}`);1291 }1292 continue;1293 }1294 }12951296 // Look for known long flag with value, like --foo=bar1297 if (/^--[^=]+=/.test(arg)) {1298 const index = arg.indexOf('=');1299 const option = this._findOption(arg.slice(0, index));1300 if (option && (option.required || option.optional)) {1301 this.emit(`option:${option.name()}`, arg.slice(index + 1));1302 continue;1303 }1304 }13051306 // Not a recognised option by this command.1307 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.13081309 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1310 if (maybeOption(arg)) {1311 dest = unknown;1312 }13131314 // If using positionalOptions, stop processing our options at subcommand.1315 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1316 if (this._findCommand(arg)) {1317 operands.push(arg);1318 if (args.length > 0) unknown.push(...args);1319 break;1320 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1321 operands.push(arg);1322 if (args.length > 0) operands.push(...args);1323 break;1324 } else if (this._defaultCommandName) {1325 unknown.push(arg);1326 if (args.length > 0) unknown.push(...args);1327 break;1328 }1329 }13301331 // If using passThroughOptions, stop processing options at first command-argument.1332 if (this._passThroughOptions) {1333 dest.push(arg);1334 if (args.length > 0) dest.push(...args);1335 break;1336 }13371338 // add arg1339 dest.push(arg);1340 }13411342 return { operands, unknown };1343 };13441345 /**1346 * Return an object containing options as key-value pairs1347 *1348 * @return {Object}1349 */1350 opts() {1351 if (this._storeOptionsAsProperties) {1352 // Preserve original behaviour so backwards compatible when still using properties1353 const result = {};1354 const len = this.options.length;13551356 for (let i = 0; i < len; i++) {1357 const key = this.options[i].attributeName();1358 result[key] = key === this._versionOptionName ? this._version : this[key];1359 }1360 return result;1361 }13621363 return this._optionValues;1364 };13651366 /**1367 * Internal bottleneck for handling of parsing errors.1368 *1369 * @api private1370 */1371 _displayError(exitCode, code, message) {1372 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1373 this._exit(exitCode, code, message);1374 }13751376 /**1377 * Argument `name` is missing.1378 *1379 * @param {string} name1380 * @api private1381 */13821383 missingArgument(name) {1384 const message = `error: missing required argument '${name}'`;1385 this._displayError(1, 'commander.missingArgument', message);1386 };13871388 /**1389 * `Option` is missing an argument.1390 *1391 * @param {Option} option1392 * @api private1393 */13941395 optionMissingArgument(option) {1396 const message = `error: option '${option.flags}' argument missing`;1397 this._displayError(1, 'commander.optionMissingArgument', message);1398 };13991400 /**1401 * `Option` does not have a value, and is a mandatory option.1402 *1403 * @param {Option} option1404 * @api private1405 */14061407 missingMandatoryOptionValue(option) {1408 const message = `error: required option '${option.flags}' not specified`;1409 this._displayError(1, 'commander.missingMandatoryOptionValue', message);1410 };14111412 /**1413 * Unknown option `flag`.1414 *1415 * @param {string} flag1416 * @api private1417 */14181419 unknownOption(flag) {1420 if (this._allowUnknownOption) return;1421 const message = `error: unknown option '${flag}'`;1422 this._displayError(1, 'commander.unknownOption', message);1423 };14241425 /**1426 * Excess arguments, more than expected.1427 *1428 * @param {string[]} receivedArgs1429 * @api private1430 */14311432 _excessArguments(receivedArgs) {1433 if (this._allowExcessArguments) return;14341435 const expected = this._args.length;1436 const s = (expected === 1) ? '' : 's';1437 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1438 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1439 this._displayError(1, 'commander.excessArguments', message);1440 };14411442 /**1443 * Unknown command.1444 *1445 * @api private1446 */14471448 unknownCommand() {1449 const partCommands = [this.name()];1450 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1451 partCommands.unshift(parentCmd.name());1452 }1453 const fullCommand = partCommands.join(' ');1454 const message = `error: unknown command '${this.args[0]}'.` +1455 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');1456 this._displayError(1, 'commander.unknownCommand', message);1457 };14581459 /**1460 * Set the program version to `str`.1461 *1462 * This method auto-registers the "-V, --version" flag1463 * which will print the version number when passed.1464 *1465 * You can optionally supply the flags and description to override the defaults.1466 *1467 * @param {string} str1468 * @param {string} [flags]1469 * @param {string} [description]1470 * @return {this | string} `this` command for chaining, or version string if no arguments1471 */14721473 version(str, flags, description) {1474 if (str === undefined) return this._version;1475 this._version = str;1476 flags = flags || '-V, --version';1477 description = description || 'output the version number';1478 const versionOption = this.createOption(flags, description);1479 this._versionOptionName = versionOption.attributeName();1480 this.options.push(versionOption);1481 this.on('option:' + versionOption.name(), () => {1482 this._outputConfiguration.writeOut(`${str}\n`);1483 this._exit(0, 'commander.version', str);1484 });1485 return this;1486 };14871488 /**1489 * Set the description to `str`.1490 *1491 * @param {string} [str]1492 * @param {Object} [argsDescription]1493 * @return {string|Command}1494 */1495 description(str, argsDescription) {1496 if (str === undefined && argsDescription === undefined) return this._description;1497 this._description = str;1498 if (argsDescription) {1499 this._argsDescription = argsDescription;1500 }1501 return this;1502 };15031504 /**1505 * Set an alias for the command.1506 *1507 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1508 *1509 * @param {string} [alias]1510 * @return {string|Command}1511 */15121513 alias(alias) {1514 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility15151516 let command = this;1517 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1518 // assume adding alias for last added executable subcommand, rather than this1519 command = this.commands[this.commands.length - 1];1520 }15211522 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');15231524 command._aliases.push(alias);1525 return this;1526 };15271528 /**1529 * Set aliases for the command.1530 *1531 * Only the first alias is shown in the auto-generated help.1532 *1533 * @param {string[]} [aliases]1534 * @return {string[]|Command}1535 */15361537 aliases(aliases) {1538 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1539 if (aliases === undefined) return this._aliases;15401541 aliases.forEach((alias) => this.alias(alias));1542 return this;1543 };15441545 /**1546 * Set / get the command usage `str`.1547 *1548 * @param {string} [str]1549 * @return {String|Command}1550 */15511552 usage(str) {1553 if (str === undefined) {1554 if (this._usage) return this._usage;15551556 const args = this._args.map((arg) => {1557 return humanReadableArgName(arg);1558 });1559 return [].concat(1560 (this.options.length || this._hasHelpOption ? '[options]' : []),1561 (this.commands.length ? '[command]' : []),1562 (this._args.length ? args : [])1563 ).join(' ');1564 }15651566 this._usage = str;1567 return this;1568 };15691570 /**1571 * Get or set the name of the command1572 *1573 * @param {string} [str]1574 * @return {string|Command}1575 */15761577 name(str) {1578 if (str === undefined) return this._name;1579 this._name = str;1580 return this;1581 };15821583 /**1584 * Return program help documentation.1585 *1586 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1587 * @return {string}1588 */15891590 helpInformation(contextOptions) {1591 const helper = this.createHelp();1592 if (helper.helpWidth === undefined) {1593 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1594 }1595 return helper.formatHelp(this, helper);1596 };15971598 /**1599 * @api private1600 */16011602 _getHelpContext(contextOptions) {1603 contextOptions = contextOptions || {};1604 const context = { error: !!contextOptions.error };1605 let write;1606 if (context.error) {1607 write = (arg) => this._outputConfiguration.writeErr(arg);1608 } else {1609 write = (arg) => this._outputConfiguration.writeOut(arg);1610 }1611 context.write = contextOptions.write || write;1612 context.command = this;1613 return context;1614 }16151616 /**1617 * Output help information for this command.1618 *1619 * Outputs built-in help, and custom text added using `.addHelpText()`.1620 *1621 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1622 */16231624 outputHelp(contextOptions) {1625 let deprecatedCallback;1626 if (typeof contextOptions === 'function') {1627 deprecatedCallback = contextOptions;1628 contextOptions = undefined;1629 }1630 const context = this._getHelpContext(contextOptions);16311632 const groupListeners = [];1633 let command = this;1634 while (command) {1635 groupListeners.push(command); // ordered from current command to root1636 command = command.parent;1637 }16381639 groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));1640 this.emit('beforeHelp', context);16411642 let helpInformation = this.helpInformation(context);1643 if (deprecatedCallback) {1644 helpInformation = deprecatedCallback(helpInformation);1645 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1646 throw new Error('outputHelp callback must return a string or a Buffer');1647 }1648 }1649 context.write(helpInformation);16501651 this.emit(this._helpLongFlag); // deprecated1652 this.emit('afterHelp', context);1653 groupListeners.forEach(command => command.emit('afterAllHelp', context));1654 };16551656 /**1657 * You can pass in flags and a description to override the help1658 * flags and help description for your command. Pass in false to1659 * disable the built-in help option.1660 *1661 * @param {string | boolean} [flags]1662 * @param {string} [description]1663 * @return {Command} `this` command for chaining1664 */16651666 helpOption(flags, description) {1667 if (typeof flags === 'boolean') {1668 this._hasHelpOption = flags;1669 return this;1670 }1671 this._helpFlags = flags || this._helpFlags;1672 this._helpDescription = description || this._helpDescription;16731674 const helpFlags = splitOptionFlags(this._helpFlags);1675 this._helpShortFlag = helpFlags.shortFlag;1676 this._helpLongFlag = helpFlags.longFlag;16771678 return this;1679 };16801681 /**1682 * Output help information and exit.1683 *1684 * Outputs built-in help, and custom text added using `.addHelpText()`.1685 *1686 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1687 */16881689 help(contextOptions) {1690 this.outputHelp(contextOptions);1691 let exitCode = process.exitCode || 0;1692 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1693 exitCode = 1;1694 }1695 // message: do not have all displayed text available so only passing placeholder.1696 this._exit(exitCode, 'commander.help', '(outputHelp)');1697 };16981699 /**1700 * Add additional text to be displayed with the built-in help.1701 *1702 * Position is 'before' or 'after' to affect just this command,1703 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1704 *1705 * @param {string} position - before or after built-in help1706 * @param {string | Function} text - string to add, or a function returning a string1707 * @return {Command} `this` command for chaining1708 */1709 addHelpText(position, text) {1710 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1711 if (!allowedValues.includes(position)) {1712 throw new Error(`Unexpected value for position to addHelpText.1713Expecting one of '${allowedValues.join("', '")}'`);1714 }1715 const helpEvent = `${position}Help`;1716 this.on(helpEvent, (context) => {1717 let helpStr;1718 if (typeof text === 'function') {1719 helpStr = text({ error: context.error, command: context.command });1720 } else {1721 helpStr = text;1722 }1723 // Ignore falsy value when nothing to output.1724 if (helpStr) {1725 context.write(`${helpStr}\n`);1726 }1727 });1728 return this;1729 }1730};17311732/**1733 * Output help information if help flags specified1734 *1735 * @param {Command} cmd - command to output help for1736 * @param {Array} args - array of options to search for help flags1737 * @api private1738 */17391740function outputHelpIfRequested(cmd, args) {1741 const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1742 if (helpOption) {1743 cmd.outputHelp();1744 // (Do not have all displayed text available so only passing placeholder.)1745 cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');1746 }1747}17481749/**1750 * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).1751 *1752 * @param {string[]} args - array of arguments from node.execArgv1753 * @returns {string[]}1754 * @api private1755 */17561757function incrementNodeInspectorPort(args) {1758 // Testing for these options:1759 // --inspect[=[host:]port]1760 // --inspect-brk[=[host:]port]1761 // --inspect-port=[host:]port1762 return args.map((arg) => {1763 if (!arg.startsWith('--inspect')) {1764 return arg;1765 }1766 let debugOption;1767 let debugHost = '127.0.0.1';1768 let debugPort = '9229';1769 let match;1770 if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {1771 // e.g. --inspect1772 debugOption = match[1];1773 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {1774 debugOption = match[1];1775 if (/^\d+$/.test(match[3])) {1776 // e.g. --inspect=12341777 debugPort = match[3];1778 } else {1779 // e.g. --inspect=localhost1780 debugHost = match[3];1781 }1782 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {1783 // e.g. --inspect=localhost:12341784 debugOption = match[1];1785 debugHost = match[3];1786 debugPort = match[4];1787 }17881789 if (debugOption && debugPort !== '0') {1790 return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;1791 }1792 return arg;1793 });1794}17951796/**1797 * @param {Command} startCommand1798 * @returns {Command[]}1799 * @api private1800 */18011802function getCommandAndParents(startCommand) {1803 const result = [];1804 for (let command = startCommand; command; command = command.parent) {1805 result.push(command);1806 }1807 return result;1808}18091810exports.Command = Command;