command.js
This file
Path
lib/command.js
2,509 lines · 76.4 KiB · JavaScript
Last changed by
Upgrade eslint and tselint (#2278)John Geebefore adoption7bc799b
History of this fileTake it
1const EventEmitter = require('node:events').EventEmitter;2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 /** @type {Command[]} */23 this.commands = [];24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;28 this._allowExcessArguments = true;29 /** @type {Argument[]} */30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old name32 /** @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, cli etc40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable44 this._executableDir = null; // custom search directory for subcommands45 this._defaultCommandName = null;46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';50 this._summary = '';51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arrays55 /** @type {(boolean | string)} */56 this._showHelpAfterError = false;57 this._showSuggestionAfterError = true;5859 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () =>64 process.stdout.isTTY ? process.stdout.columns : undefined,65 getErrHelpWidth: () =>66 process.stderr.isTTY ? process.stderr.columns : undefined,67 outputError: (str, write) => write(str),68 };6970 this._hidden = false;71 /** @type {(Option | null | undefined)} */72 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.73 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited74 /** @type {Command} */75 this._helpCommand = undefined; // lazy initialised, inherited76 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} `this` command for chaining86 */87 copyInheritedSettings(sourceCommand) {88 this._outputConfiguration = sourceCommand._outputConfiguration;89 this._helpOption = sourceCommand._helpOption;90 this._helpCommand = sourceCommand._helpCommand;91 this._helpConfiguration = sourceCommand._helpConfiguration;92 this._exitCallback = sourceCommand._exitCallback;93 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;94 this._combineFlagAndOptionalValue =95 sourceCommand._combineFlagAndOptionalValue;96 this._allowExcessArguments = sourceCommand._allowExcessArguments;97 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;98 this._showHelpAfterError = sourceCommand._showHelpAfterError;99 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;100101 return this;102 }103104 /**105 * @returns {Command[]}106 * @private107 */108109 _getCommandAndAncestors() {110 const result = [];111 // eslint-disable-next-line @typescript-eslint/no-this-alias112 for (let command = this; command; command = command.parent) {113 result.push(command);114 }115 return result;116 }117118 /**119 * Define a command.120 *121 * There are two styles of command: pay attention to where to put the description.122 *123 * @example124 * // Command implemented using action handler (description is supplied separately to `.command`)125 * program126 * .command('clone <source> [destination]')127 * .description('clone a repository into a newly created directory')128 * .action((source, destination) => {129 * console.log('clone command called');130 * });131 *132 * // Command implemented using separate executable file (description is second parameter to `.command`)133 * program134 * .command('start <service>', 'start named service')135 * .command('stop [service]', 'stop named service, or all if no name supplied');136 *137 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`138 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)139 * @param {object} [execOpts] - configuration options (for executable)140 * @return {Command} returns new command for action handler, or `this` for executable command141 */142143 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {144 let desc = actionOptsOrExecDesc;145 let opts = execOpts;146 if (typeof desc === 'object' && desc !== null) {147 opts = desc;148 desc = null;149 }150 opts = opts || {};151 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);152153 const cmd = this.createCommand(name);154 if (desc) {155 cmd.description(desc);156 cmd._executableHandler = true;157 }158 if (opts.isDefault) this._defaultCommandName = cmd._name;159 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden160 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor161 if (args) cmd.arguments(args);162 this._registerCommand(cmd);163 cmd.parent = this;164 cmd.copyInheritedSettings(this);165166 if (desc) return this;167 return cmd;168 }169170 /**171 * Factory routine to create a new unattached command.172 *173 * See .command() for creating an attached subcommand, which uses this routine to174 * create the command. You can override createCommand to customise subcommands.175 *176 * @param {string} [name]177 * @return {Command} new command178 */179180 createCommand(name) {181 return new Command(name);182 }183184 /**185 * You can customise the help with a subclass of Help by overriding createHelp,186 * or by overriding Help properties using configureHelp().187 *188 * @return {Help}189 */190191 createHelp() {192 return Object.assign(new Help(), this.configureHelp());193 }194195 /**196 * You can customise the help by overriding Help properties using configureHelp(),197 * or with a subclass of Help by overriding createHelp().198 *199 * @param {object} [configuration] - configuration options200 * @return {(Command | object)} `this` command for chaining, or stored configuration201 */202203 configureHelp(configuration) {204 if (configuration === undefined) return this._helpConfiguration;205206 this._helpConfiguration = configuration;207 return this;208 }209210 /**211 * The default output goes to stdout and stderr. You can customise this for special212 * applications. You can also customise the display of errors by overriding outputError.213 *214 * The configuration properties are all functions:215 *216 * // functions to change where being written, stdout and stderr217 * writeOut(str)218 * writeErr(str)219 * // matching functions to specify width for wrapping help220 * getOutHelpWidth()221 * getErrHelpWidth()222 * // functions based on what is being written out223 * outputError(str, write) // used for displaying errors, and not used for displaying help224 *225 * @param {object} [configuration] - configuration options226 * @return {(Command | object)} `this` command for chaining, or stored configuration227 */228229 configureOutput(configuration) {230 if (configuration === undefined) return this._outputConfiguration;231232 Object.assign(this._outputConfiguration, configuration);233 return this;234 }235236 /**237 * Display the help or a custom message after an error occurs.238 *239 * @param {(boolean|string)} [displayHelp]240 * @return {Command} `this` command for chaining241 */242 showHelpAfterError(displayHelp = true) {243 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;244 this._showHelpAfterError = displayHelp;245 return this;246 }247248 /**249 * Display suggestion of similar commands for unknown commands, or options for unknown options.250 *251 * @param {boolean} [displaySuggestion]252 * @return {Command} `this` command for chaining253 */254 showSuggestionAfterError(displaySuggestion = true) {255 this._showSuggestionAfterError = !!displaySuggestion;256 return this;257 }258259 /**260 * Add a prepared subcommand.261 *262 * See .command() for creating an attached subcommand which inherits settings from its parent.263 *264 * @param {Command} cmd - new subcommand265 * @param {object} [opts] - configuration options266 * @return {Command} `this` command for chaining267 */268269 addCommand(cmd, opts) {270 if (!cmd._name) {271 throw new Error(`Command passed to .addCommand() must have a name272- specify the name in Command constructor or using .name()`);273 }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._registerCommand(cmd);280 cmd.parent = this;281 cmd._checkForBrokenPassThrough();282283 return this;284 }285286 /**287 * Factory routine to create a new unattached argument.288 *289 * See .argument() for creating an attached argument, which uses this routine to290 * create the argument. You can override createArgument to return a custom argument.291 *292 * @param {string} name293 * @param {string} [description]294 * @return {Argument} new argument295 */296297 createArgument(name, description) {298 return new Argument(name, description);299 }300301 /**302 * Define argument syntax for command.303 *304 * The default is that the argument is required, and you can explicitly305 * indicate this with <> around the name. Put [] around the name for an optional argument.306 *307 * @example308 * program.argument('<input-file>');309 * program.argument('[output-file]');310 *311 * @param {string} name312 * @param {string} [description]313 * @param {(Function|*)} [fn] - custom argument processing function314 * @param {*} [defaultValue]315 * @return {Command} `this` command for chaining316 */317 argument(name, description, fn, defaultValue) {318 const argument = this.createArgument(name, description);319 if (typeof fn === 'function') {320 argument.default(defaultValue).argParser(fn);321 } else {322 argument.default(fn);323 }324 this.addArgument(argument);325 return this;326 }327328 /**329 * Define argument syntax for command, adding multiple at once (without descriptions).330 *331 * See also .argument().332 *333 * @example334 * program.arguments('<cmd> [env]');335 *336 * @param {string} names337 * @return {Command} `this` command for chaining338 */339340 arguments(names) {341 names342 .trim()343 .split(/ +/)344 .forEach((detail) => {345 this.argument(detail);346 });347 return this;348 }349350 /**351 * Define argument syntax for command, adding a prepared argument.352 *353 * @param {Argument} argument354 * @return {Command} `this` command for chaining355 */356 addArgument(argument) {357 const previousArgument = this.registeredArguments.slice(-1)[0];358 if (previousArgument && previousArgument.variadic) {359 throw new Error(360 `only the last argument can be variadic '${previousArgument.name()}'`,361 );362 }363 if (364 argument.required &&365 argument.defaultValue !== undefined &&366 argument.parseArg === undefined367 ) {368 throw new Error(369 `a default value for a required argument is never used: '${argument.name()}'`,370 );371 }372 this.registeredArguments.push(argument);373 return this;374 }375376 /**377 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.378 *379 * @example380 * program.helpCommand('help [cmd]');381 * program.helpCommand('help [cmd]', 'show help');382 * program.helpCommand(false); // suppress default help command383 * program.helpCommand(true); // add help command even if no subcommands384 *385 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added386 * @param {string} [description] - custom description387 * @return {Command} `this` command for chaining388 */389390 helpCommand(enableOrNameAndArgs, description) {391 if (typeof enableOrNameAndArgs === 'boolean') {392 this._addImplicitHelpCommand = enableOrNameAndArgs;393 return this;394 }395396 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';397 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);398 const helpDescription = description ?? 'display help for command';399400 const helpCommand = this.createCommand(helpName);401 helpCommand.helpOption(false);402 if (helpArgs) helpCommand.arguments(helpArgs);403 if (helpDescription) helpCommand.description(helpDescription);404405 this._addImplicitHelpCommand = true;406 this._helpCommand = helpCommand;407408 return this;409 }410411 /**412 * Add prepared custom help command.413 *414 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`415 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only416 * @return {Command} `this` command for chaining417 */418 addHelpCommand(helpCommand, deprecatedDescription) {419 // If not passed an object, call through to helpCommand for backwards compatibility,420 // as addHelpCommand was originally used like helpCommand is now.421 if (typeof helpCommand !== 'object') {422 this.helpCommand(helpCommand, deprecatedDescription);423 return this;424 }425426 this._addImplicitHelpCommand = true;427 this._helpCommand = helpCommand;428 return this;429 }430431 /**432 * Lazy create help command.433 *434 * @return {(Command|null)}435 * @package436 */437 _getHelpCommand() {438 const hasImplicitHelpCommand =439 this._addImplicitHelpCommand ??440 (this.commands.length &&441 !this._actionHandler &&442 !this._findCommand('help'));443444 if (hasImplicitHelpCommand) {445 if (this._helpCommand === undefined) {446 this.helpCommand(undefined, undefined); // use default name and description447 }448 return this._helpCommand;449 }450 return null;451 }452453 /**454 * Add hook for life cycle event.455 *456 * @param {string} event457 * @param {Function} listener458 * @return {Command} `this` command for chaining459 */460461 hook(event, listener) {462 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];463 if (!allowedValues.includes(event)) {464 throw new Error(`Unexpected value for event passed to hook : '${event}'.465Expecting one of '${allowedValues.join("', '")}'`);466 }467 if (this._lifeCycleHooks[event]) {468 this._lifeCycleHooks[event].push(listener);469 } else {470 this._lifeCycleHooks[event] = [listener];471 }472 return this;473 }474475 /**476 * Register callback to use as replacement for calling process.exit.477 *478 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing479 * @return {Command} `this` command for chaining480 */481482 exitOverride(fn) {483 if (fn) {484 this._exitCallback = fn;485 } else {486 this._exitCallback = (err) => {487 if (err.code !== 'commander.executeSubCommandAsync') {488 throw err;489 } else {490 // Async callback from spawn events, not useful to throw.491 }492 };493 }494 return this;495 }496497 /**498 * Call process.exit, and _exitCallback if defined.499 *500 * @param {number} exitCode exit code for using with process.exit501 * @param {string} code an id string representing the error502 * @param {string} message human-readable description of the error503 * @return never504 * @private505 */506507 _exit(exitCode, code, message) {508 if (this._exitCallback) {509 this._exitCallback(new CommanderError(exitCode, code, message));510 // Expecting this line is not reached.511 }512 process.exit(exitCode);513 }514515 /**516 * Register callback `fn` for the command.517 *518 * @example519 * program520 * .command('serve')521 * .description('start service')522 * .action(function() {523 * // do work here524 * });525 *526 * @param {Function} fn527 * @return {Command} `this` command for chaining528 */529530 action(fn) {531 const listener = (args) => {532 // The .action callback takes an extra parameter which is the command or options.533 const expectedArgsCount = this.registeredArguments.length;534 const actionArgs = args.slice(0, expectedArgsCount);535 if (this._storeOptionsAsProperties) {536 actionArgs[expectedArgsCount] = this; // backwards compatible "options"537 } else {538 actionArgs[expectedArgsCount] = this.opts();539 }540 actionArgs.push(this);541542 return fn.apply(this, actionArgs);543 };544 this._actionHandler = listener;545 return this;546 }547548 /**549 * Factory routine to create a new unattached option.550 *551 * See .option() for creating an attached option, which uses this routine to552 * create the option. You can override createOption to return a custom option.553 *554 * @param {string} flags555 * @param {string} [description]556 * @return {Option} new option557 */558559 createOption(flags, description) {560 return new Option(flags, description);561 }562563 /**564 * Wrap parseArgs to catch 'commander.invalidArgument'.565 *566 * @param {(Option | Argument)} target567 * @param {string} value568 * @param {*} previous569 * @param {string} invalidArgumentMessage570 * @private571 */572573 _callParseArg(target, value, previous, invalidArgumentMessage) {574 try {575 return target.parseArg(value, previous);576 } catch (err) {577 if (err.code === 'commander.invalidArgument') {578 const message = `${invalidArgumentMessage} ${err.message}`;579 this.error(message, { exitCode: err.exitCode, code: err.code });580 }581 throw err;582 }583 }584585 /**586 * Check for option flag conflicts.587 * Register option if no conflicts found, or throw on conflict.588 *589 * @param {Option} option590 * @private591 */592593 _registerOption(option) {594 const matchingOption =595 (option.short && this._findOption(option.short)) ||596 (option.long && this._findOption(option.long));597 if (matchingOption) {598 const matchingFlag =599 option.long && this._findOption(option.long)600 ? option.long601 : option.short;602 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'603- already used by option '${matchingOption.flags}'`);604 }605606 this.options.push(option);607 }608609 /**610 * Check for command name and alias conflicts with existing commands.611 * Register command if no conflicts found, or throw on conflict.612 *613 * @param {Command} command614 * @private615 */616617 _registerCommand(command) {618 const knownBy = (cmd) => {619 return [cmd.name()].concat(cmd.aliases());620 };621622 const alreadyUsed = knownBy(command).find((name) =>623 this._findCommand(name),624 );625 if (alreadyUsed) {626 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');627 const newCmd = knownBy(command).join('|');628 throw new Error(629 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,630 );631 }632633 this.commands.push(command);634 }635636 /**637 * Add an option.638 *639 * @param {Option} option640 * @return {Command} `this` command for chaining641 */642 addOption(option) {643 this._registerOption(option);644645 const oname = option.name();646 const name = option.attributeName();647648 // store default value649 if (option.negate) {650 // --no-foo is special and defaults foo to true, unless a --foo option is already defined651 const positiveLongFlag = option.long.replace(/^--no-/, '--');652 if (!this._findOption(positiveLongFlag)) {653 this.setOptionValueWithSource(654 name,655 option.defaultValue === undefined ? true : option.defaultValue,656 'default',657 );658 }659 } else if (option.defaultValue !== undefined) {660 this.setOptionValueWithSource(name, option.defaultValue, 'default');661 }662663 // handler for cli and env supplied values664 const handleOptionValue = (val, invalidValueMessage, valueSource) => {665 // val is null for optional option used without an optional-argument.666 // val is undefined for boolean and negated option.667 if (val == null && option.presetArg !== undefined) {668 val = option.presetArg;669 }670671 // custom processing672 const oldValue = this.getOptionValue(name);673 if (val !== null && option.parseArg) {674 val = this._callParseArg(option, val, oldValue, invalidValueMessage);675 } else if (val !== null && option.variadic) {676 val = option._concatValue(val, oldValue);677 }678679 // Fill-in appropriate missing values. Long winded but easy to follow.680 if (val == null) {681 if (option.negate) {682 val = false;683 } else if (option.isBoolean() || option.optional) {684 val = true;685 } else {686 val = ''; // not normal, parseArg might have failed or be a mock function for testing687 }688 }689 this.setOptionValueWithSource(name, val, valueSource);690 };691692 this.on('option:' + oname, (val) => {693 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;694 handleOptionValue(val, invalidValueMessage, 'cli');695 });696697 if (option.envVar) {698 this.on('optionEnv:' + oname, (val) => {699 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;700 handleOptionValue(val, invalidValueMessage, 'env');701 });702 }703704 return this;705 }706707 /**708 * Internal implementation shared by .option() and .requiredOption()709 *710 * @return {Command} `this` command for chaining711 * @private712 */713 _optionEx(config, flags, description, fn, defaultValue) {714 if (typeof flags === 'object' && flags instanceof Option) {715 throw new Error(716 'To add an Option object use addOption() instead of option() or requiredOption()',717 );718 }719 const option = this.createOption(flags, description);720 option.makeOptionMandatory(!!config.mandatory);721 if (typeof fn === 'function') {722 option.default(defaultValue).argParser(fn);723 } else if (fn instanceof RegExp) {724 // deprecated725 const regex = fn;726 fn = (val, def) => {727 const m = regex.exec(val);728 return m ? m[0] : def;729 };730 option.default(defaultValue).argParser(fn);731 } else {732 option.default(fn);733 }734735 return this.addOption(option);736 }737738 /**739 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.740 *741 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required742 * option-argument is indicated by `<>` and an optional option-argument by `[]`.743 *744 * See the README for more details, and see also addOption() and requiredOption().745 *746 * @example747 * program748 * .option('-p, --pepper', 'add pepper')749 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument750 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default751 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function752 *753 * @param {string} flags754 * @param {string} [description]755 * @param {(Function|*)} [parseArg] - custom option processing function or default value756 * @param {*} [defaultValue]757 * @return {Command} `this` command for chaining758 */759760 option(flags, description, parseArg, defaultValue) {761 return this._optionEx({}, flags, description, parseArg, defaultValue);762 }763764 /**765 * Add a required option which must have a value after parsing. This usually means766 * the option must be specified on the command line. (Otherwise the same as .option().)767 *768 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.769 *770 * @param {string} flags771 * @param {string} [description]772 * @param {(Function|*)} [parseArg] - custom option processing function or default value773 * @param {*} [defaultValue]774 * @return {Command} `this` command for chaining775 */776777 requiredOption(flags, description, parseArg, defaultValue) {778 return this._optionEx(779 { mandatory: true },780 flags,781 description,782 parseArg,783 defaultValue,784 );785 }786787 /**788 * Alter parsing of short flags with optional values.789 *790 * @example791 * // for `.option('-f,--flag [value]'):792 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour793 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`794 *795 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.796 * @return {Command} `this` command for chaining797 */798 combineFlagAndOptionalValue(combine = true) {799 this._combineFlagAndOptionalValue = !!combine;800 return this;801 }802803 /**804 * Allow unknown options on the command line.805 *806 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.807 * @return {Command} `this` command for chaining808 */809 allowUnknownOption(allowUnknown = true) {810 this._allowUnknownOption = !!allowUnknown;811 return this;812 }813814 /**815 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.816 *817 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.818 * @return {Command} `this` command for chaining819 */820 allowExcessArguments(allowExcess = true) {821 this._allowExcessArguments = !!allowExcess;822 return this;823 }824825 /**826 * Enable positional options. Positional means global options are specified before subcommands which lets827 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.828 * The default behaviour is non-positional and global options may appear anywhere on the command line.829 *830 * @param {boolean} [positional]831 * @return {Command} `this` command for chaining832 */833 enablePositionalOptions(positional = true) {834 this._enablePositionalOptions = !!positional;835 return this;836 }837838 /**839 * Pass through options that come after command-arguments rather than treat them as command-options,840 * so actual command-options come before command-arguments. Turning this on for a subcommand requires841 * positional options to have been enabled on the program (parent commands).842 * The default behaviour is non-positional and options may appear before or after command-arguments.843 *844 * @param {boolean} [passThrough] for unknown options.845 * @return {Command} `this` command for chaining846 */847 passThroughOptions(passThrough = true) {848 this._passThroughOptions = !!passThrough;849 this._checkForBrokenPassThrough();850 return this;851 }852853 /**854 * @private855 */856857 _checkForBrokenPassThrough() {858 if (859 this.parent &&860 this._passThroughOptions &&861 !this.parent._enablePositionalOptions862 ) {863 throw new Error(864 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,865 );866 }867 }868869 /**870 * Whether to store option values as properties on command object,871 * or store separately (specify false). In both cases the option values can be accessed using .opts().872 *873 * @param {boolean} [storeAsProperties=true]874 * @return {Command} `this` command for chaining875 */876877 storeOptionsAsProperties(storeAsProperties = true) {878 if (this.options.length) {879 throw new Error('call .storeOptionsAsProperties() before adding options');880 }881 if (Object.keys(this._optionValues).length) {882 throw new Error(883 'call .storeOptionsAsProperties() before setting option values',884 );885 }886 this._storeOptionsAsProperties = !!storeAsProperties;887 return this;888 }889890 /**891 * Retrieve option value.892 *893 * @param {string} key894 * @return {object} value895 */896897 getOptionValue(key) {898 if (this._storeOptionsAsProperties) {899 return this[key];900 }901 return this._optionValues[key];902 }903904 /**905 * Store option value.906 *907 * @param {string} key908 * @param {object} value909 * @return {Command} `this` command for chaining910 */911912 setOptionValue(key, value) {913 return this.setOptionValueWithSource(key, value, undefined);914 }915916 /**917 * Store option value and where the value came from.918 *919 * @param {string} key920 * @param {object} value921 * @param {string} source - expected values are default/config/env/cli/implied922 * @return {Command} `this` command for chaining923 */924925 setOptionValueWithSource(key, value, source) {926 if (this._storeOptionsAsProperties) {927 this[key] = value;928 } else {929 this._optionValues[key] = value;930 }931 this._optionValueSources[key] = source;932 return this;933 }934935 /**936 * Get source of option value.937 * Expected values are default | config | env | cli | implied938 *939 * @param {string} key940 * @return {string}941 */942943 getOptionValueSource(key) {944 return this._optionValueSources[key];945 }946947 /**948 * Get source of option value. See also .optsWithGlobals().949 * Expected values are default | config | env | cli | implied950 *951 * @param {string} key952 * @return {string}953 */954955 getOptionValueSourceWithGlobals(key) {956 // global overwrites local, like optsWithGlobals957 let source;958 this._getCommandAndAncestors().forEach((cmd) => {959 if (cmd.getOptionValueSource(key) !== undefined) {960 source = cmd.getOptionValueSource(key);961 }962 });963 return source;964 }965966 /**967 * Get user arguments from implied or explicit arguments.968 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.969 *970 * @private971 */972973 _prepareUserArgs(argv, parseOptions) {974 if (argv !== undefined && !Array.isArray(argv)) {975 throw new Error('first parameter to parse must be array or undefined');976 }977 parseOptions = parseOptions || {};978979 // auto-detect argument conventions if nothing supplied980 if (argv === undefined && parseOptions.from === undefined) {981 if (process.versions?.electron) {982 parseOptions.from = 'electron';983 }984 // check node specific options for scenarios where user CLI args follow executable without scriptname985 const execArgv = process.execArgv ?? [];986 if (987 execArgv.includes('-e') ||988 execArgv.includes('--eval') ||989 execArgv.includes('-p') ||990 execArgv.includes('--print')991 ) {992 parseOptions.from = 'eval'; // internal usage, not documented993 }994 }995996 // default to using process.argv997 if (argv === undefined) {998 argv = process.argv;999 }1000 this.rawArgs = argv.slice();10011002 // extract the user args and scriptPath1003 let userArgs;1004 switch (parseOptions.from) {1005 case undefined:1006 case 'node':1007 this._scriptPath = argv[1];1008 userArgs = argv.slice(2);1009 break;1010 case 'electron':1011 // @ts-ignore: because defaultApp is an unknown property1012 if (process.defaultApp) {1013 this._scriptPath = argv[1];1014 userArgs = argv.slice(2);1015 } else {1016 userArgs = argv.slice(1);1017 }1018 break;1019 case 'user':1020 userArgs = argv.slice(0);1021 break;1022 case 'eval':1023 userArgs = argv.slice(1);1024 break;1025 default:1026 throw new Error(1027 `unexpected parse option { from: '${parseOptions.from}' }`,1028 );1029 }10301031 // Find default name for program from arguments.1032 if (!this._name && this._scriptPath)1033 this.nameFromFilename(this._scriptPath);1034 this._name = this._name || 'program';10351036 return userArgs;1037 }10381039 /**1040 * Parse `argv`, setting options and invoking commands when defined.1041 *1042 * Use parseAsync instead of parse if any of your action handlers are async.1043 *1044 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1045 *1046 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1047 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1048 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1049 * - `'user'`: just user arguments1050 *1051 * @example1052 * program.parse(); // parse process.argv and auto-detect electron and special node flags1053 * program.parse(process.argv); // assume argv[0] is app and argv[1] is script1054 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1055 *1056 * @param {string[]} [argv] - optional, defaults to process.argv1057 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1058 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1059 * @return {Command} `this` command for chaining1060 */10611062 parse(argv, parseOptions) {1063 const userArgs = this._prepareUserArgs(argv, parseOptions);1064 this._parseCommand([], userArgs);10651066 return this;1067 }10681069 /**1070 * Parse `argv`, setting options and invoking commands when defined.1071 *1072 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1073 *1074 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1075 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1076 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1077 * - `'user'`: just user arguments1078 *1079 * @example1080 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1081 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script1082 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1083 *1084 * @param {string[]} [argv]1085 * @param {object} [parseOptions]1086 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1087 * @return {Promise}1088 */10891090 async parseAsync(argv, parseOptions) {1091 const userArgs = this._prepareUserArgs(argv, parseOptions);1092 await this._parseCommand([], userArgs);10931094 return this;1095 }10961097 /**1098 * Execute a sub-command executable.1099 *1100 * @private1101 */11021103 _executeSubCommand(subcommand, args) {1104 args = args.slice();1105 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1106 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];11071108 function findFile(baseDir, baseName) {1109 // Look for specified file1110 const localBin = path.resolve(baseDir, baseName);1111 if (fs.existsSync(localBin)) return localBin;11121113 // Stop looking if candidate already has an expected extension.1114 if (sourceExt.includes(path.extname(baseName))) return undefined;11151116 // Try all the extensions.1117 const foundExt = sourceExt.find((ext) =>1118 fs.existsSync(`${localBin}${ext}`),1119 );1120 if (foundExt) return `${localBin}${foundExt}`;11211122 return undefined;1123 }11241125 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1126 this._checkForMissingMandatoryOptions();1127 this._checkForConflictingOptions();11281129 // executableFile and executableDir might be full path, or just a name1130 let executableFile =1131 subcommand._executableFile || `${this._name}-${subcommand._name}`;1132 let executableDir = this._executableDir || '';1133 if (this._scriptPath) {1134 let resolvedScriptPath; // resolve possible symlink for installed npm binary1135 try {1136 resolvedScriptPath = fs.realpathSync(this._scriptPath);1137 } catch {1138 resolvedScriptPath = this._scriptPath;1139 }1140 executableDir = path.resolve(1141 path.dirname(resolvedScriptPath),1142 executableDir,1143 );1144 }11451146 // Look for a local file in preference to a command in PATH.1147 if (executableDir) {1148 let localFile = findFile(executableDir, executableFile);11491150 // Legacy search using prefix of script name instead of command name1151 if (!localFile && !subcommand._executableFile && this._scriptPath) {1152 const legacyName = path.basename(1153 this._scriptPath,1154 path.extname(this._scriptPath),1155 );1156 if (legacyName !== this._name) {1157 localFile = findFile(1158 executableDir,1159 `${legacyName}-${subcommand._name}`,1160 );1161 }1162 }1163 executableFile = localFile || executableFile;1164 }11651166 launchWithNode = sourceExt.includes(path.extname(executableFile));11671168 let proc;1169 if (process.platform !== 'win32') {1170 if (launchWithNode) {1171 args.unshift(executableFile);1172 // add executable arguments to spawn1173 args = incrementNodeInspectorPort(process.execArgv).concat(args);11741175 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1176 } else {1177 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1178 }1179 } else {1180 args.unshift(executableFile);1181 // add executable arguments to spawn1182 args = incrementNodeInspectorPort(process.execArgv).concat(args);1183 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1184 }11851186 if (!proc.killed) {1187 // testing mainly to avoid leak warnings during unit tests with mocked spawn1188 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1189 signals.forEach((signal) => {1190 process.on(signal, () => {1191 if (proc.killed === false && proc.exitCode === null) {1192 // @ts-ignore because signals not typed to known strings1193 proc.kill(signal);1194 }1195 });1196 });1197 }11981199 // By default terminate process when spawned process terminates.1200 const exitCallback = this._exitCallback;1201 proc.on('close', (code) => {1202 code = code ?? 1; // code is null if spawned process terminated due to a signal1203 if (!exitCallback) {1204 process.exit(code);1205 } else {1206 exitCallback(1207 new CommanderError(1208 code,1209 'commander.executeSubCommandAsync',1210 '(close)',1211 ),1212 );1213 }1214 });1215 proc.on('error', (err) => {1216 // @ts-ignore: because err.code is an unknown property1217 if (err.code === 'ENOENT') {1218 const executableDirMessage = executableDir1219 ? `searched for local subcommand relative to directory '${executableDir}'`1220 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1221 const executableMissing = `'${executableFile}' does not exist1222 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1223 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1224 - ${executableDirMessage}`;1225 throw new Error(executableMissing);1226 // @ts-ignore: because err.code is an unknown property1227 } else if (err.code === 'EACCES') {1228 throw new Error(`'${executableFile}' not executable`);1229 }1230 if (!exitCallback) {1231 process.exit(1);1232 } else {1233 const wrappedError = new CommanderError(1234 1,1235 'commander.executeSubCommandAsync',1236 '(error)',1237 );1238 wrappedError.nestedError = err;1239 exitCallback(wrappedError);1240 }1241 });12421243 // Store the reference to the child process1244 this.runningCommand = proc;1245 }12461247 /**1248 * @private1249 */12501251 _dispatchSubcommand(commandName, operands, unknown) {1252 const subCommand = this._findCommand(commandName);1253 if (!subCommand) this.help({ error: true });12541255 let promiseChain;1256 promiseChain = this._chainOrCallSubCommandHook(1257 promiseChain,1258 subCommand,1259 'preSubcommand',1260 );1261 promiseChain = this._chainOrCall(promiseChain, () => {1262 if (subCommand._executableHandler) {1263 this._executeSubCommand(subCommand, operands.concat(unknown));1264 } else {1265 return subCommand._parseCommand(operands, unknown);1266 }1267 });1268 return promiseChain;1269 }12701271 /**1272 * Invoke help directly if possible, or dispatch if necessary.1273 * e.g. help foo1274 *1275 * @private1276 */12771278 _dispatchHelpCommand(subcommandName) {1279 if (!subcommandName) {1280 this.help();1281 }1282 const subCommand = this._findCommand(subcommandName);1283 if (subCommand && !subCommand._executableHandler) {1284 subCommand.help();1285 }12861287 // Fallback to parsing the help flag to invoke the help.1288 return this._dispatchSubcommand(1289 subcommandName,1290 [],1291 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1292 );1293 }12941295 /**1296 * Check this.args against expected this.registeredArguments.1297 *1298 * @private1299 */13001301 _checkNumberOfArguments() {1302 // too few1303 this.registeredArguments.forEach((arg, i) => {1304 if (arg.required && this.args[i] == null) {1305 this.missingArgument(arg.name());1306 }1307 });1308 // too many1309 if (1310 this.registeredArguments.length > 0 &&1311 this.registeredArguments[this.registeredArguments.length - 1].variadic1312 ) {1313 return;1314 }1315 if (this.args.length > this.registeredArguments.length) {1316 this._excessArguments(this.args);1317 }1318 }13191320 /**1321 * Process this.args using this.registeredArguments and save as this.processedArgs!1322 *1323 * @private1324 */13251326 _processArguments() {1327 const myParseArg = (argument, value, previous) => {1328 // Extra processing for nice error message on parsing failure.1329 let parsedValue = value;1330 if (value !== null && argument.parseArg) {1331 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1332 parsedValue = this._callParseArg(1333 argument,1334 value,1335 previous,1336 invalidValueMessage,1337 );1338 }1339 return parsedValue;1340 };13411342 this._checkNumberOfArguments();13431344 const processedArgs = [];1345 this.registeredArguments.forEach((declaredArg, index) => {1346 let value = declaredArg.defaultValue;1347 if (declaredArg.variadic) {1348 // Collect together remaining arguments for passing together as an array.1349 if (index < this.args.length) {1350 value = this.args.slice(index);1351 if (declaredArg.parseArg) {1352 value = value.reduce((processed, v) => {1353 return myParseArg(declaredArg, v, processed);1354 }, declaredArg.defaultValue);1355 }1356 } else if (value === undefined) {1357 value = [];1358 }1359 } else if (index < this.args.length) {1360 value = this.args[index];1361 if (declaredArg.parseArg) {1362 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1363 }1364 }1365 processedArgs[index] = value;1366 });1367 this.processedArgs = processedArgs;1368 }13691370 /**1371 * Once we have a promise we chain, but call synchronously until then.1372 *1373 * @param {(Promise|undefined)} promise1374 * @param {Function} fn1375 * @return {(Promise|undefined)}1376 * @private1377 */13781379 _chainOrCall(promise, fn) {1380 // thenable1381 if (promise && promise.then && typeof promise.then === 'function') {1382 // already have a promise, chain callback1383 return promise.then(() => fn());1384 }1385 // callback might return a promise1386 return fn();1387 }13881389 /**1390 *1391 * @param {(Promise|undefined)} promise1392 * @param {string} event1393 * @return {(Promise|undefined)}1394 * @private1395 */13961397 _chainOrCallHooks(promise, event) {1398 let result = promise;1399 const hooks = [];1400 this._getCommandAndAncestors()1401 .reverse()1402 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1403 .forEach((hookedCommand) => {1404 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1405 hooks.push({ hookedCommand, callback });1406 });1407 });1408 if (event === 'postAction') {1409 hooks.reverse();1410 }14111412 hooks.forEach((hookDetail) => {1413 result = this._chainOrCall(result, () => {1414 return hookDetail.callback(hookDetail.hookedCommand, this);1415 });1416 });1417 return result;1418 }14191420 /**1421 *1422 * @param {(Promise|undefined)} promise1423 * @param {Command} subCommand1424 * @param {string} event1425 * @return {(Promise|undefined)}1426 * @private1427 */14281429 _chainOrCallSubCommandHook(promise, subCommand, event) {1430 let result = promise;1431 if (this._lifeCycleHooks[event] !== undefined) {1432 this._lifeCycleHooks[event].forEach((hook) => {1433 result = this._chainOrCall(result, () => {1434 return hook(this, subCommand);1435 });1436 });1437 }1438 return result;1439 }14401441 /**1442 * Process arguments in context of this command.1443 * Returns action result, in case it is a promise.1444 *1445 * @private1446 */14471448 _parseCommand(operands, unknown) {1449 const parsed = this.parseOptions(unknown);1450 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1451 this._parseOptionsImplied();1452 operands = operands.concat(parsed.operands);1453 unknown = parsed.unknown;1454 this.args = operands.concat(unknown);14551456 if (operands && this._findCommand(operands[0])) {1457 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1458 }1459 if (1460 this._getHelpCommand() &&1461 operands[0] === this._getHelpCommand().name()1462 ) {1463 return this._dispatchHelpCommand(operands[1]);1464 }1465 if (this._defaultCommandName) {1466 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1467 return this._dispatchSubcommand(1468 this._defaultCommandName,1469 operands,1470 unknown,1471 );1472 }1473 if (1474 this.commands.length &&1475 this.args.length === 0 &&1476 !this._actionHandler &&1477 !this._defaultCommandName1478 ) {1479 // probably missing subcommand and no handler, user needs help (and exit)1480 this.help({ error: true });1481 }14821483 this._outputHelpIfRequested(parsed.unknown);1484 this._checkForMissingMandatoryOptions();1485 this._checkForConflictingOptions();14861487 // We do not always call this check to avoid masking a "better" error, like unknown command.1488 const checkForUnknownOptions = () => {1489 if (parsed.unknown.length > 0) {1490 this.unknownOption(parsed.unknown[0]);1491 }1492 };14931494 const commandEvent = `command:${this.name()}`;1495 if (this._actionHandler) {1496 checkForUnknownOptions();1497 this._processArguments();14981499 let promiseChain;1500 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1501 promiseChain = this._chainOrCall(promiseChain, () =>1502 this._actionHandler(this.processedArgs),1503 );1504 if (this.parent) {1505 promiseChain = this._chainOrCall(promiseChain, () => {1506 this.parent.emit(commandEvent, operands, unknown); // legacy1507 });1508 }1509 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1510 return promiseChain;1511 }1512 if (this.parent && this.parent.listenerCount(commandEvent)) {1513 checkForUnknownOptions();1514 this._processArguments();1515 this.parent.emit(commandEvent, operands, unknown); // legacy1516 } else if (operands.length) {1517 if (this._findCommand('*')) {1518 // legacy default command1519 return this._dispatchSubcommand('*', operands, unknown);1520 }1521 if (this.listenerCount('command:*')) {1522 // skip option check, emit event for possible misspelling suggestion1523 this.emit('command:*', operands, unknown);1524 } else if (this.commands.length) {1525 this.unknownCommand();1526 } else {1527 checkForUnknownOptions();1528 this._processArguments();1529 }1530 } else if (this.commands.length) {1531 checkForUnknownOptions();1532 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1533 this.help({ error: true });1534 } else {1535 checkForUnknownOptions();1536 this._processArguments();1537 // fall through for caller to handle after calling .parse()1538 }1539 }15401541 /**1542 * Find matching command.1543 *1544 * @private1545 * @return {Command | undefined}1546 */1547 _findCommand(name) {1548 if (!name) return undefined;1549 return this.commands.find(1550 (cmd) => cmd._name === name || cmd._aliases.includes(name),1551 );1552 }15531554 /**1555 * Return an option matching `arg` if any.1556 *1557 * @param {string} arg1558 * @return {Option}1559 * @package1560 */15611562 _findOption(arg) {1563 return this.options.find((option) => option.is(arg));1564 }15651566 /**1567 * Display an error message if a mandatory option does not have a value.1568 * Called after checking for help flags in leaf subcommand.1569 *1570 * @private1571 */15721573 _checkForMissingMandatoryOptions() {1574 // Walk up hierarchy so can call in subcommand after checking for displaying help.1575 this._getCommandAndAncestors().forEach((cmd) => {1576 cmd.options.forEach((anOption) => {1577 if (1578 anOption.mandatory &&1579 cmd.getOptionValue(anOption.attributeName()) === undefined1580 ) {1581 cmd.missingMandatoryOptionValue(anOption);1582 }1583 });1584 });1585 }15861587 /**1588 * Display an error message if conflicting options are used together in this.1589 *1590 * @private1591 */1592 _checkForConflictingLocalOptions() {1593 const definedNonDefaultOptions = this.options.filter((option) => {1594 const optionKey = option.attributeName();1595 if (this.getOptionValue(optionKey) === undefined) {1596 return false;1597 }1598 return this.getOptionValueSource(optionKey) !== 'default';1599 });16001601 const optionsWithConflicting = definedNonDefaultOptions.filter(1602 (option) => option.conflictsWith.length > 0,1603 );16041605 optionsWithConflicting.forEach((option) => {1606 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1607 option.conflictsWith.includes(defined.attributeName()),1608 );1609 if (conflictingAndDefined) {1610 this._conflictingOption(option, conflictingAndDefined);1611 }1612 });1613 }16141615 /**1616 * Display an error message if conflicting options are used together.1617 * Called after checking for help flags in leaf subcommand.1618 *1619 * @private1620 */1621 _checkForConflictingOptions() {1622 // Walk up hierarchy so can call in subcommand after checking for displaying help.1623 this._getCommandAndAncestors().forEach((cmd) => {1624 cmd._checkForConflictingLocalOptions();1625 });1626 }16271628 /**1629 * Parse options from `argv` removing known options,1630 * and return argv split into operands and unknown arguments.1631 *1632 * Examples:1633 *1634 * argv => operands, unknown1635 * --known kkk op => [op], []1636 * op --known kkk => [op], []1637 * sub --unknown uuu op => [sub], [--unknown uuu op]1638 * sub -- --unknown uuu op => [sub --unknown uuu op], []1639 *1640 * @param {string[]} argv1641 * @return {{operands: string[], unknown: string[]}}1642 */16431644 parseOptions(argv) {1645 const operands = []; // operands, not options or values1646 const unknown = []; // first unknown option and remaining unknown args1647 let dest = operands;1648 const args = argv.slice();16491650 function maybeOption(arg) {1651 return arg.length > 1 && arg[0] === '-';1652 }16531654 // parse options1655 let activeVariadicOption = null;1656 while (args.length) {1657 const arg = args.shift();16581659 // literal1660 if (arg === '--') {1661 if (dest === unknown) dest.push(arg);1662 dest.push(...args);1663 break;1664 }16651666 if (activeVariadicOption && !maybeOption(arg)) {1667 this.emit(`option:${activeVariadicOption.name()}`, arg);1668 continue;1669 }1670 activeVariadicOption = null;16711672 if (maybeOption(arg)) {1673 const option = this._findOption(arg);1674 // recognised option, call listener to assign value with possible custom processing1675 if (option) {1676 if (option.required) {1677 const value = args.shift();1678 if (value === undefined) this.optionMissingArgument(option);1679 this.emit(`option:${option.name()}`, value);1680 } else if (option.optional) {1681 let value = null;1682 // historical behaviour is optional value is following arg unless an option1683 if (args.length > 0 && !maybeOption(args[0])) {1684 value = args.shift();1685 }1686 this.emit(`option:${option.name()}`, value);1687 } else {1688 // boolean flag1689 this.emit(`option:${option.name()}`);1690 }1691 activeVariadicOption = option.variadic ? option : null;1692 continue;1693 }1694 }16951696 // Look for combo options following single dash, eat first one if known.1697 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1698 const option = this._findOption(`-${arg[1]}`);1699 if (option) {1700 if (1701 option.required ||1702 (option.optional && this._combineFlagAndOptionalValue)1703 ) {1704 // option with value following in same argument1705 this.emit(`option:${option.name()}`, arg.slice(2));1706 } else {1707 // boolean option, emit and put back remainder of arg for further processing1708 this.emit(`option:${option.name()}`);1709 args.unshift(`-${arg.slice(2)}`);1710 }1711 continue;1712 }1713 }17141715 // Look for known long flag with value, like --foo=bar1716 if (/^--[^=]+=/.test(arg)) {1717 const index = arg.indexOf('=');1718 const option = this._findOption(arg.slice(0, index));1719 if (option && (option.required || option.optional)) {1720 this.emit(`option:${option.name()}`, arg.slice(index + 1));1721 continue;1722 }1723 }17241725 // Not a recognised option by this command.1726 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.17271728 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1729 if (maybeOption(arg)) {1730 dest = unknown;1731 }17321733 // If using positionalOptions, stop processing our options at subcommand.1734 if (1735 (this._enablePositionalOptions || this._passThroughOptions) &&1736 operands.length === 0 &&1737 unknown.length === 01738 ) {1739 if (this._findCommand(arg)) {1740 operands.push(arg);1741 if (args.length > 0) unknown.push(...args);1742 break;1743 } else if (1744 this._getHelpCommand() &&1745 arg === this._getHelpCommand().name()1746 ) {1747 operands.push(arg);1748 if (args.length > 0) operands.push(...args);1749 break;1750 } else if (this._defaultCommandName) {1751 unknown.push(arg);1752 if (args.length > 0) unknown.push(...args);1753 break;1754 }1755 }17561757 // If using passThroughOptions, stop processing options at first command-argument.1758 if (this._passThroughOptions) {1759 dest.push(arg);1760 if (args.length > 0) dest.push(...args);1761 break;1762 }17631764 // add arg1765 dest.push(arg);1766 }17671768 return { operands, unknown };1769 }17701771 /**1772 * Return an object containing local option values as key-value pairs.1773 *1774 * @return {object}1775 */1776 opts() {1777 if (this._storeOptionsAsProperties) {1778 // Preserve original behaviour so backwards compatible when still using properties1779 const result = {};1780 const len = this.options.length;17811782 for (let i = 0; i < len; i++) {1783 const key = this.options[i].attributeName();1784 result[key] =1785 key === this._versionOptionName ? this._version : this[key];1786 }1787 return result;1788 }17891790 return this._optionValues;1791 }17921793 /**1794 * Return an object containing merged local and global option values as key-value pairs.1795 *1796 * @return {object}1797 */1798 optsWithGlobals() {1799 // globals overwrite locals1800 return this._getCommandAndAncestors().reduce(1801 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1802 {},1803 );1804 }18051806 /**1807 * Display error message and exit (or call exitOverride).1808 *1809 * @param {string} message1810 * @param {object} [errorOptions]1811 * @param {string} [errorOptions.code] - an id string representing the error1812 * @param {number} [errorOptions.exitCode] - used with process.exit1813 */1814 error(message, errorOptions) {1815 // output handling1816 this._outputConfiguration.outputError(1817 `${message}\n`,1818 this._outputConfiguration.writeErr,1819 );1820 if (typeof this._showHelpAfterError === 'string') {1821 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1822 } else if (this._showHelpAfterError) {1823 this._outputConfiguration.writeErr('\n');1824 this.outputHelp({ error: true });1825 }18261827 // exit handling1828 const config = errorOptions || {};1829 const exitCode = config.exitCode || 1;1830 const code = config.code || 'commander.error';1831 this._exit(exitCode, code, message);1832 }18331834 /**1835 * Apply any option related environment variables, if option does1836 * not have a value from cli or client code.1837 *1838 * @private1839 */1840 _parseOptionsEnv() {1841 this.options.forEach((option) => {1842 if (option.envVar && option.envVar in process.env) {1843 const optionKey = option.attributeName();1844 // Priority check. Do not overwrite cli or options from unknown source (client-code).1845 if (1846 this.getOptionValue(optionKey) === undefined ||1847 ['default', 'config', 'env'].includes(1848 this.getOptionValueSource(optionKey),1849 )1850 ) {1851 if (option.required || option.optional) {1852 // option can take a value1853 // keep very simple, optional always takes value1854 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1855 } else {1856 // boolean1857 // keep very simple, only care that envVar defined and not the value1858 this.emit(`optionEnv:${option.name()}`);1859 }1860 }1861 }1862 });1863 }18641865 /**1866 * Apply any implied option values, if option is undefined or default value.1867 *1868 * @private1869 */1870 _parseOptionsImplied() {1871 const dualHelper = new DualOptions(this.options);1872 const hasCustomOptionValue = (optionKey) => {1873 return (1874 this.getOptionValue(optionKey) !== undefined &&1875 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1876 );1877 };1878 this.options1879 .filter(1880 (option) =>1881 option.implied !== undefined &&1882 hasCustomOptionValue(option.attributeName()) &&1883 dualHelper.valueFromOption(1884 this.getOptionValue(option.attributeName()),1885 option,1886 ),1887 )1888 .forEach((option) => {1889 Object.keys(option.implied)1890 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))1891 .forEach((impliedKey) => {1892 this.setOptionValueWithSource(1893 impliedKey,1894 option.implied[impliedKey],1895 'implied',1896 );1897 });1898 });1899 }19001901 /**1902 * Argument `name` is missing.1903 *1904 * @param {string} name1905 * @private1906 */19071908 missingArgument(name) {1909 const message = `error: missing required argument '${name}'`;1910 this.error(message, { code: 'commander.missingArgument' });1911 }19121913 /**1914 * `Option` is missing an argument.1915 *1916 * @param {Option} option1917 * @private1918 */19191920 optionMissingArgument(option) {1921 const message = `error: option '${option.flags}' argument missing`;1922 this.error(message, { code: 'commander.optionMissingArgument' });1923 }19241925 /**1926 * `Option` does not have a value, and is a mandatory option.1927 *1928 * @param {Option} option1929 * @private1930 */19311932 missingMandatoryOptionValue(option) {1933 const message = `error: required option '${option.flags}' not specified`;1934 this.error(message, { code: 'commander.missingMandatoryOptionValue' });1935 }19361937 /**1938 * `Option` conflicts with another option.1939 *1940 * @param {Option} option1941 * @param {Option} conflictingOption1942 * @private1943 */1944 _conflictingOption(option, conflictingOption) {1945 // The calling code does not know whether a negated option is the source of the1946 // value, so do some work to take an educated guess.1947 const findBestOptionFromValue = (option) => {1948 const optionKey = option.attributeName();1949 const optionValue = this.getOptionValue(optionKey);1950 const negativeOption = this.options.find(1951 (target) => target.negate && optionKey === target.attributeName(),1952 );1953 const positiveOption = this.options.find(1954 (target) => !target.negate && optionKey === target.attributeName(),1955 );1956 if (1957 negativeOption &&1958 ((negativeOption.presetArg === undefined && optionValue === false) ||1959 (negativeOption.presetArg !== undefined &&1960 optionValue === negativeOption.presetArg))1961 ) {1962 return negativeOption;1963 }1964 return positiveOption || option;1965 };19661967 const getErrorMessage = (option) => {1968 const bestOption = findBestOptionFromValue(option);1969 const optionKey = bestOption.attributeName();1970 const source = this.getOptionValueSource(optionKey);1971 if (source === 'env') {1972 return `environment variable '${bestOption.envVar}'`;1973 }1974 return `option '${bestOption.flags}'`;1975 };19761977 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1978 this.error(message, { code: 'commander.conflictingOption' });1979 }19801981 /**1982 * Unknown option `flag`.1983 *1984 * @param {string} flag1985 * @private1986 */19871988 unknownOption(flag) {1989 if (this._allowUnknownOption) return;1990 let suggestion = '';19911992 if (flag.startsWith('--') && this._showSuggestionAfterError) {1993 // Looping to pick up the global options too1994 let candidateFlags = [];1995 // eslint-disable-next-line @typescript-eslint/no-this-alias1996 let command = this;1997 do {1998 const moreFlags = command1999 .createHelp()2000 .visibleOptions(command)The first 2,000 of 2,509 lines.