command.js
This file
Path
lib/command.js
1,924 lines · 60.4 KiB · JavaScript
Last changed by
Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
History of this fileTake it
1const 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');10const { suggestSimilar } = require('./suggestSimilar');1112// @ts-check1314class Command extends EventEmitter {15 /**16 * Initialize a new `Command`.17 *18 * @param {string} [name]19 */2021 constructor(name) {22 super();23 /** @type {Command[]} */24 this.commands = [];25 /** @type {Option[]} */26 this.options = [];27 this.parent = null;28 this._allowUnknownOption = false;29 this._allowExcessArguments = true;30 /** @type {Argument[]} */31 this._args = [];32 /** @type {string[]} */33 this.args = []; // cli args with options removed34 this.rawArgs = [];35 this.processedArgs = []; // like .args but after custom processing and collecting variadic36 this._scriptPath = null;37 this._name = name || '';38 this._optionValues = {};39 this._optionValueSources = {}; // default < env < cli40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable44 this._defaultCommandName = null;45 this._exitCallback = null;46 this._aliases = [];47 this._combineFlagAndOptionalValue = true;48 this._description = '';49 this._argsDescription = undefined; // legacy50 this._enablePositionalOptions = false;51 this._passThroughOptions = false;52 this._lifeCycleHooks = {}; // a hash of arrays53 /** @type {boolean | string} */54 this._showHelpAfterError = false;55 this._showSuggestionAfterError = false;5657 // see .configureOutput() for docs58 this._outputConfiguration = {59 writeOut: (str) => process.stdout.write(str),60 writeErr: (str) => process.stderr.write(str),61 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,62 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,63 outputError: (str, write) => write(str)64 };6566 this._hidden = false;67 this._hasHelpOption = true;68 this._helpFlags = '-h, --help';69 this._helpDescription = 'display help for command';70 this._helpShortFlag = '-h';71 this._helpLongFlag = '--help';72 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false73 this._helpCommandName = 'help';74 this._helpCommandnameAndArgs = 'help [command]';75 this._helpCommandDescription = 'display help for command';76 this._helpConfiguration = {};77 }7879 /**80 * Copy settings that are useful to have in common across root command and subcommands.81 *82 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)83 *84 * @param {Command} sourceCommand85 * @return {Command} returns `this` for executable command86 */87 copyInheritedSettings(sourceCommand) {88 this._outputConfiguration = sourceCommand._outputConfiguration;89 this._hasHelpOption = sourceCommand._hasHelpOption;90 this._helpFlags = sourceCommand._helpFlags;91 this._helpDescription = sourceCommand._helpDescription;92 this._helpShortFlag = sourceCommand._helpShortFlag;93 this._helpLongFlag = sourceCommand._helpLongFlag;94 this._helpCommandName = sourceCommand._helpCommandName;95 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;96 this._helpCommandDescription = sourceCommand._helpCommandDescription;97 this._helpConfiguration = sourceCommand._helpConfiguration;98 this._exitCallback = sourceCommand._exitCallback;99 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;100 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;101 this._allowExcessArguments = sourceCommand._allowExcessArguments;102 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103 this._showHelpAfterError = sourceCommand._showHelpAfterError;104 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;105106 return this;107 }108109 /**110 * Define a command.111 *112 * There are two styles of command: pay attention to where to put the description.113 *114 * @example115 * // Command implemented using action handler (description is supplied separately to `.command`)116 * program117 * .command('clone <source> [destination]')118 * .description('clone a repository into a newly created directory')119 * .action((source, destination) => {120 * console.log('clone command called');121 * });122 *123 * // Command implemented using separate executable file (description is second parameter to `.command`)124 * program125 * .command('start <service>', 'start named service')126 * .command('stop [service]', 'stop named service, or all if no name supplied');127 *128 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`129 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)130 * @param {Object} [execOpts] - configuration options (for executable)131 * @return {Command} returns new command for action handler, or `this` for executable command132 */133134 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {135 let desc = actionOptsOrExecDesc;136 let opts = execOpts;137 if (typeof desc === 'object' && desc !== null) {138 opts = desc;139 desc = null;140 }141 opts = opts || {};142 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);143144 const cmd = this.createCommand(name);145 if (desc) {146 cmd.description(desc);147 cmd._executableHandler = true;148 }149 if (opts.isDefault) this._defaultCommandName = cmd._name;150 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden151 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor152 if (args) cmd.arguments(args);153 this.commands.push(cmd);154 cmd.parent = this;155 cmd.copyInheritedSettings(this);156157 if (desc) return this;158 return cmd;159 };160161 /**162 * Factory routine to create a new unattached command.163 *164 * See .command() for creating an attached subcommand, which uses this routine to165 * create the command. You can override createCommand to customise subcommands.166 *167 * @param {string} [name]168 * @return {Command} new command169 */170171 createCommand(name) {172 return new Command(name);173 };174175 /**176 * You can customise the help with a subclass of Help by overriding createHelp,177 * or by overriding Help properties using configureHelp().178 *179 * @return {Help}180 */181182 createHelp() {183 return Object.assign(new Help(), this.configureHelp());184 };185186 /**187 * You can customise the help by overriding Help properties using configureHelp(),188 * or with a subclass of Help by overriding createHelp().189 *190 * @param {Object} [configuration] - configuration options191 * @return {Command|Object} `this` command for chaining, or stored configuration192 */193194 configureHelp(configuration) {195 if (configuration === undefined) return this._helpConfiguration;196197 this._helpConfiguration = configuration;198 return this;199 }200201 /**202 * The default output goes to stdout and stderr. You can customise this for special203 * applications. You can also customise the display of errors by overriding outputError.204 *205 * The configuration properties are all functions:206 *207 * // functions to change where being written, stdout and stderr208 * writeOut(str)209 * writeErr(str)210 * // matching functions to specify width for wrapping help211 * getOutHelpWidth()212 * getErrHelpWidth()213 * // functions based on what is being written out214 * outputError(str, write) // used for displaying errors, and not used for displaying help215 *216 * @param {Object} [configuration] - configuration options217 * @return {Command|Object} `this` command for chaining, or stored configuration218 */219220 configureOutput(configuration) {221 if (configuration === undefined) return this._outputConfiguration;222223 Object.assign(this._outputConfiguration, configuration);224 return this;225 }226227 /**228 * Display the help or a custom message after an error occurs.229 *230 * @param {boolean|string} [displayHelp]231 * @return {Command} `this` command for chaining232 */233 showHelpAfterError(displayHelp = true) {234 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;235 this._showHelpAfterError = displayHelp;236 return this;237 }238239 /**240 * Display suggestion of similar commands for unknown commands, or options for unknown options.241 *242 * @param {boolean} [displaySuggestion]243 * @return {Command} `this` command for chaining244 */245 showSuggestionAfterError(displaySuggestion = true) {246 this._showSuggestionAfterError = !!displaySuggestion;247 return this;248 }249250 /**251 * Add a prepared subcommand.252 *253 * See .command() for creating an attached subcommand which inherits settings from its parent.254 *255 * @param {Command} cmd - new subcommand256 * @param {Object} [opts] - configuration options257 * @return {Command} `this` command for chaining258 */259260 addCommand(cmd, opts) {261 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');262263 // To keep things simple, block automatic name generation for deeply nested executables.264 // Fail fast and detect when adding rather than later when parsing.265 function checkExplicitNames(commandArray) {266 commandArray.forEach((cmd) => {267 if (cmd._executableHandler && !cmd._executableFile) {268 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);269 }270 checkExplicitNames(cmd.commands);271 });272 }273 checkExplicitNames(cmd.commands);274275 opts = opts || {};276 if (opts.isDefault) this._defaultCommandName = cmd._name;277 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation278279 this.commands.push(cmd);280 cmd.parent = this;281 return this;282 };283284 /**285 * Factory routine to create a new unattached argument.286 *287 * See .argument() for creating an attached argument, which uses this routine to288 * create the argument. You can override createArgument to return a custom argument.289 *290 * @param {string} name291 * @param {string} [description]292 * @return {Argument} new argument293 */294295 createArgument(name, description) {296 return new Argument(name, description);297 };298299 /**300 * Define argument syntax for command.301 *302 * The default is that the argument is required, and you can explicitly303 * indicate this with <> around the name. Put [] around the name for an optional argument.304 *305 * @example306 * program.argument('<input-file>');307 * program.argument('[output-file]');308 *309 * @param {string} name310 * @param {string} [description]311 * @param {Function|*} [fn] - custom argument processing function312 * @param {*} [defaultValue]313 * @return {Command} `this` command for chaining314 */315 argument(name, description, fn, defaultValue) {316 const argument = this.createArgument(name, description);317 if (typeof fn === 'function') {318 argument.default(defaultValue).argParser(fn);319 } else {320 argument.default(fn);321 }322 this.addArgument(argument);323 return this;324 }325326 /**327 * Define argument syntax for command, adding multiple at once (without descriptions).328 *329 * See also .argument().330 *331 * @example332 * program.arguments('<cmd> [env]');333 *334 * @param {string} names335 * @return {Command} `this` command for chaining336 */337338 arguments(names) {339 names.split(/ +/).forEach((detail) => {340 this.argument(detail);341 });342 return this;343 };344345 /**346 * Define argument syntax for command, adding a prepared argument.347 *348 * @param {Argument} argument349 * @return {Command} `this` command for chaining350 */351 addArgument(argument) {352 const previousArgument = this._args.slice(-1)[0];353 if (previousArgument && previousArgument.variadic) {354 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);355 }356 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {357 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);358 }359 this._args.push(argument);360 return this;361 }362363 /**364 * Override default decision whether to add implicit help command.365 *366 * addHelpCommand() // force on367 * addHelpCommand(false); // force off368 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details369 *370 * @return {Command} `this` command for chaining371 */372373 addHelpCommand(enableOrNameAndArgs, description) {374 if (enableOrNameAndArgs === false) {375 this._addImplicitHelpCommand = false;376 } else {377 this._addImplicitHelpCommand = true;378 if (typeof enableOrNameAndArgs === 'string') {379 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];380 this._helpCommandnameAndArgs = enableOrNameAndArgs;381 }382 this._helpCommandDescription = description || this._helpCommandDescription;383 }384 return this;385 };386387 /**388 * @return {boolean}389 * @api private390 */391392 _hasImplicitHelpCommand() {393 if (this._addImplicitHelpCommand === undefined) {394 return this.commands.length && !this._actionHandler && !this._findCommand('help');395 }396 return this._addImplicitHelpCommand;397 };398399 /**400 * Add hook for life cycle event.401 *402 * @param {string} event403 * @param {Function} listener404 * @return {Command} `this` command for chaining405 */406407 hook(event, listener) {408 const allowedValues = ['preAction', 'postAction'];409 if (!allowedValues.includes(event)) {410 throw new Error(`Unexpected value for event passed to hook : '${event}'.411Expecting one of '${allowedValues.join("', '")}'`);412 }413 if (this._lifeCycleHooks[event]) {414 this._lifeCycleHooks[event].push(listener);415 } else {416 this._lifeCycleHooks[event] = [listener];417 }418 return this;419 }420421 /**422 * Register callback to use as replacement for calling process.exit.423 *424 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing425 * @return {Command} `this` command for chaining426 */427428 exitOverride(fn) {429 if (fn) {430 this._exitCallback = fn;431 } else {432 this._exitCallback = (err) => {433 if (err.code !== 'commander.executeSubCommandAsync') {434 throw err;435 } else {436 // Async callback from spawn events, not useful to throw.437 }438 };439 }440 return this;441 };442443 /**444 * Call process.exit, and _exitCallback if defined.445 *446 * @param {number} exitCode exit code for using with process.exit447 * @param {string} code an id string representing the error448 * @param {string} message human-readable description of the error449 * @return never450 * @api private451 */452453 _exit(exitCode, code, message) {454 if (this._exitCallback) {455 this._exitCallback(new CommanderError(exitCode, code, message));456 // Expecting this line is not reached.457 }458 process.exit(exitCode);459 };460461 /**462 * Register callback `fn` for the command.463 *464 * @example465 * program466 * .command('help')467 * .description('display verbose help')468 * .action(function() {469 * // output help here470 * });471 *472 * @param {Function} fn473 * @return {Command} `this` command for chaining474 */475476 action(fn) {477 const listener = (args) => {478 // The .action callback takes an extra parameter which is the command or options.479 const expectedArgsCount = this._args.length;480 const actionArgs = args.slice(0, expectedArgsCount);481 if (this._storeOptionsAsProperties) {482 actionArgs[expectedArgsCount] = this; // backwards compatible "options"483 } else {484 actionArgs[expectedArgsCount] = this.opts();485 }486 actionArgs.push(this);487488 return fn.apply(this, actionArgs);489 };490 this._actionHandler = listener;491 return this;492 };493494 /**495 * Factory routine to create a new unattached option.496 *497 * See .option() for creating an attached option, which uses this routine to498 * create the option. You can override createOption to return a custom option.499 *500 * @param {string} flags501 * @param {string} [description]502 * @return {Option} new option503 */504505 createOption(flags, description) {506 return new Option(flags, description);507 };508509 /**510 * Add an option.511 *512 * @param {Option} option513 * @return {Command} `this` command for chaining514 */515 addOption(option) {516 const oname = option.name();517 const name = option.attributeName();518519 let defaultValue = option.defaultValue;520521 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value522 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {523 // when --no-foo we make sure default is true, unless a --foo option is already defined524 if (option.negate) {525 const positiveLongFlag = option.long.replace(/^--no-/, '--');526 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;527 }528 // preassign only if we have a default529 if (defaultValue !== undefined) {530 this._setOptionValueWithSource(name, defaultValue, 'default');531 }532 }533534 // register the option535 this.options.push(option);536537 // handler for cli and env supplied values538 const handleOptionValue = (val, invalidValueMessage, valueSource) => {539 // Note: using closure to access lots of lexical scoped variables.540 const oldValue = this.getOptionValue(name);541542 // custom processing543 if (val !== null && option.parseArg) {544 try {545 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);546 } catch (err) {547 if (err.code === 'commander.invalidArgument') {548 const message = `${invalidValueMessage} ${err.message}`;549 this._displayError(err.exitCode, err.code, message);550 }551 throw err;552 }553 } else if (val !== null && option.variadic) {554 val = option._concatValue(val, oldValue);555 }556557 // unassigned or boolean value558 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {559 // if no value, negate false, and we have a default, then use it!560 if (val == null) {561 this._setOptionValueWithSource(name, option.negate ? false : defaultValue || true, valueSource);562 } else {563 this._setOptionValueWithSource(name, val, valueSource);564 }565 } else if (val !== null) {566 // reassign567 this._setOptionValueWithSource(name, option.negate ? false : val, valueSource);568 }569 };570571 this.on('option:' + oname, (val) => {572 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;573 handleOptionValue(val, invalidValueMessage, 'cli');574 });575576 if (option.envVar) {577 this.on('optionEnv:' + oname, (val) => {578 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;579 handleOptionValue(val, invalidValueMessage, 'env');580 });581 }582583 return this;584 }585586 /**587 * Internal implementation shared by .option() and .requiredOption()588 *589 * @api private590 */591 _optionEx(config, flags, description, fn, defaultValue) {592 const option = this.createOption(flags, description);593 option.makeOptionMandatory(!!config.mandatory);594 if (typeof fn === 'function') {595 option.default(defaultValue).argParser(fn);596 } else if (fn instanceof RegExp) {597 // deprecated598 const regex = fn;599 fn = (val, def) => {600 const m = regex.exec(val);601 return m ? m[0] : def;602 };603 option.default(defaultValue).argParser(fn);604 } else {605 option.default(fn);606 }607608 return this.addOption(option);609 }610611 /**612 * Define option with `flags`, `description` and optional613 * coercion `fn`.614 *615 * The `flags` string contains the short and/or long flags,616 * separated by comma, a pipe or space. The following are all valid617 * all will output this way when `--help` is used.618 *619 * "-p, --pepper"620 * "-p|--pepper"621 * "-p --pepper"622 *623 * @example624 * // simple boolean defaulting to undefined625 * program.option('-p, --pepper', 'add pepper');626 *627 * program.pepper628 * // => undefined629 *630 * --pepper631 * program.pepper632 * // => true633 *634 * // simple boolean defaulting to true (unless non-negated option is also defined)635 * program.option('-C, --no-cheese', 'remove cheese');636 *637 * program.cheese638 * // => true639 *640 * --no-cheese641 * program.cheese642 * // => false643 *644 * // required argument645 * program.option('-C, --chdir <path>', 'change the working directory');646 *647 * --chdir /tmp648 * program.chdir649 * // => "/tmp"650 *651 * // optional argument652 * program.option('-c, --cheese [type]', 'add cheese [marble]');653 *654 * @param {string} flags655 * @param {string} [description]656 * @param {Function|*} [fn] - custom option processing function or default value657 * @param {*} [defaultValue]658 * @return {Command} `this` command for chaining659 */660661 option(flags, description, fn, defaultValue) {662 return this._optionEx({}, flags, description, fn, defaultValue);663 };664665 /**666 * Add a required option which must have a value after parsing. This usually means667 * the option must be specified on the command line. (Otherwise the same as .option().)668 *669 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.670 *671 * @param {string} flags672 * @param {string} [description]673 * @param {Function|*} [fn] - custom option processing function or default value674 * @param {*} [defaultValue]675 * @return {Command} `this` command for chaining676 */677678 requiredOption(flags, description, fn, defaultValue) {679 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);680 };681682 /**683 * Alter parsing of short flags with optional values.684 *685 * @example686 * // for `.option('-f,--flag [value]'):687 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour688 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`689 *690 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.691 */692 combineFlagAndOptionalValue(combine = true) {693 this._combineFlagAndOptionalValue = !!combine;694 return this;695 };696697 /**698 * Allow unknown options on the command line.699 *700 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown701 * for unknown options.702 */703 allowUnknownOption(allowUnknown = true) {704 this._allowUnknownOption = !!allowUnknown;705 return this;706 };707708 /**709 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.710 *711 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown712 * for excess arguments.713 */714 allowExcessArguments(allowExcess = true) {715 this._allowExcessArguments = !!allowExcess;716 return this;717 };718719 /**720 * Enable positional options. Positional means global options are specified before subcommands which lets721 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.722 * The default behaviour is non-positional and global options may appear anywhere on the command line.723 *724 * @param {Boolean} [positional=true]725 */726 enablePositionalOptions(positional = true) {727 this._enablePositionalOptions = !!positional;728 return this;729 };730731 /**732 * Pass through options that come after command-arguments rather than treat them as command-options,733 * so actual command-options come before command-arguments. Turning this on for a subcommand requires734 * positional options to have been enabled on the program (parent commands).735 * The default behaviour is non-positional and options may appear before or after command-arguments.736 *737 * @param {Boolean} [passThrough=true]738 * for unknown options.739 */740 passThroughOptions(passThrough = true) {741 this._passThroughOptions = !!passThrough;742 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {743 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');744 }745 return this;746 };747748 /**749 * Whether to store option values as properties on command object,750 * or store separately (specify false). In both cases the option values can be accessed using .opts().751 *752 * @param {boolean} [storeAsProperties=true]753 * @return {Command} `this` command for chaining754 */755756 storeOptionsAsProperties(storeAsProperties = true) {757 this._storeOptionsAsProperties = !!storeAsProperties;758 if (this.options.length) {759 throw new Error('call .storeOptionsAsProperties() before adding options');760 }761 return this;762 };763764 /**765 * Retrieve option value.766 *767 * @param {string} key768 * @return {Object} value769 */770771 getOptionValue(key) {772 if (this._storeOptionsAsProperties) {773 return this[key];774 }775 return this._optionValues[key];776 };777778 /**779 * Store option value.780 *781 * @param {string} key782 * @param {Object} value783 * @return {Command} `this` command for chaining784 */785786 setOptionValue(key, value) {787 if (this._storeOptionsAsProperties) {788 this[key] = value;789 } else {790 this._optionValues[key] = value;791 }792 return this;793 };794795 /**796 * @api private797 */798 _setOptionValueWithSource(key, value, source) {799 this.setOptionValue(key, value);800 this._optionValueSources[key] = source;801 }802803 /**804 * Get user arguments implied or explicit arguments.805 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.806 *807 * @api private808 */809810 _prepareUserArgs(argv, parseOptions) {811 if (argv !== undefined && !Array.isArray(argv)) {812 throw new Error('first parameter to parse must be array or undefined');813 }814 parseOptions = parseOptions || {};815816 // Default to using process.argv817 if (argv === undefined) {818 argv = process.argv;819 // @ts-ignore: unknown property820 if (process.versions && process.versions.electron) {821 parseOptions.from = 'electron';822 }823 }824 this.rawArgs = argv.slice();825826 // make it a little easier for callers by supporting various argv conventions827 let userArgs;828 switch (parseOptions.from) {829 case undefined:830 case 'node':831 this._scriptPath = argv[1];832 userArgs = argv.slice(2);833 break;834 case 'electron':835 // @ts-ignore: unknown property836 if (process.defaultApp) {837 this._scriptPath = argv[1];838 userArgs = argv.slice(2);839 } else {840 userArgs = argv.slice(1);841 }842 break;843 case 'user':844 userArgs = argv.slice(0);845 break;846 default:847 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);848 }849 if (!this._scriptPath && require.main) {850 this._scriptPath = require.main.filename;851 }852853 // Guess name, used in usage in help.854 this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));855856 return userArgs;857 }858859 /**860 * Parse `argv`, setting options and invoking commands when defined.861 *862 * The default expectation is that the arguments are from node and have the application as argv[0]863 * and the script being run in argv[1], with user parameters after that.864 *865 * @example866 * program.parse(process.argv);867 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions868 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]869 *870 * @param {string[]} [argv] - optional, defaults to process.argv871 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron872 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'873 * @return {Command} `this` command for chaining874 */875876 parse(argv, parseOptions) {877 const userArgs = this._prepareUserArgs(argv, parseOptions);878 this._parseCommand([], userArgs);879880 return this;881 };882883 /**884 * Parse `argv`, setting options and invoking commands when defined.885 *886 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.887 *888 * The default expectation is that the arguments are from node and have the application as argv[0]889 * and the script being run in argv[1], with user parameters after that.890 *891 * @example892 * await program.parseAsync(process.argv);893 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions894 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]895 *896 * @param {string[]} [argv]897 * @param {Object} [parseOptions]898 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'899 * @return {Promise}900 */901902 async parseAsync(argv, parseOptions) {903 const userArgs = this._prepareUserArgs(argv, parseOptions);904 await this._parseCommand([], userArgs);905906 return this;907 };908909 /**910 * Execute a sub-command executable.911 *912 * @api private913 */914915 _executeSubCommand(subcommand, args) {916 args = args.slice();917 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.918 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];919920 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.921 this._checkForMissingMandatoryOptions();922923 // Want the entry script as the reference for command name and directory for searching for other files.924 let scriptPath = this._scriptPath;925 // Fallback in case not set, due to how Command created or called.926 if (!scriptPath && require.main) {927 scriptPath = require.main.filename;928 }929930 let baseDir;931 try {932 const resolvedLink = fs.realpathSync(scriptPath);933 baseDir = path.dirname(resolvedLink);934 } catch (e) {935 baseDir = '.'; // dummy, probably not going to find executable!936 }937938 // name of the subcommand, like `pm-install`939 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;940 if (subcommand._executableFile) {941 bin = subcommand._executableFile;942 }943944 const localBin = path.join(baseDir, bin);945 if (fs.existsSync(localBin)) {946 // prefer local `./<bin>` to bin in the $PATH947 bin = localBin;948 } else {949 // Look for source files.950 sourceExt.forEach((ext) => {951 if (fs.existsSync(`${localBin}${ext}`)) {952 bin = `${localBin}${ext}`;953 }954 });955 }956 launchWithNode = sourceExt.includes(path.extname(bin));957958 let proc;959 if (process.platform !== 'win32') {960 if (launchWithNode) {961 args.unshift(bin);962 // add executable arguments to spawn963 args = incrementNodeInspectorPort(process.execArgv).concat(args);964965 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });966 } else {967 proc = childProcess.spawn(bin, args, { stdio: 'inherit' });968 }969 } else {970 args.unshift(bin);971 // add executable arguments to spawn972 args = incrementNodeInspectorPort(process.execArgv).concat(args);973 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });974 }975976 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];977 signals.forEach((signal) => {978 // @ts-ignore979 process.on(signal, () => {980 if (proc.killed === false && proc.exitCode === null) {981 proc.kill(signal);982 }983 });984 });985986 // By default terminate process when spawned process terminates.987 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!988 const exitCallback = this._exitCallback;989 if (!exitCallback) {990 proc.on('close', process.exit.bind(process));991 } else {992 proc.on('close', () => {993 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));994 });995 }996 proc.on('error', (err) => {997 // @ts-ignore998 if (err.code === 'ENOENT') {999 const executableMissing = `'${bin}' does not exist1000 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1001 - if the default executable name is not suitable, use the executableFile option to supply a custom name`;1002 throw new Error(executableMissing);1003 // @ts-ignore1004 } else if (err.code === 'EACCES') {1005 throw new Error(`'${bin}' not executable`);1006 }1007 if (!exitCallback) {1008 process.exit(1);1009 } else {1010 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1011 wrappedError.nestedError = err;1012 exitCallback(wrappedError);1013 }1014 });10151016 // Store the reference to the child process1017 this.runningCommand = proc;1018 };10191020 /**1021 * @api private1022 */10231024 _dispatchSubcommand(commandName, operands, unknown) {1025 const subCommand = this._findCommand(commandName);1026 if (!subCommand) this.help({ error: true });10271028 if (subCommand._executableHandler) {1029 this._executeSubCommand(subCommand, operands.concat(unknown));1030 } else {1031 return subCommand._parseCommand(operands, unknown);1032 }1033 };10341035 /**1036 * Check this.args against expected this._args.1037 *1038 * @api private1039 */10401041 _checkNumberOfArguments() {1042 // too few1043 this._args.forEach((arg, i) => {1044 if (arg.required && this.args[i] == null) {1045 this.missingArgument(arg.name());1046 }1047 });1048 // too many1049 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1050 return;1051 }1052 if (this.args.length > this._args.length) {1053 this._excessArguments(this.args);1054 }1055 };10561057 /**1058 * Process this.args using this._args and save as this.processedArgs!1059 *1060 * @api private1061 */10621063 _processArguments() {1064 const myParseArg = (argument, value, previous) => {1065 // Extra processing for nice error message on parsing failure.1066 let parsedValue = value;1067 if (value !== null && argument.parseArg) {1068 try {1069 parsedValue = argument.parseArg(value, previous);1070 } catch (err) {1071 if (err.code === 'commander.invalidArgument') {1072 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1073 this._displayError(err.exitCode, err.code, message);1074 }1075 throw err;1076 }1077 }1078 return parsedValue;1079 };10801081 this._checkNumberOfArguments();10821083 const processedArgs = [];1084 this._args.forEach((declaredArg, index) => {1085 let value = declaredArg.defaultValue;1086 if (declaredArg.variadic) {1087 // Collect together remaining arguments for passing together as an array.1088 if (index < this.args.length) {1089 value = this.args.slice(index);1090 if (declaredArg.parseArg) {1091 value = value.reduce((processed, v) => {1092 return myParseArg(declaredArg, v, processed);1093 }, declaredArg.defaultValue);1094 }1095 } else if (value === undefined) {1096 value = [];1097 }1098 } else if (index < this.args.length) {1099 value = this.args[index];1100 if (declaredArg.parseArg) {1101 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1102 }1103 }1104 processedArgs[index] = value;1105 });1106 this.processedArgs = processedArgs;1107 }11081109 /**1110 * Once we have a promise we chain, but call synchronously until then.1111 *1112 * @param {Promise|undefined} promise1113 * @param {Function} fn1114 * @return {Promise|undefined}1115 */11161117 _chainOrCall(promise, fn) {1118 // thenable1119 if (promise && promise.then && typeof promise.then === 'function') {1120 // already have a promise, chain callback1121 return promise.then(() => fn());1122 }1123 // callback might return a promise1124 return fn();1125 }11261127 /**1128 *1129 * @param {Promise|undefined} promise1130 * @param {string} event1131 * @return {Promise|undefined}1132 * @api private1133 */11341135 _chainOrCallHooks(promise, event) {1136 let result = promise;1137 const hooks = [];1138 getCommandAndParents(this)1139 .reverse()1140 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1141 .forEach(hookedCommand => {1142 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1143 hooks.push({ hookedCommand, callback });1144 });1145 });1146 if (event === 'postAction') {1147 hooks.reverse();1148 }11491150 hooks.forEach((hookDetail) => {1151 result = this._chainOrCall(result, () => {1152 return hookDetail.callback(hookDetail.hookedCommand, this);1153 });1154 });1155 return result;1156 }11571158 /**1159 * Process arguments in context of this command.1160 * Returns action result, in case it is a promise.1161 *1162 * @api private1163 */11641165 _parseCommand(operands, unknown) {1166 const parsed = this.parseOptions(unknown);1167 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1168 operands = operands.concat(parsed.operands);1169 unknown = parsed.unknown;1170 this.args = operands.concat(unknown);11711172 if (operands && this._findCommand(operands[0])) {1173 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1174 }1175 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1176 if (operands.length === 1) {1177 this.help();1178 }1179 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1180 }1181 if (this._defaultCommandName) {1182 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1183 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1184 }1185 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1186 // probably missing subcommand and no handler, user needs help (and exit)1187 this.help({ error: true });1188 }11891190 outputHelpIfRequested(this, parsed.unknown);1191 this._checkForMissingMandatoryOptions();11921193 // We do not always call this check to avoid masking a "better" error, like unknown command.1194 const checkForUnknownOptions = () => {1195 if (parsed.unknown.length > 0) {1196 this.unknownOption(parsed.unknown[0]);1197 }1198 };11991200 const commandEvent = `command:${this.name()}`;1201 if (this._actionHandler) {1202 checkForUnknownOptions();1203 this._processArguments();12041205 let actionResult;1206 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1207 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));1208 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1209 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1210 return actionResult;1211 }1212 if (this.parent && this.parent.listenerCount(commandEvent)) {1213 checkForUnknownOptions();1214 this._processArguments();1215 this.parent.emit(commandEvent, operands, unknown); // legacy1216 } else if (operands.length) {1217 if (this._findCommand('*')) { // legacy default command1218 return this._dispatchSubcommand('*', operands, unknown);1219 }1220 if (this.listenerCount('command:*')) {1221 // skip option check, emit event for possible misspelling suggestion1222 this.emit('command:*', operands, unknown);1223 } else if (this.commands.length) {1224 this.unknownCommand();1225 } else {1226 checkForUnknownOptions();1227 this._processArguments();1228 }1229 } else if (this.commands.length) {1230 checkForUnknownOptions();1231 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1232 this.help({ error: true });1233 } else {1234 checkForUnknownOptions();1235 this._processArguments();1236 // fall through for caller to handle after calling .parse()1237 }1238 };12391240 /**1241 * Find matching command.1242 *1243 * @api private1244 */1245 _findCommand(name) {1246 if (!name) return undefined;1247 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1248 };12491250 /**1251 * Return an option matching `arg` if any.1252 *1253 * @param {string} arg1254 * @return {Option}1255 * @api private1256 */12571258 _findOption(arg) {1259 return this.options.find(option => option.is(arg));1260 };12611262 /**1263 * Display an error message if a mandatory option does not have a value.1264 * Lazy calling after checking for help flags from leaf subcommand.1265 *1266 * @api private1267 */12681269 _checkForMissingMandatoryOptions() {1270 // Walk up hierarchy so can call in subcommand after checking for displaying help.1271 for (let cmd = this; cmd; cmd = cmd.parent) {1272 cmd.options.forEach((anOption) => {1273 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1274 cmd.missingMandatoryOptionValue(anOption);1275 }1276 });1277 }1278 };12791280 /**1281 * Parse options from `argv` removing known options,1282 * and return argv split into operands and unknown arguments.1283 *1284 * Examples:1285 *1286 * argv => operands, unknown1287 * --known kkk op => [op], []1288 * op --known kkk => [op], []1289 * sub --unknown uuu op => [sub], [--unknown uuu op]1290 * sub -- --unknown uuu op => [sub --unknown uuu op], []1291 *1292 * @param {String[]} argv1293 * @return {{operands: String[], unknown: String[]}}1294 */12951296 parseOptions(argv) {1297 const operands = []; // operands, not options or values1298 const unknown = []; // first unknown option and remaining unknown args1299 let dest = operands;1300 const args = argv.slice();13011302 function maybeOption(arg) {1303 return arg.length > 1 && arg[0] === '-';1304 }13051306 // parse options1307 let activeVariadicOption = null;1308 while (args.length) {1309 const arg = args.shift();13101311 // literal1312 if (arg === '--') {1313 if (dest === unknown) dest.push(arg);1314 dest.push(...args);1315 break;1316 }13171318 if (activeVariadicOption && !maybeOption(arg)) {1319 this.emit(`option:${activeVariadicOption.name()}`, arg);1320 continue;1321 }1322 activeVariadicOption = null;13231324 if (maybeOption(arg)) {1325 const option = this._findOption(arg);1326 // recognised option, call listener to assign value with possible custom processing1327 if (option) {1328 if (option.required) {1329 const value = args.shift();1330 if (value === undefined) this.optionMissingArgument(option);1331 this.emit(`option:${option.name()}`, value);1332 } else if (option.optional) {1333 let value = null;1334 // historical behaviour is optional value is following arg unless an option1335 if (args.length > 0 && !maybeOption(args[0])) {1336 value = args.shift();1337 }1338 this.emit(`option:${option.name()}`, value);1339 } else { // boolean flag1340 this.emit(`option:${option.name()}`);1341 }1342 activeVariadicOption = option.variadic ? option : null;1343 continue;1344 }1345 }13461347 // Look for combo options following single dash, eat first one if known.1348 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1349 const option = this._findOption(`-${arg[1]}`);1350 if (option) {1351 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1352 // option with value following in same argument1353 this.emit(`option:${option.name()}`, arg.slice(2));1354 } else {1355 // boolean option, emit and put back remainder of arg for further processing1356 this.emit(`option:${option.name()}`);1357 args.unshift(`-${arg.slice(2)}`);1358 }1359 continue;1360 }1361 }13621363 // Look for known long flag with value, like --foo=bar1364 if (/^--[^=]+=/.test(arg)) {1365 const index = arg.indexOf('=');1366 const option = this._findOption(arg.slice(0, index));1367 if (option && (option.required || option.optional)) {1368 this.emit(`option:${option.name()}`, arg.slice(index + 1));1369 continue;1370 }1371 }13721373 // Not a recognised option by this command.1374 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.13751376 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1377 if (maybeOption(arg)) {1378 dest = unknown;1379 }13801381 // If using positionalOptions, stop processing our options at subcommand.1382 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1383 if (this._findCommand(arg)) {1384 operands.push(arg);1385 if (args.length > 0) unknown.push(...args);1386 break;1387 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1388 operands.push(arg);1389 if (args.length > 0) operands.push(...args);1390 break;1391 } else if (this._defaultCommandName) {1392 unknown.push(arg);1393 if (args.length > 0) unknown.push(...args);1394 break;1395 }1396 }13971398 // If using passThroughOptions, stop processing options at first command-argument.1399 if (this._passThroughOptions) {1400 dest.push(arg);1401 if (args.length > 0) dest.push(...args);1402 break;1403 }14041405 // add arg1406 dest.push(arg);1407 }14081409 return { operands, unknown };1410 };14111412 /**1413 * Return an object containing options as key-value pairs1414 *1415 * @return {Object}1416 */1417 opts() {1418 if (this._storeOptionsAsProperties) {1419 // Preserve original behaviour so backwards compatible when still using properties1420 const result = {};1421 const len = this.options.length;14221423 for (let i = 0; i < len; i++) {1424 const key = this.options[i].attributeName();1425 result[key] = key === this._versionOptionName ? this._version : this[key];1426 }1427 return result;1428 }14291430 return this._optionValues;1431 };14321433 /**1434 * Internal bottleneck for handling of parsing errors.1435 *1436 * @api private1437 */1438 _displayError(exitCode, code, message) {1439 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1440 if (typeof this._showHelpAfterError === 'string') {1441 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1442 } else if (this._showHelpAfterError) {1443 this._outputConfiguration.writeErr('\n');1444 this.outputHelp({ error: true });1445 }1446 this._exit(exitCode, code, message);1447 }14481449 /**1450 * Apply any option related environment variables, if option does1451 * not have a value from cli or client code.1452 *1453 * @api private1454 */1455 _parseOptionsEnv() {1456 this.options.forEach((option) => {1457 if (option.envVar && option.envVar in process.env) {1458 const optionKey = option.attributeName();1459 // env is second lowest priority source, above default1460 if (this.getOptionValue(optionKey) === undefined || this._optionValueSources[optionKey] === 'default') {1461 if (option.required || option.optional) { // option can take a value1462 // keep very simple, optional always takes value1463 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1464 } else { // boolean1465 // keep very simple, only care that envVar defined and not the value1466 this.emit(`optionEnv:${option.name()}`);1467 }1468 }1469 }1470 });1471 }14721473 /**1474 * Argument `name` is missing.1475 *1476 * @param {string} name1477 * @api private1478 */14791480 missingArgument(name) {1481 const message = `error: missing required argument '${name}'`;1482 this._displayError(1, 'commander.missingArgument', message);1483 };14841485 /**1486 * `Option` is missing an argument.1487 *1488 * @param {Option} option1489 * @api private1490 */14911492 optionMissingArgument(option) {1493 const message = `error: option '${option.flags}' argument missing`;1494 this._displayError(1, 'commander.optionMissingArgument', message);1495 };14961497 /**1498 * `Option` does not have a value, and is a mandatory option.1499 *1500 * @param {Option} option1501 * @api private1502 */15031504 missingMandatoryOptionValue(option) {1505 const message = `error: required option '${option.flags}' not specified`;1506 this._displayError(1, 'commander.missingMandatoryOptionValue', message);1507 };15081509 /**1510 * Unknown option `flag`.1511 *1512 * @param {string} flag1513 * @api private1514 */15151516 unknownOption(flag) {1517 if (this._allowUnknownOption) return;1518 let suggestion = '';15191520 if (flag.startsWith('--') && this._showSuggestionAfterError) {1521 // Looping to pick up the global options too1522 let candidateFlags = [];1523 let command = this;1524 do {1525 const moreFlags = command.createHelp().visibleOptions(command)1526 .filter(option => option.long)1527 .map(option => option.long);1528 candidateFlags = candidateFlags.concat(moreFlags);1529 command = command.parent;1530 } while (command && !command._enablePositionalOptions);1531 suggestion = suggestSimilar(flag, candidateFlags);1532 }15331534 const message = `error: unknown option '${flag}'${suggestion}`;1535 this._displayError(1, 'commander.unknownOption', message);1536 };15371538 /**1539 * Excess arguments, more than expected.1540 *1541 * @param {string[]} receivedArgs1542 * @api private1543 */15441545 _excessArguments(receivedArgs) {1546 if (this._allowExcessArguments) return;15471548 const expected = this._args.length;1549 const s = (expected === 1) ? '' : 's';1550 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1551 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1552 this._displayError(1, 'commander.excessArguments', message);1553 };15541555 /**1556 * Unknown command.1557 *1558 * @api private1559 */15601561 unknownCommand() {1562 const unknownName = this.args[0];1563 let suggestion = '';15641565 if (this._showSuggestionAfterError) {1566 const candidateNames = [];1567 this.createHelp().visibleCommands(this).forEach((command) => {1568 candidateNames.push(command.name());1569 // just visible alias1570 if (command.alias()) candidateNames.push(command.alias());1571 });1572 suggestion = suggestSimilar(unknownName, candidateNames);1573 }15741575 const message = `error: unknown command '${unknownName}'${suggestion}`;1576 this._displayError(1, 'commander.unknownCommand', message);1577 };15781579 /**1580 * Set the program version to `str`.1581 *1582 * This method auto-registers the "-V, --version" flag1583 * which will print the version number when passed.1584 *1585 * You can optionally supply the flags and description to override the defaults.1586 *1587 * @param {string} str1588 * @param {string} [flags]1589 * @param {string} [description]1590 * @return {this | string} `this` command for chaining, or version string if no arguments1591 */15921593 version(str, flags, description) {1594 if (str === undefined) return this._version;1595 this._version = str;1596 flags = flags || '-V, --version';1597 description = description || 'output the version number';1598 const versionOption = this.createOption(flags, description);1599 this._versionOptionName = versionOption.attributeName();1600 this.options.push(versionOption);1601 this.on('option:' + versionOption.name(), () => {1602 this._outputConfiguration.writeOut(`${str}\n`);1603 this._exit(0, 'commander.version', str);1604 });1605 return this;1606 };16071608 /**1609 * Set the description to `str`.1610 *1611 * @param {string} [str]1612 * @param {Object} [argsDescription]1613 * @return {string|Command}1614 */1615 description(str, argsDescription) {1616 if (str === undefined && argsDescription === undefined) return this._description;1617 this._description = str;1618 if (argsDescription) {1619 this._argsDescription = argsDescription;1620 }1621 return this;1622 };16231624 /**1625 * Set an alias for the command.1626 *1627 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1628 *1629 * @param {string} [alias]1630 * @return {string|Command}1631 */16321633 alias(alias) {1634 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility16351636 /** @type {Command} */1637 let command = this;1638 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1639 // assume adding alias for last added executable subcommand, rather than this1640 command = this.commands[this.commands.length - 1];1641 }16421643 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');16441645 command._aliases.push(alias);1646 return this;1647 };16481649 /**1650 * Set aliases for the command.1651 *1652 * Only the first alias is shown in the auto-generated help.1653 *1654 * @param {string[]} [aliases]1655 * @return {string[]|Command}1656 */16571658 aliases(aliases) {1659 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1660 if (aliases === undefined) return this._aliases;16611662 aliases.forEach((alias) => this.alias(alias));1663 return this;1664 };16651666 /**1667 * Set / get the command usage `str`.1668 *1669 * @param {string} [str]1670 * @return {String|Command}1671 */16721673 usage(str) {1674 if (str === undefined) {1675 if (this._usage) return this._usage;16761677 const args = this._args.map((arg) => {1678 return humanReadableArgName(arg);1679 });1680 return [].concat(1681 (this.options.length || this._hasHelpOption ? '[options]' : []),1682 (this.commands.length ? '[command]' : []),1683 (this._args.length ? args : [])1684 ).join(' ');1685 }16861687 this._usage = str;1688 return this;1689 };16901691 /**1692 * Get or set the name of the command1693 *1694 * @param {string} [str]1695 * @return {string|Command}1696 */16971698 name(str) {1699 if (str === undefined) return this._name;1700 this._name = str;1701 return this;1702 };17031704 /**1705 * Return program help documentation.1706 *1707 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1708 * @return {string}1709 */17101711 helpInformation(contextOptions) {1712 const helper = this.createHelp();1713 if (helper.helpWidth === undefined) {1714 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1715 }1716 return helper.formatHelp(this, helper);1717 };17181719 /**1720 * @api private1721 */17221723 _getHelpContext(contextOptions) {1724 contextOptions = contextOptions || {};1725 const context = { error: !!contextOptions.error };1726 let write;1727 if (context.error) {1728 write = (arg) => this._outputConfiguration.writeErr(arg);1729 } else {1730 write = (arg) => this._outputConfiguration.writeOut(arg);1731 }1732 context.write = contextOptions.write || write;1733 context.command = this;1734 return context;1735 }17361737 /**1738 * Output help information for this command.1739 *1740 * Outputs built-in help, and custom text added using `.addHelpText()`.1741 *1742 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1743 */17441745 outputHelp(contextOptions) {1746 let deprecatedCallback;1747 if (typeof contextOptions === 'function') {1748 deprecatedCallback = contextOptions;1749 contextOptions = undefined;1750 }1751 const context = this._getHelpContext(contextOptions);17521753 getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));1754 this.emit('beforeHelp', context);17551756 let helpInformation = this.helpInformation(context);1757 if (deprecatedCallback) {1758 helpInformation = deprecatedCallback(helpInformation);1759 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1760 throw new Error('outputHelp callback must return a string or a Buffer');1761 }1762 }1763 context.write(helpInformation);17641765 this.emit(this._helpLongFlag); // deprecated1766 this.emit('afterHelp', context);1767 getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));1768 };17691770 /**1771 * You can pass in flags and a description to override the help1772 * flags and help description for your command. Pass in false to1773 * disable the built-in help option.1774 *1775 * @param {string | boolean} [flags]1776 * @param {string} [description]1777 * @return {Command} `this` command for chaining1778 */17791780 helpOption(flags, description) {1781 if (typeof flags === 'boolean') {1782 this._hasHelpOption = flags;1783 return this;1784 }1785 this._helpFlags = flags || this._helpFlags;1786 this._helpDescription = description || this._helpDescription;17871788 const helpFlags = splitOptionFlags(this._helpFlags);1789 this._helpShortFlag = helpFlags.shortFlag;1790 this._helpLongFlag = helpFlags.longFlag;17911792 return this;1793 };17941795 /**1796 * Output help information and exit.1797 *1798 * Outputs built-in help, and custom text added using `.addHelpText()`.1799 *1800 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1801 */18021803 help(contextOptions) {1804 this.outputHelp(contextOptions);1805 let exitCode = process.exitCode || 0;1806 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1807 exitCode = 1;1808 }1809 // message: do not have all displayed text available so only passing placeholder.1810 this._exit(exitCode, 'commander.help', '(outputHelp)');1811 };18121813 /**1814 * Add additional text to be displayed with the built-in help.1815 *1816 * Position is 'before' or 'after' to affect just this command,1817 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1818 *1819 * @param {string} position - before or after built-in help1820 * @param {string | Function} text - string to add, or a function returning a string1821 * @return {Command} `this` command for chaining1822 */1823 addHelpText(position, text) {1824 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1825 if (!allowedValues.includes(position)) {1826 throw new Error(`Unexpected value for position to addHelpText.1827Expecting one of '${allowedValues.join("', '")}'`);1828 }1829 const helpEvent = `${position}Help`;1830 this.on(helpEvent, (context) => {1831 let helpStr;1832 if (typeof text === 'function') {1833 helpStr = text({ error: context.error, command: context.command });1834 } else {1835 helpStr = text;1836 }1837 // Ignore falsy value when nothing to output.1838 if (helpStr) {1839 context.write(`${helpStr}\n`);1840 }1841 });1842 return this;1843 }1844};18451846/**1847 * Output help information if help flags specified1848 *1849 * @param {Command} cmd - command to output help for1850 * @param {Array} args - array of options to search for help flags1851 * @api private1852 */18531854function outputHelpIfRequested(cmd, args) {1855 const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1856 if (helpOption) {1857 cmd.outputHelp();1858 // (Do not have all displayed text available so only passing placeholder.)1859 cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');1860 }1861}18621863/**1864 * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).1865 *1866 * @param {string[]} args - array of arguments from node.execArgv1867 * @returns {string[]}1868 * @api private1869 */18701871function incrementNodeInspectorPort(args) {1872 // Testing for these options:1873 // --inspect[=[host:]port]1874 // --inspect-brk[=[host:]port]1875 // --inspect-port=[host:]port1876 return args.map((arg) => {1877 if (!arg.startsWith('--inspect')) {1878 return arg;1879 }1880 let debugOption;1881 let debugHost = '127.0.0.1';1882 let debugPort = '9229';1883 let match;1884 if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {1885 // e.g. --inspect1886 debugOption = match[1];1887 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {1888 debugOption = match[1];1889 if (/^\d+$/.test(match[3])) {1890 // e.g. --inspect=12341891 debugPort = match[3];1892 } else {1893 // e.g. --inspect=localhost1894 debugHost = match[3];1895 }1896 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {1897 // e.g. --inspect=localhost:12341898 debugOption = match[1];1899 debugHost = match[3];1900 debugPort = match[4];1901 }19021903 if (debugOption && debugPort !== '0') {1904 return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;1905 }1906 return arg;1907 });1908}19091910/**1911 * @param {Command} startCommand1912 * @returns {Command[]}1913 * @api private1914 */19151916function getCommandAndParents(startCommand) {1917 const result = [];1918 for (let command = startCommand; command; command = command.parent) {1919 result.push(command);1920 }1921 return result;1922}19231924exports.Command = Command;