Skip to content
Myr

command.js

This file

Path

lib/command.js

2,301 lines · 73.1 KiB · JavaScript

Last changed by

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

History of this file

Take it

1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');5const process = require('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: () => process.stdout.isTTY ? process.stdout.columns : undefined,64      getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65      outputError: (str, write) => write(str)66    };6768    this._hidden = false;69    /** @type {(Option | null | undefined)} */70    this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.71    this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited72    /** @type {Command} */73    this._helpCommand = undefined; // lazy initialised, inherited74    this._helpConfiguration = {};75  }7677  /**78   * Copy settings that are useful to have in common across root command and subcommands.79   *80   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)81   *82   * @param {Command} sourceCommand83   * @return {Command} `this` command for chaining84   */85  copyInheritedSettings(sourceCommand) {86    this._outputConfiguration = sourceCommand._outputConfiguration;87    this._helpOption = sourceCommand._helpOption;88    this._helpCommand = sourceCommand._helpCommand;89    this._helpConfiguration = sourceCommand._helpConfiguration;90    this._exitCallback = sourceCommand._exitCallback;91    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;92    this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;93    this._allowExcessArguments = sourceCommand._allowExcessArguments;94    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;95    this._showHelpAfterError = sourceCommand._showHelpAfterError;96    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;9798    return this;99  }100101  /**102   * @returns {Command[]}103   * @private104   */105106  _getCommandAndAncestors() {107    const result = [];108    // eslint-disable-next-line @typescript-eslint/no-this-alias109    for (let command = this; command; command = command.parent) {110      result.push(command);111    }112    return result;113  }114115  /**116   * Define a command.117   *118   * There are two styles of command: pay attention to where to put the description.119   *120   * @example121   * // Command implemented using action handler (description is supplied separately to `.command`)122   * program123   *   .command('clone <source> [destination]')124   *   .description('clone a repository into a newly created directory')125   *   .action((source, destination) => {126   *     console.log('clone command called');127   *   });128   *129   * // Command implemented using separate executable file (description is second parameter to `.command`)130   * program131   *   .command('start <service>', 'start named service')132   *   .command('stop [service]', 'stop named service, or all if no name supplied');133   *134   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`135   * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)136   * @param {Object} [execOpts] - configuration options (for executable)137   * @return {Command} returns new command for action handler, or `this` for executable command138   */139140  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {141    let desc = actionOptsOrExecDesc;142    let opts = execOpts;143    if (typeof desc === 'object' && desc !== null) {144      opts = desc;145      desc = null;146    }147    opts = opts || {};148    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);149150    const cmd = this.createCommand(name);151    if (desc) {152      cmd.description(desc);153      cmd._executableHandler = true;154    }155    if (opts.isDefault) this._defaultCommandName = cmd._name;156    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden157    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor158    if (args) cmd.arguments(args);159    this._registerCommand(cmd);160    cmd.parent = this;161    cmd.copyInheritedSettings(this);162163    if (desc) return this;164    return cmd;165  }166167  /**168   * Factory routine to create a new unattached command.169   *170   * See .command() for creating an attached subcommand, which uses this routine to171   * create the command. You can override createCommand to customise subcommands.172   *173   * @param {string} [name]174   * @return {Command} new command175   */176177  createCommand(name) {178    return new Command(name);179  }180181  /**182   * You can customise the help with a subclass of Help by overriding createHelp,183   * or by overriding Help properties using configureHelp().184   *185   * @return {Help}186   */187188  createHelp() {189    return Object.assign(new Help(), this.configureHelp());190  }191192  /**193   * You can customise the help by overriding Help properties using configureHelp(),194   * or with a subclass of Help by overriding createHelp().195   *196   * @param {Object} [configuration] - configuration options197   * @return {(Command|Object)} `this` command for chaining, or stored configuration198   */199200  configureHelp(configuration) {201    if (configuration === undefined) return this._helpConfiguration;202203    this._helpConfiguration = configuration;204    return this;205  }206207  /**208   * The default output goes to stdout and stderr. You can customise this for special209   * applications. You can also customise the display of errors by overriding outputError.210   *211   * The configuration properties are all functions:212   *213   *     // functions to change where being written, stdout and stderr214   *     writeOut(str)215   *     writeErr(str)216   *     // matching functions to specify width for wrapping help217   *     getOutHelpWidth()218   *     getErrHelpWidth()219   *     // functions based on what is being written out220   *     outputError(str, write) // used for displaying errors, and not used for displaying help221   *222   * @param {Object} [configuration] - configuration options223   * @return {(Command|Object)} `this` command for chaining, or stored configuration224   */225226  configureOutput(configuration) {227    if (configuration === undefined) return this._outputConfiguration;228229    Object.assign(this._outputConfiguration, configuration);230    return this;231  }232233  /**234   * Display the help or a custom message after an error occurs.235   *236   * @param {(boolean|string)} [displayHelp]237   * @return {Command} `this` command for chaining238   */239  showHelpAfterError(displayHelp = true) {240    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;241    this._showHelpAfterError = displayHelp;242    return this;243  }244245  /**246   * Display suggestion of similar commands for unknown commands, or options for unknown options.247   *248   * @param {boolean} [displaySuggestion]249   * @return {Command} `this` command for chaining250   */251  showSuggestionAfterError(displaySuggestion = true) {252    this._showSuggestionAfterError = !!displaySuggestion;253    return this;254  }255256  /**257   * Add a prepared subcommand.258   *259   * See .command() for creating an attached subcommand which inherits settings from its parent.260   *261   * @param {Command} cmd - new subcommand262   * @param {Object} [opts] - configuration options263   * @return {Command} `this` command for chaining264   */265266  addCommand(cmd, opts) {267    if (!cmd._name) {268      throw new Error(`Command passed to .addCommand() must have a name269- specify the name in Command constructor or using .name()`);270    }271272    opts = opts || {};273    if (opts.isDefault) this._defaultCommandName = cmd._name;274    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation275276    this._registerCommand(cmd);277    cmd.parent = this;278    cmd._checkForBrokenPassThrough();279280    return this;281  }282283  /**284   * Factory routine to create a new unattached argument.285   *286   * See .argument() for creating an attached argument, which uses this routine to287   * create the argument. You can override createArgument to return a custom argument.288   *289   * @param {string} name290   * @param {string} [description]291   * @return {Argument} new argument292   */293294  createArgument(name, description) {295    return new Argument(name, description);296  }297298  /**299   * Define argument syntax for command.300   *301   * The default is that the argument is required, and you can explicitly302   * indicate this with <> around the name. Put [] around the name for an optional argument.303   *304   * @example305   * program.argument('<input-file>');306   * program.argument('[output-file]');307   *308   * @param {string} name309   * @param {string} [description]310   * @param {(Function|*)} [fn] - custom argument processing function311   * @param {*} [defaultValue]312   * @return {Command} `this` command for chaining313   */314  argument(name, description, fn, defaultValue) {315    const argument = this.createArgument(name, description);316    if (typeof fn === 'function') {317      argument.default(defaultValue).argParser(fn);318    } else {319      argument.default(fn);320    }321    this.addArgument(argument);322    return this;323  }324325  /**326   * Define argument syntax for command, adding multiple at once (without descriptions).327   *328   * See also .argument().329   *330   * @example331   * program.arguments('<cmd> [env]');332   *333   * @param {string} names334   * @return {Command} `this` command for chaining335   */336337  arguments(names) {338    names.trim().split(/ +/).forEach((detail) => {339      this.argument(detail);340    });341    return this;342  }343344  /**345   * Define argument syntax for command, adding a prepared argument.346   *347   * @param {Argument} argument348   * @return {Command} `this` command for chaining349   */350  addArgument(argument) {351    const previousArgument = this.registeredArguments.slice(-1)[0];352    if (previousArgument && previousArgument.variadic) {353      throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);354    }355    if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {356      throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);357    }358    this.registeredArguments.push(argument);359    return this;360  }361362  /**363   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.364   *365   * @example366   *    program.helpCommand('help [cmd]');367   *    program.helpCommand('help [cmd]', 'show help');368   *    program.helpCommand(false); // suppress default help command369   *    program.helpCommand(true); // add help command even if no subcommands370   *371   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added372   * @param {string} [description] - custom description373   * @return {Command} `this` command for chaining374   */375376  helpCommand(enableOrNameAndArgs, description) {377    if (typeof enableOrNameAndArgs === 'boolean') {378      this._addImplicitHelpCommand = enableOrNameAndArgs;379      return this;380    }381382    enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';383    const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);384    const helpDescription = description ?? 'display help for command';385386    const helpCommand = this.createCommand(helpName);387    helpCommand.helpOption(false);388    if (helpArgs) helpCommand.arguments(helpArgs);389    if (helpDescription) helpCommand.description(helpDescription);390391    this._addImplicitHelpCommand = true;392    this._helpCommand = helpCommand;393394    return this;395  }396397  /**398   * Add prepared custom help command.399   *400   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`401   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only402   * @return {Command} `this` command for chaining403   */404  addHelpCommand(helpCommand, deprecatedDescription) {405    // If not passed an object, call through to helpCommand for backwards compatibility,406    // as addHelpCommand was originally used like helpCommand is now.407    if (typeof helpCommand !== 'object') {408      this.helpCommand(helpCommand, deprecatedDescription);409      return this;410    }411412    this._addImplicitHelpCommand = true;413    this._helpCommand = helpCommand;414    return this;415  }416417  /**418   * Lazy create help command.419   *420   * @return {(Command|null)}421   * @package422   */423  _getHelpCommand() {424    const hasImplicitHelpCommand = this._addImplicitHelpCommand ??425      (this.commands.length && !this._actionHandler && !this._findCommand('help'));426427    if (hasImplicitHelpCommand) {428      if (this._helpCommand === undefined) {429        this.helpCommand(undefined, undefined); // use default name and description430      }431      return this._helpCommand;432    }433    return null;434  }435436  /**437   * Add hook for life cycle event.438   *439   * @param {string} event440   * @param {Function} listener441   * @return {Command} `this` command for chaining442   */443444  hook(event, listener) {445    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];446    if (!allowedValues.includes(event)) {447      throw new Error(`Unexpected value for event passed to hook : '${event}'.448Expecting one of '${allowedValues.join("', '")}'`);449    }450    if (this._lifeCycleHooks[event]) {451      this._lifeCycleHooks[event].push(listener);452    } else {453      this._lifeCycleHooks[event] = [listener];454    }455    return this;456  }457458  /**459   * Register callback to use as replacement for calling process.exit.460   *461   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing462   * @return {Command} `this` command for chaining463   */464465  exitOverride(fn) {466    if (fn) {467      this._exitCallback = fn;468    } else {469      this._exitCallback = (err) => {470        if (err.code !== 'commander.executeSubCommandAsync') {471          throw err;472        } else {473          // Async callback from spawn events, not useful to throw.474        }475      };476    }477    return this;478  }479480  /**481   * Call process.exit, and _exitCallback if defined.482   *483   * @param {number} exitCode exit code for using with process.exit484   * @param {string} code an id string representing the error485   * @param {string} message human-readable description of the error486   * @return never487   * @private488   */489490  _exit(exitCode, code, message) {491    if (this._exitCallback) {492      this._exitCallback(new CommanderError(exitCode, code, message));493      // Expecting this line is not reached.494    }495    process.exit(exitCode);496  }497498  /**499   * Register callback `fn` for the command.500   *501   * @example502   * program503   *   .command('serve')504   *   .description('start service')505   *   .action(function() {506   *      // do work here507   *   });508   *509   * @param {Function} fn510   * @return {Command} `this` command for chaining511   */512513  action(fn) {514    const listener = (args) => {515      // The .action callback takes an extra parameter which is the command or options.516      const expectedArgsCount = this.registeredArguments.length;517      const actionArgs = args.slice(0, expectedArgsCount);518      if (this._storeOptionsAsProperties) {519        actionArgs[expectedArgsCount] = this; // backwards compatible "options"520      } else {521        actionArgs[expectedArgsCount] = this.opts();522      }523      actionArgs.push(this);524525      return fn.apply(this, actionArgs);526    };527    this._actionHandler = listener;528    return this;529  }530531  /**532   * Factory routine to create a new unattached option.533   *534   * See .option() for creating an attached option, which uses this routine to535   * create the option. You can override createOption to return a custom option.536   *537   * @param {string} flags538   * @param {string} [description]539   * @return {Option} new option540   */541542  createOption(flags, description) {543    return new Option(flags, description);544  }545546  /**547   * Wrap parseArgs to catch 'commander.invalidArgument'.548   *549   * @param {(Option | Argument)} target550   * @param {string} value551   * @param {*} previous552   * @param {string} invalidArgumentMessage553   * @private554   */555556  _callParseArg(target, value, previous, invalidArgumentMessage) {557    try {558      return target.parseArg(value, previous);559    } catch (err) {560      if (err.code === 'commander.invalidArgument') {561        const message = `${invalidArgumentMessage} ${err.message}`;562        this.error(message, { exitCode: err.exitCode, code: err.code });563      }564      throw err;565    }566  }567568  /**569   * Check for option flag conflicts.570   * Register option if no conflicts found, or throw on conflict.571   *572   * @param {Option} option573   * @api private574   */575576  _registerOption(option) {577    const matchingOption = (option.short && this._findOption(option.short)) ||578      (option.long && this._findOption(option.long));579    if (matchingOption) {580      const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;581      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'582-  already used by option '${matchingOption.flags}'`);583    }584585    this.options.push(option);586  }587588  /**589   * Check for command name and alias conflicts with existing commands.590   * Register command if no conflicts found, or throw on conflict.591   *592   * @param {Command} command593   * @api private594   */595596  _registerCommand(command) {597    const knownBy = (cmd) => {598      return [cmd.name()].concat(cmd.aliases());599    };600601    const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));602    if (alreadyUsed) {603      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');604      const newCmd = knownBy(command).join('|');605      throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);606    }607608    this.commands.push(command);609  }610611  /**612   * Add an option.613   *614   * @param {Option} option615   * @return {Command} `this` command for chaining616   */617  addOption(option) {618    this._registerOption(option);619620    const oname = option.name();621    const name = option.attributeName();622623    // store default value624    if (option.negate) {625      // --no-foo is special and defaults foo to true, unless a --foo option is already defined626      const positiveLongFlag = option.long.replace(/^--no-/, '--');627      if (!this._findOption(positiveLongFlag)) {628        this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');629      }630    } else if (option.defaultValue !== undefined) {631      this.setOptionValueWithSource(name, option.defaultValue, 'default');632    }633634    // handler for cli and env supplied values635    const handleOptionValue = (val, invalidValueMessage, valueSource) => {636      // val is null for optional option used without an optional-argument.637      // val is undefined for boolean and negated option.638      if (val == null && option.presetArg !== undefined) {639        val = option.presetArg;640      }641642      // custom processing643      const oldValue = this.getOptionValue(name);644      if (val !== null && option.parseArg) {645        val = this._callParseArg(option, val, oldValue, invalidValueMessage);646      } else if (val !== null && option.variadic) {647        val = option._concatValue(val, oldValue);648      }649650      // Fill-in appropriate missing values. Long winded but easy to follow.651      if (val == null) {652        if (option.negate) {653          val = false;654        } else if (option.isBoolean() || option.optional) {655          val = true;656        } else {657          val = ''; // not normal, parseArg might have failed or be a mock function for testing658        }659      }660      this.setOptionValueWithSource(name, val, valueSource);661    };662663    this.on('option:' + oname, (val) => {664      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;665      handleOptionValue(val, invalidValueMessage, 'cli');666    });667668    if (option.envVar) {669      this.on('optionEnv:' + oname, (val) => {670        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;671        handleOptionValue(val, invalidValueMessage, 'env');672      });673    }674675    return this;676  }677678  /**679   * Internal implementation shared by .option() and .requiredOption()680   *681   * @private682   */683  _optionEx(config, flags, description, fn, defaultValue) {684    if (typeof flags === 'object' && flags instanceof Option) {685      throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');686    }687    const option = this.createOption(flags, description);688    option.makeOptionMandatory(!!config.mandatory);689    if (typeof fn === 'function') {690      option.default(defaultValue).argParser(fn);691    } else if (fn instanceof RegExp) {692      // deprecated693      const regex = fn;694      fn = (val, def) => {695        const m = regex.exec(val);696        return m ? m[0] : def;697      };698      option.default(defaultValue).argParser(fn);699    } else {700      option.default(fn);701    }702703    return this.addOption(option);704  }705706  /**707   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.708   *709   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required710   * option-argument is indicated by `<>` and an optional option-argument by `[]`.711   *712   * See the README for more details, and see also addOption() and requiredOption().713   *714   * @example715   * program716   *     .option('-p, --pepper', 'add pepper')717   *     .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument718   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default719   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function720   *721   * @param {string} flags722   * @param {string} [description]723   * @param {(Function|*)} [parseArg] - custom option processing function or default value724   * @param {*} [defaultValue]725   * @return {Command} `this` command for chaining726   */727728  option(flags, description, parseArg, defaultValue) {729    return this._optionEx({}, flags, description, parseArg, defaultValue);730  }731732  /**733  * Add a required option which must have a value after parsing. This usually means734  * the option must be specified on the command line. (Otherwise the same as .option().)735  *736  * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.737  *738  * @param {string} flags739  * @param {string} [description]740  * @param {(Function|*)} [parseArg] - custom option processing function or default value741  * @param {*} [defaultValue]742  * @return {Command} `this` command for chaining743  */744745  requiredOption(flags, description, parseArg, defaultValue) {746    return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);747  }748749  /**750   * Alter parsing of short flags with optional values.751   *752   * @example753   * // for `.option('-f,--flag [value]'):754   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour755   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`756   *757   * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.758   */759  combineFlagAndOptionalValue(combine = true) {760    this._combineFlagAndOptionalValue = !!combine;761    return this;762  }763764  /**765   * Allow unknown options on the command line.766   *767   * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown768   * for unknown options.769   */770  allowUnknownOption(allowUnknown = true) {771    this._allowUnknownOption = !!allowUnknown;772    return this;773  }774775  /**776   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.777   *778   * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown779   * for excess arguments.780   */781  allowExcessArguments(allowExcess = true) {782    this._allowExcessArguments = !!allowExcess;783    return this;784  }785786  /**787   * Enable positional options. Positional means global options are specified before subcommands which lets788   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.789   * The default behaviour is non-positional and global options may appear anywhere on the command line.790   *791   * @param {boolean} [positional=true]792   */793  enablePositionalOptions(positional = true) {794    this._enablePositionalOptions = !!positional;795    return this;796  }797798  /**799   * Pass through options that come after command-arguments rather than treat them as command-options,800   * so actual command-options come before command-arguments. Turning this on for a subcommand requires801   * positional options to have been enabled on the program (parent commands).802   * The default behaviour is non-positional and options may appear before or after command-arguments.803   *804   * @param {boolean} [passThrough=true]805   * for unknown options.806   */807  passThroughOptions(passThrough = true) {808    this._passThroughOptions = !!passThrough;809    this._checkForBrokenPassThrough();810    return this;811  }812813  /**814   * @private815   */816817  _checkForBrokenPassThrough() {818    if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {819      throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);820    }821  }822823  /**824    * Whether to store option values as properties on command object,825    * or store separately (specify false). In both cases the option values can be accessed using .opts().826    *827    * @param {boolean} [storeAsProperties=true]828    * @return {Command} `this` command for chaining829    */830831  storeOptionsAsProperties(storeAsProperties = true) {832    if (this.options.length) {833      throw new Error('call .storeOptionsAsProperties() before adding options');834    }835    if (Object.keys(this._optionValues).length) {836      throw new Error('call .storeOptionsAsProperties() before setting option values');837    }838    this._storeOptionsAsProperties = !!storeAsProperties;839    return this;840  }841842  /**843   * Retrieve option value.844   *845   * @param {string} key846   * @return {Object} value847   */848849  getOptionValue(key) {850    if (this._storeOptionsAsProperties) {851      return this[key];852    }853    return this._optionValues[key];854  }855856  /**857   * Store option value.858   *859   * @param {string} key860   * @param {Object} value861   * @return {Command} `this` command for chaining862   */863864  setOptionValue(key, value) {865    return this.setOptionValueWithSource(key, value, undefined);866  }867868  /**869    * Store option value and where the value came from.870    *871    * @param {string} key872    * @param {Object} value873    * @param {string} source - expected values are default/config/env/cli/implied874    * @return {Command} `this` command for chaining875    */876877  setOptionValueWithSource(key, value, source) {878    if (this._storeOptionsAsProperties) {879      this[key] = value;880    } else {881      this._optionValues[key] = value;882    }883    this._optionValueSources[key] = source;884    return this;885  }886887  /**888    * Get source of option value.889    * Expected values are default | config | env | cli | implied890    *891    * @param {string} key892    * @return {string}893    */894895  getOptionValueSource(key) {896    return this._optionValueSources[key];897  }898899  /**900    * Get source of option value. See also .optsWithGlobals().901    * Expected values are default | config | env | cli | implied902    *903    * @param {string} key904    * @return {string}905    */906907  getOptionValueSourceWithGlobals(key) {908    // global overwrites local, like optsWithGlobals909    let source;910    this._getCommandAndAncestors().forEach((cmd) => {911      if (cmd.getOptionValueSource(key) !== undefined) {912        source = cmd.getOptionValueSource(key);913      }914    });915    return source;916  }917918  /**919   * Get user arguments from implied or explicit arguments.920   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.921   *922   * @private923   */924925  _prepareUserArgs(argv, parseOptions) {926    if (argv !== undefined && !Array.isArray(argv)) {927      throw new Error('first parameter to parse must be array or undefined');928    }929    parseOptions = parseOptions || {};930931    // Default to using process.argv932    if (argv === undefined) {933      argv = process.argv;934      if (process.versions && process.versions.electron) {935        parseOptions.from = 'electron';936      }937    }938    this.rawArgs = argv.slice();939940    // make it a little easier for callers by supporting various argv conventions941    let userArgs;942    switch (parseOptions.from) {943      case undefined:944      case 'node':945        this._scriptPath = argv[1];946        userArgs = argv.slice(2);947        break;948      case 'electron':949        // @ts-ignore: because defaultApp is an unknown property950        if (process.defaultApp) {951          this._scriptPath = argv[1];952          userArgs = argv.slice(2);953        } else {954          userArgs = argv.slice(1);955        }956        break;957      case 'user':958        userArgs = argv.slice(0);959        break;960      default:961        throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);962    }963964    // Find default name for program from arguments.965    if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);966    this._name = this._name || 'program';967968    return userArgs;969  }970971  /**972   * Parse `argv`, setting options and invoking commands when defined.973   *974   * The default expectation is that the arguments are from node and have the application as argv[0]975   * and the script being run in argv[1], with user parameters after that.976   *977   * @example978   * program.parse(process.argv);979   * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions980   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]981   *982   * @param {string[]} [argv] - optional, defaults to process.argv983   * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron984   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'985   * @return {Command} `this` command for chaining986   */987988  parse(argv, parseOptions) {989    const userArgs = this._prepareUserArgs(argv, parseOptions);990    this._parseCommand([], userArgs);991992    return this;993  }994995  /**996   * Parse `argv`, setting options and invoking commands when defined.997   *998   * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.999   *1000   * The default expectation is that the arguments are from node and have the application as argv[0]1001   * and the script being run in argv[1], with user parameters after that.1002   *1003   * @example1004   * await program.parseAsync(process.argv);1005   * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1006   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1007   *1008   * @param {string[]} [argv]1009   * @param {Object} [parseOptions]1010   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1011   * @return {Promise}1012   */10131014  async parseAsync(argv, parseOptions) {1015    const userArgs = this._prepareUserArgs(argv, parseOptions);1016    await this._parseCommand([], userArgs);10171018    return this;1019  }10201021  /**1022   * Execute a sub-command executable.1023   *1024   * @private1025   */10261027  _executeSubCommand(subcommand, args) {1028    args = args.slice();1029    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1030    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];10311032    function findFile(baseDir, baseName) {1033      // Look for specified file1034      const localBin = path.resolve(baseDir, baseName);1035      if (fs.existsSync(localBin)) return localBin;10361037      // Stop looking if candidate already has an expected extension.1038      if (sourceExt.includes(path.extname(baseName))) return undefined;10391040      // Try all the extensions.1041      const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));1042      if (foundExt) return `${localBin}${foundExt}`;10431044      return undefined;1045    }10461047    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1048    this._checkForMissingMandatoryOptions();1049    this._checkForConflictingOptions();10501051    // executableFile and executableDir might be full path, or just a name1052    let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1053    let executableDir = this._executableDir || '';1054    if (this._scriptPath) {1055      let resolvedScriptPath; // resolve possible symlink for installed npm binary1056      try {1057        resolvedScriptPath = fs.realpathSync(this._scriptPath);1058      } catch (err) {1059        resolvedScriptPath = this._scriptPath;1060      }1061      executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);1062    }10631064    // Look for a local file in preference to a command in PATH.1065    if (executableDir) {1066      let localFile = findFile(executableDir, executableFile);10671068      // Legacy search using prefix of script name instead of command name1069      if (!localFile && !subcommand._executableFile && this._scriptPath) {1070        const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1071        if (legacyName !== this._name) {1072          localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);1073        }1074      }1075      executableFile = localFile || executableFile;1076    }10771078    launchWithNode = sourceExt.includes(path.extname(executableFile));10791080    let proc;1081    if (process.platform !== 'win32') {1082      if (launchWithNode) {1083        args.unshift(executableFile);1084        // add executable arguments to spawn1085        args = incrementNodeInspectorPort(process.execArgv).concat(args);10861087        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1088      } else {1089        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1090      }1091    } else {1092      args.unshift(executableFile);1093      // add executable arguments to spawn1094      args = incrementNodeInspectorPort(process.execArgv).concat(args);1095      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1096    }10971098    if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1099      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1100      signals.forEach((signal) => {1101        process.on(signal, () => {1102          if (proc.killed === false && proc.exitCode === null) {1103            proc.kill(signal);1104          }1105        });1106      });1107    }11081109    // By default terminate process when spawned process terminates.1110    const exitCallback = this._exitCallback;1111    proc.on('close', (code) => {1112      code = code ?? 1; // code is null if spawned process terminated due to a signal1113      if (!exitCallback) {1114        process.exit(code);1115      } else {1116        exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));1117      }1118    });1119    proc.on('error', (err) => {1120      // @ts-ignore: because err.code is an unknown property  1121      if (err.code === 'ENOENT') {1122        const executableDirMessage = executableDir1123          ? `searched for local subcommand relative to directory '${executableDir}'`1124          : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1125        const executableMissing = `'${executableFile}' does not exist1126 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1127 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1128 - ${executableDirMessage}`;1129        throw new Error(executableMissing);1130      // @ts-ignore: because err.code is an unknown property1131      } else if (err.code === 'EACCES') {1132        throw new Error(`'${executableFile}' not executable`);1133      }1134      if (!exitCallback) {1135        process.exit(1);1136      } else {1137        const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1138        wrappedError.nestedError = err;1139        exitCallback(wrappedError);1140      }1141    });11421143    // Store the reference to the child process1144    this.runningCommand = proc;1145  }11461147  /**1148   * @private1149   */11501151  _dispatchSubcommand(commandName, operands, unknown) {1152    const subCommand = this._findCommand(commandName);1153    if (!subCommand) this.help({ error: true });11541155    let promiseChain;1156    promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1157    promiseChain = this._chainOrCall(promiseChain, () => {1158      if (subCommand._executableHandler) {1159        this._executeSubCommand(subCommand, operands.concat(unknown));1160      } else {1161        return subCommand._parseCommand(operands, unknown);1162      }1163    });1164    return promiseChain;1165  }11661167  /**1168   * Invoke help directly if possible, or dispatch if necessary.1169   * e.g. help foo1170   *1171   * @private1172   */11731174  _dispatchHelpCommand(subcommandName) {1175    if (!subcommandName) {1176      this.help();1177    }1178    const subCommand = this._findCommand(subcommandName);1179    if (subCommand && !subCommand._executableHandler) {1180      subCommand.help();1181    }11821183    // Fallback to parsing the help flag to invoke the help.1184    return this._dispatchSubcommand(subcommandName, [], [1185      this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'1186    ]);1187  }11881189  /**1190   * Check this.args against expected this.registeredArguments.1191   *1192   * @private1193   */11941195  _checkNumberOfArguments() {1196    // too few1197    this.registeredArguments.forEach((arg, i) => {1198      if (arg.required && this.args[i] == null) {1199        this.missingArgument(arg.name());1200      }1201    });1202    // too many1203    if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {1204      return;1205    }1206    if (this.args.length > this.registeredArguments.length) {1207      this._excessArguments(this.args);1208    }1209  }12101211  /**1212   * Process this.args using this.registeredArguments and save as this.processedArgs!1213   *1214   * @private1215   */12161217  _processArguments() {1218    const myParseArg = (argument, value, previous) => {1219      // Extra processing for nice error message on parsing failure.1220      let parsedValue = value;1221      if (value !== null && argument.parseArg) {1222        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1223        parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);1224      }1225      return parsedValue;1226    };12271228    this._checkNumberOfArguments();12291230    const processedArgs = [];1231    this.registeredArguments.forEach((declaredArg, index) => {1232      let value = declaredArg.defaultValue;1233      if (declaredArg.variadic) {1234        // Collect together remaining arguments for passing together as an array.1235        if (index < this.args.length) {1236          value = this.args.slice(index);1237          if (declaredArg.parseArg) {1238            value = value.reduce((processed, v) => {1239              return myParseArg(declaredArg, v, processed);1240            }, declaredArg.defaultValue);1241          }1242        } else if (value === undefined) {1243          value = [];1244        }1245      } else if (index < this.args.length) {1246        value = this.args[index];1247        if (declaredArg.parseArg) {1248          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1249        }1250      }1251      processedArgs[index] = value;1252    });1253    this.processedArgs = processedArgs;1254  }12551256  /**1257   * Once we have a promise we chain, but call synchronously until then.1258   *1259   * @param {(Promise|undefined)} promise1260   * @param {Function} fn1261   * @return {(Promise|undefined)}1262   * @private1263   */12641265  _chainOrCall(promise, fn) {1266    // thenable1267    if (promise && promise.then && typeof promise.then === 'function') {1268      // already have a promise, chain callback1269      return promise.then(() => fn());1270    }1271    // callback might return a promise1272    return fn();1273  }12741275  /**1276   *1277   * @param {(Promise|undefined)} promise1278   * @param {string} event1279   * @return {(Promise|undefined)}1280   * @private1281   */12821283  _chainOrCallHooks(promise, event) {1284    let result = promise;1285    const hooks = [];1286    this._getCommandAndAncestors()1287      .reverse()1288      .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1289      .forEach(hookedCommand => {1290        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1291          hooks.push({ hookedCommand, callback });1292        });1293      });1294    if (event === 'postAction') {1295      hooks.reverse();1296    }12971298    hooks.forEach((hookDetail) => {1299      result = this._chainOrCall(result, () => {1300        return hookDetail.callback(hookDetail.hookedCommand, this);1301      });1302    });1303    return result;1304  }13051306  /**1307   *1308   * @param {(Promise|undefined)} promise1309   * @param {Command} subCommand1310   * @param {string} event1311   * @return {(Promise|undefined)}1312   * @private1313   */13141315  _chainOrCallSubCommandHook(promise, subCommand, event) {1316    let result = promise;1317    if (this._lifeCycleHooks[event] !== undefined) {1318      this._lifeCycleHooks[event].forEach((hook) => {1319        result = this._chainOrCall(result, () => {1320          return hook(this, subCommand);1321        });1322      });1323    }1324    return result;1325  }13261327  /**1328   * Process arguments in context of this command.1329   * Returns action result, in case it is a promise.1330   *1331   * @private1332   */13331334  _parseCommand(operands, unknown) {1335    const parsed = this.parseOptions(unknown);1336    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1337    this._parseOptionsImplied();1338    operands = operands.concat(parsed.operands);1339    unknown = parsed.unknown;1340    this.args = operands.concat(unknown);13411342    if (operands && this._findCommand(operands[0])) {1343      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1344    }1345    if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {1346      return this._dispatchHelpCommand(operands[1]);1347    }1348    if (this._defaultCommandName) {1349      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1350      return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1351    }1352    if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1353      // probably missing subcommand and no handler, user needs help (and exit)1354      this.help({ error: true });1355    }13561357    this._outputHelpIfRequested(parsed.unknown);1358    this._checkForMissingMandatoryOptions();1359    this._checkForConflictingOptions();13601361    // We do not always call this check to avoid masking a "better" error, like unknown command.1362    const checkForUnknownOptions = () => {1363      if (parsed.unknown.length > 0) {1364        this.unknownOption(parsed.unknown[0]);1365      }1366    };13671368    const commandEvent = `command:${this.name()}`;1369    if (this._actionHandler) {1370      checkForUnknownOptions();1371      this._processArguments();13721373      let promiseChain;1374      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1375      promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));1376      if (this.parent) {1377        promiseChain = this._chainOrCall(promiseChain, () => {1378          this.parent.emit(commandEvent, operands, unknown); // legacy1379        });1380      }1381      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1382      return promiseChain;1383    }1384    if (this.parent && this.parent.listenerCount(commandEvent)) {1385      checkForUnknownOptions();1386      this._processArguments();1387      this.parent.emit(commandEvent, operands, unknown); // legacy1388    } else if (operands.length) {1389      if (this._findCommand('*')) { // legacy default command1390        return this._dispatchSubcommand('*', operands, unknown);1391      }1392      if (this.listenerCount('command:*')) {1393        // skip option check, emit event for possible misspelling suggestion1394        this.emit('command:*', operands, unknown);1395      } else if (this.commands.length) {1396        this.unknownCommand();1397      } else {1398        checkForUnknownOptions();1399        this._processArguments();1400      }1401    } else if (this.commands.length) {1402      checkForUnknownOptions();1403      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1404      this.help({ error: true });1405    } else {1406      checkForUnknownOptions();1407      this._processArguments();1408      // fall through for caller to handle after calling .parse()1409    }1410  }14111412  /**1413   * Find matching command.1414   *1415   * @private1416   */1417  _findCommand(name) {1418    if (!name) return undefined;1419    return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1420  }14211422  /**1423   * Return an option matching `arg` if any.1424   *1425   * @param {string} arg1426   * @return {Option}1427   * @package internal use only1428   */14291430  _findOption(arg) {1431    return this.options.find(option => option.is(arg));1432  }14331434  /**1435   * Display an error message if a mandatory option does not have a value.1436   * Called after checking for help flags in leaf subcommand.1437   *1438   * @private1439   */14401441  _checkForMissingMandatoryOptions() {1442    // Walk up hierarchy so can call in subcommand after checking for displaying help.1443    this._getCommandAndAncestors().forEach((cmd) => {1444      cmd.options.forEach((anOption) => {1445        if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1446          cmd.missingMandatoryOptionValue(anOption);1447        }1448      });1449    });1450  }14511452  /**1453   * Display an error message if conflicting options are used together in this.1454   *1455   * @private1456   */1457  _checkForConflictingLocalOptions() {1458    const definedNonDefaultOptions = this.options.filter(1459      (option) => {1460        const optionKey = option.attributeName();1461        if (this.getOptionValue(optionKey) === undefined) {1462          return false;1463        }1464        return this.getOptionValueSource(optionKey) !== 'default';1465      }1466    );14671468    const optionsWithConflicting = definedNonDefaultOptions.filter(1469      (option) => option.conflictsWith.length > 01470    );14711472    optionsWithConflicting.forEach((option) => {1473      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1474        option.conflictsWith.includes(defined.attributeName())1475      );1476      if (conflictingAndDefined) {1477        this._conflictingOption(option, conflictingAndDefined);1478      }1479    });1480  }14811482  /**1483   * Display an error message if conflicting options are used together.1484   * Called after checking for help flags in leaf subcommand.1485   *1486   * @private1487   */1488  _checkForConflictingOptions() {1489    // Walk up hierarchy so can call in subcommand after checking for displaying help.1490    this._getCommandAndAncestors().forEach((cmd) => {1491      cmd._checkForConflictingLocalOptions();1492    });1493  }14941495  /**1496   * Parse options from `argv` removing known options,1497   * and return argv split into operands and unknown arguments.1498   *1499   * Examples:1500   *1501   *     argv => operands, unknown1502   *     --known kkk op => [op], []1503   *     op --known kkk => [op], []1504   *     sub --unknown uuu op => [sub], [--unknown uuu op]1505   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1506   *1507   * @param {string[]} argv1508   * @return {{operands: string[], unknown: string[]}}1509   */15101511  parseOptions(argv) {1512    const operands = []; // operands, not options or values1513    const unknown = []; // first unknown option and remaining unknown args1514    let dest = operands;1515    const args = argv.slice();15161517    function maybeOption(arg) {1518      return arg.length > 1 && arg[0] === '-';1519    }15201521    // parse options1522    let activeVariadicOption = null;1523    while (args.length) {1524      const arg = args.shift();15251526      // literal1527      if (arg === '--') {1528        if (dest === unknown) dest.push(arg);1529        dest.push(...args);1530        break;1531      }15321533      if (activeVariadicOption && !maybeOption(arg)) {1534        this.emit(`option:${activeVariadicOption.name()}`, arg);1535        continue;1536      }1537      activeVariadicOption = null;15381539      if (maybeOption(arg)) {1540        const option = this._findOption(arg);1541        // recognised option, call listener to assign value with possible custom processing1542        if (option) {1543          if (option.required) {1544            const value = args.shift();1545            if (value === undefined) this.optionMissingArgument(option);1546            this.emit(`option:${option.name()}`, value);1547          } else if (option.optional) {1548            let value = null;1549            // historical behaviour is optional value is following arg unless an option1550            if (args.length > 0 && !maybeOption(args[0])) {1551              value = args.shift();1552            }1553            this.emit(`option:${option.name()}`, value);1554          } else { // boolean flag1555            this.emit(`option:${option.name()}`);1556          }1557          activeVariadicOption = option.variadic ? option : null;1558          continue;1559        }1560      }15611562      // Look for combo options following single dash, eat first one if known.1563      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1564        const option = this._findOption(`-${arg[1]}`);1565        if (option) {1566          if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1567            // option with value following in same argument1568            this.emit(`option:${option.name()}`, arg.slice(2));1569          } else {1570            // boolean option, emit and put back remainder of arg for further processing1571            this.emit(`option:${option.name()}`);1572            args.unshift(`-${arg.slice(2)}`);1573          }1574          continue;1575        }1576      }15771578      // Look for known long flag with value, like --foo=bar1579      if (/^--[^=]+=/.test(arg)) {1580        const index = arg.indexOf('=');1581        const option = this._findOption(arg.slice(0, index));1582        if (option && (option.required || option.optional)) {1583          this.emit(`option:${option.name()}`, arg.slice(index + 1));1584          continue;1585        }1586      }15871588      // Not a recognised option by this command.1589      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15901591      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1592      if (maybeOption(arg)) {1593        dest = unknown;1594      }15951596      // If using positionalOptions, stop processing our options at subcommand.1597      if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1598        if (this._findCommand(arg)) {1599          operands.push(arg);1600          if (args.length > 0) unknown.push(...args);1601          break;1602        } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {1603          operands.push(arg);1604          if (args.length > 0) operands.push(...args);1605          break;1606        } else if (this._defaultCommandName) {1607          unknown.push(arg);1608          if (args.length > 0) unknown.push(...args);1609          break;1610        }1611      }16121613      // If using passThroughOptions, stop processing options at first command-argument.1614      if (this._passThroughOptions) {1615        dest.push(arg);1616        if (args.length > 0) dest.push(...args);1617        break;1618      }16191620      // add arg1621      dest.push(arg);1622    }16231624    return { operands, unknown };1625  }16261627  /**1628   * Return an object containing local option values as key-value pairs.1629   *1630   * @return {Object}1631   */1632  opts() {1633    if (this._storeOptionsAsProperties) {1634      // Preserve original behaviour so backwards compatible when still using properties1635      const result = {};1636      const len = this.options.length;16371638      for (let i = 0; i < len; i++) {1639        const key = this.options[i].attributeName();1640        result[key] = key === this._versionOptionName ? this._version : this[key];1641      }1642      return result;1643    }16441645    return this._optionValues;1646  }16471648  /**1649   * Return an object containing merged local and global option values as key-value pairs.1650   *1651   * @return {Object}1652   */1653  optsWithGlobals() {1654    // globals overwrite locals1655    return this._getCommandAndAncestors().reduce(1656      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1657      {}1658    );1659  }16601661  /**1662   * Display error message and exit (or call exitOverride).1663   *1664   * @param {string} message1665   * @param {Object} [errorOptions]1666   * @param {string} [errorOptions.code] - an id string representing the error1667   * @param {number} [errorOptions.exitCode] - used with process.exit1668   */1669  error(message, errorOptions) {1670    // output handling1671    this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1672    if (typeof this._showHelpAfterError === 'string') {1673      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1674    } else if (this._showHelpAfterError) {1675      this._outputConfiguration.writeErr('\n');1676      this.outputHelp({ error: true });1677    }16781679    // exit handling1680    const config = errorOptions || {};1681    const exitCode = config.exitCode || 1;1682    const code = config.code || 'commander.error';1683    this._exit(exitCode, code, message);1684  }16851686  /**1687   * Apply any option related environment variables, if option does1688   * not have a value from cli or client code.1689   *1690   * @private1691   */1692  _parseOptionsEnv() {1693    this.options.forEach((option) => {1694      if (option.envVar && option.envVar in process.env) {1695        const optionKey = option.attributeName();1696        // Priority check. Do not overwrite cli or options from unknown source (client-code).1697        if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1698          if (option.required || option.optional) { // option can take a value1699            // keep very simple, optional always takes value1700            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1701          } else { // boolean1702            // keep very simple, only care that envVar defined and not the value1703            this.emit(`optionEnv:${option.name()}`);1704          }1705        }1706      }1707    });1708  }17091710  /**1711   * Apply any implied option values, if option is undefined or default value.1712   *1713   * @private1714   */1715  _parseOptionsImplied() {1716    const dualHelper = new DualOptions(this.options);1717    const hasCustomOptionValue = (optionKey) => {1718      return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1719    };1720    this.options1721      .filter(option => (option.implied !== undefined) &&1722        hasCustomOptionValue(option.attributeName()) &&1723        dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1724      .forEach((option) => {1725        Object.keys(option.implied)1726          .filter(impliedKey => !hasCustomOptionValue(impliedKey))1727          .forEach(impliedKey => {1728            this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1729          });1730      });1731  }17321733  /**1734   * Argument `name` is missing.1735   *1736   * @param {string} name1737   * @private1738   */17391740  missingArgument(name) {1741    const message = `error: missing required argument '${name}'`;1742    this.error(message, { code: 'commander.missingArgument' });1743  }17441745  /**1746   * `Option` is missing an argument.1747   *1748   * @param {Option} option1749   * @private1750   */17511752  optionMissingArgument(option) {1753    const message = `error: option '${option.flags}' argument missing`;1754    this.error(message, { code: 'commander.optionMissingArgument' });1755  }17561757  /**1758   * `Option` does not have a value, and is a mandatory option.1759   *1760   * @param {Option} option1761   * @private1762   */17631764  missingMandatoryOptionValue(option) {1765    const message = `error: required option '${option.flags}' not specified`;1766    this.error(message, { code: 'commander.missingMandatoryOptionValue' });1767  }17681769  /**1770   * `Option` conflicts with another option.1771   *1772   * @param {Option} option1773   * @param {Option} conflictingOption1774   * @private1775   */1776  _conflictingOption(option, conflictingOption) {1777    // The calling code does not know whether a negated option is the source of the1778    // value, so do some work to take an educated guess.1779    const findBestOptionFromValue = (option) => {1780      const optionKey = option.attributeName();1781      const optionValue = this.getOptionValue(optionKey);1782      const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1783      const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1784      if (negativeOption && (1785        (negativeOption.presetArg === undefined && optionValue === false) ||1786        (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1787      )) {1788        return negativeOption;1789      }1790      return positiveOption || option;1791    };17921793    const getErrorMessage = (option) => {1794      const bestOption = findBestOptionFromValue(option);1795      const optionKey = bestOption.attributeName();1796      const source = this.getOptionValueSource(optionKey);1797      if (source === 'env') {1798        return `environment variable '${bestOption.envVar}'`;1799      }1800      return `option '${bestOption.flags}'`;1801    };18021803    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1804    this.error(message, { code: 'commander.conflictingOption' });1805  }18061807  /**1808   * Unknown option `flag`.1809   *1810   * @param {string} flag1811   * @private1812   */18131814  unknownOption(flag) {1815    if (this._allowUnknownOption) return;1816    let suggestion = '';18171818    if (flag.startsWith('--') && this._showSuggestionAfterError) {1819      // Looping to pick up the global options too1820      let candidateFlags = [];1821      // eslint-disable-next-line @typescript-eslint/no-this-alias1822      let command = this;1823      do {1824        const moreFlags = command.createHelp().visibleOptions(command)1825          .filter(option => option.long)1826          .map(option => option.long);1827        candidateFlags = candidateFlags.concat(moreFlags);1828        command = command.parent;1829      } while (command && !command._enablePositionalOptions);1830      suggestion = suggestSimilar(flag, candidateFlags);1831    }18321833    const message = `error: unknown option '${flag}'${suggestion}`;1834    this.error(message, { code: 'commander.unknownOption' });1835  }18361837  /**1838   * Excess arguments, more than expected.1839   *1840   * @param {string[]} receivedArgs1841   * @private1842   */18431844  _excessArguments(receivedArgs) {1845    if (this._allowExcessArguments) return;18461847    const expected = this.registeredArguments.length;1848    const s = (expected === 1) ? '' : 's';1849    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1850    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1851    this.error(message, { code: 'commander.excessArguments' });1852  }18531854  /**1855   * Unknown command.1856   *1857   * @private1858   */18591860  unknownCommand() {1861    const unknownName = this.args[0];1862    let suggestion = '';18631864    if (this._showSuggestionAfterError) {1865      const candidateNames = [];1866      this.createHelp().visibleCommands(this).forEach((command) => {1867        candidateNames.push(command.name());1868        // just visible alias1869        if (command.alias()) candidateNames.push(command.alias());1870      });1871      suggestion = suggestSimilar(unknownName, candidateNames);1872    }18731874    const message = `error: unknown command '${unknownName}'${suggestion}`;1875    this.error(message, { code: 'commander.unknownCommand' });1876  }18771878  /**1879   * Get or set the program version.1880   *1881   * This method auto-registers the "-V, --version" option which will print the version number.1882   *1883   * You can optionally supply the flags and description to override the defaults.1884   *1885   * @param {string} [str]1886   * @param {string} [flags]1887   * @param {string} [description]1888   * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments1889   */18901891  version(str, flags, description) {1892    if (str === undefined) return this._version;1893    this._version = str;1894    flags = flags || '-V, --version';1895    description = description || 'output the version number';1896    const versionOption = this.createOption(flags, description);1897    this._versionOptionName = versionOption.attributeName();1898    this._registerOption(versionOption);18991900    this.on('option:' + versionOption.name(), () => {1901      this._outputConfiguration.writeOut(`${str}\n`);1902      this._exit(0, 'commander.version', str);1903    });1904    return this;1905  }19061907  /**1908   * Set the description.1909   *1910   * @param {string} [str]1911   * @param {Object} [argsDescription]1912   * @return {(string|Command)}1913   */1914  description(str, argsDescription) {1915    if (str === undefined && argsDescription === undefined) return this._description;1916    this._description = str;1917    if (argsDescription) {1918      this._argsDescription = argsDescription;1919    }1920    return this;1921  }19221923  /**1924   * Set the summary. Used when listed as subcommand of parent.1925   *1926   * @param {string} [str]1927   * @return {(string|Command)}1928   */1929  summary(str) {1930    if (str === undefined) return this._summary;1931    this._summary = str;1932    return this;1933  }19341935  /**1936   * Set an alias for the command.1937   *1938   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1939   *1940   * @param {string} [alias]1941   * @return {(string|Command)}1942   */19431944  alias(alias) {1945    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility19461947    /** @type {Command} */1948    // eslint-disable-next-line @typescript-eslint/no-this-alias1949    let command = this;1950    if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1951      // assume adding alias for last added executable subcommand, rather than this1952      command = this.commands[this.commands.length - 1];1953    }19541955    if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');1956    const matchingCommand = this.parent?._findCommand(alias);1957    if (matchingCommand) {1958      // c.f. _registerCommand1959      const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');1960      throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);1961    }19621963    command._aliases.push(alias);1964    return this;1965  }19661967  /**1968   * Set aliases for the command.1969   *1970   * Only the first alias is shown in the auto-generated help.1971   *1972   * @param {string[]} [aliases]1973   * @return {(string[]|Command)}1974   */19751976  aliases(aliases) {1977    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1978    if (aliases === undefined) return this._aliases;19791980    aliases.forEach((alias) => this.alias(alias));1981    return this;1982  }19831984  /**1985   * Set / get the command usage `str`.1986   *1987   * @param {string} [str]1988   * @return {(string|Command)}1989   */19901991  usage(str) {1992    if (str === undefined) {1993      if (this._usage) return this._usage;19941995      const args = this.registeredArguments.map((arg) => {1996        return humanReadableArgName(arg);1997      });1998      return [].concat(1999        (this.options.length || (this._helpOption !== null) ? '[options]' : []),2000        (this.commands.length ? '[command]' : []),

The first 2,000 of 2,301 lines.