Skip to content
Myr

command.js

This file

Path

lib/command.js

2,299 lines · 72.9 KiB · JavaScript

Last changed by

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

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    for (let command = this; command; command = command.parent) {109      result.push(command);110    }111    return result;112  }113114  /**115   * Define a command.116   *117   * There are two styles of command: pay attention to where to put the description.118   *119   * @example120   * // Command implemented using action handler (description is supplied separately to `.command`)121   * program122   *   .command('clone <source> [destination]')123   *   .description('clone a repository into a newly created directory')124   *   .action((source, destination) => {125   *     console.log('clone command called');126   *   });127   *128   * // Command implemented using separate executable file (description is second parameter to `.command`)129   * program130   *   .command('start <service>', 'start named service')131   *   .command('stop [service]', 'stop named service, or all if no name supplied');132   *133   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`134   * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)135   * @param {Object} [execOpts] - configuration options (for executable)136   * @return {Command} returns new command for action handler, or `this` for executable command137   */138139  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {140    let desc = actionOptsOrExecDesc;141    let opts = execOpts;142    if (typeof desc === 'object' && desc !== null) {143      opts = desc;144      desc = null;145    }146    opts = opts || {};147    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);148149    const cmd = this.createCommand(name);150    if (desc) {151      cmd.description(desc);152      cmd._executableHandler = true;153    }154    if (opts.isDefault) this._defaultCommandName = cmd._name;155    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden156    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor157    if (args) cmd.arguments(args);158    this._registerCommand(cmd);159    cmd.parent = this;160    cmd.copyInheritedSettings(this);161162    if (desc) return this;163    return cmd;164  }165166  /**167   * Factory routine to create a new unattached command.168   *169   * See .command() for creating an attached subcommand, which uses this routine to170   * create the command. You can override createCommand to customise subcommands.171   *172   * @param {string} [name]173   * @return {Command} new command174   */175176  createCommand(name) {177    return new Command(name);178  }179180  /**181   * You can customise the help with a subclass of Help by overriding createHelp,182   * or by overriding Help properties using configureHelp().183   *184   * @return {Help}185   */186187  createHelp() {188    return Object.assign(new Help(), this.configureHelp());189  }190191  /**192   * You can customise the help by overriding Help properties using configureHelp(),193   * or with a subclass of Help by overriding createHelp().194   *195   * @param {Object} [configuration] - configuration options196   * @return {(Command|Object)} `this` command for chaining, or stored configuration197   */198199  configureHelp(configuration) {200    if (configuration === undefined) return this._helpConfiguration;201202    this._helpConfiguration = configuration;203    return this;204  }205206  /**207   * The default output goes to stdout and stderr. You can customise this for special208   * applications. You can also customise the display of errors by overriding outputError.209   *210   * The configuration properties are all functions:211   *212   *     // functions to change where being written, stdout and stderr213   *     writeOut(str)214   *     writeErr(str)215   *     // matching functions to specify width for wrapping help216   *     getOutHelpWidth()217   *     getErrHelpWidth()218   *     // functions based on what is being written out219   *     outputError(str, write) // used for displaying errors, and not used for displaying help220   *221   * @param {Object} [configuration] - configuration options222   * @return {(Command|Object)} `this` command for chaining, or stored configuration223   */224225  configureOutput(configuration) {226    if (configuration === undefined) return this._outputConfiguration;227228    Object.assign(this._outputConfiguration, configuration);229    return this;230  }231232  /**233   * Display the help or a custom message after an error occurs.234   *235   * @param {(boolean|string)} [displayHelp]236   * @return {Command} `this` command for chaining237   */238  showHelpAfterError(displayHelp = true) {239    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;240    this._showHelpAfterError = displayHelp;241    return this;242  }243244  /**245   * Display suggestion of similar commands for unknown commands, or options for unknown options.246   *247   * @param {boolean} [displaySuggestion]248   * @return {Command} `this` command for chaining249   */250  showSuggestionAfterError(displaySuggestion = true) {251    this._showSuggestionAfterError = !!displaySuggestion;252    return this;253  }254255  /**256   * Add a prepared subcommand.257   *258   * See .command() for creating an attached subcommand which inherits settings from its parent.259   *260   * @param {Command} cmd - new subcommand261   * @param {Object} [opts] - configuration options262   * @return {Command} `this` command for chaining263   */264265  addCommand(cmd, opts) {266    if (!cmd._name) {267      throw new Error(`Command passed to .addCommand() must have a name268- specify the name in Command constructor or using .name()`);269    }270271    opts = opts || {};272    if (opts.isDefault) this._defaultCommandName = cmd._name;273    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation274275    this._registerCommand(cmd);276    cmd.parent = this;277    cmd._checkForBrokenPassThrough();278279    return this;280  }281282  /**283   * Factory routine to create a new unattached argument.284   *285   * See .argument() for creating an attached argument, which uses this routine to286   * create the argument. You can override createArgument to return a custom argument.287   *288   * @param {string} name289   * @param {string} [description]290   * @return {Argument} new argument291   */292293  createArgument(name, description) {294    return new Argument(name, description);295  }296297  /**298   * Define argument syntax for command.299   *300   * The default is that the argument is required, and you can explicitly301   * indicate this with <> around the name. Put [] around the name for an optional argument.302   *303   * @example304   * program.argument('<input-file>');305   * program.argument('[output-file]');306   *307   * @param {string} name308   * @param {string} [description]309   * @param {(Function|*)} [fn] - custom argument processing function310   * @param {*} [defaultValue]311   * @return {Command} `this` command for chaining312   */313  argument(name, description, fn, defaultValue) {314    const argument = this.createArgument(name, description);315    if (typeof fn === 'function') {316      argument.default(defaultValue).argParser(fn);317    } else {318      argument.default(fn);319    }320    this.addArgument(argument);321    return this;322  }323324  /**325   * Define argument syntax for command, adding multiple at once (without descriptions).326   *327   * See also .argument().328   *329   * @example330   * program.arguments('<cmd> [env]');331   *332   * @param {string} names333   * @return {Command} `this` command for chaining334   */335336  arguments(names) {337    names.trim().split(/ +/).forEach((detail) => {338      this.argument(detail);339    });340    return this;341  }342343  /**344   * Define argument syntax for command, adding a prepared argument.345   *346   * @param {Argument} argument347   * @return {Command} `this` command for chaining348   */349  addArgument(argument) {350    const previousArgument = this.registeredArguments.slice(-1)[0];351    if (previousArgument && previousArgument.variadic) {352      throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);353    }354    if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {355      throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);356    }357    this.registeredArguments.push(argument);358    return this;359  }360361  /**362   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.363   *364   *    program.helpCommand('help [cmd]');365   *    program.helpCommand('help [cmd]', 'show help');366   *    program.helpCommand(false); // suppress default help command367   *    program.helpCommand(true); // add help command even if no subcommands368   *369   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added370   * @param {string} [description] - custom description371   * @return {Command} `this` command for chaining372   */373374  helpCommand(enableOrNameAndArgs, description) {375    if (typeof enableOrNameAndArgs === 'boolean') {376      this._addImplicitHelpCommand = enableOrNameAndArgs;377      return this;378    }379380    enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';381    const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);382    const helpDescription = description ?? 'display help for command';383384    const helpCommand = this.createCommand(helpName);385    helpCommand.helpOption(false);386    if (helpArgs) helpCommand.arguments(helpArgs);387    if (helpDescription) helpCommand.description(helpDescription);388389    this._addImplicitHelpCommand = true;390    this._helpCommand = helpCommand;391392    return this;393  }394395  /**396   * Add prepared custom help command.397   *398   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`399   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only400   * @return {Command} `this` command for chaining401   */402  addHelpCommand(helpCommand, deprecatedDescription) {403    // If not passed an object, call through to helpCommand for backwards compatibility,404    // as addHelpCommand was originally used like helpCommand is now.405    if (typeof helpCommand !== 'object') {406      this.helpCommand(helpCommand, deprecatedDescription);407      return this;408    }409410    this._addImplicitHelpCommand = true;411    this._helpCommand = helpCommand;412    return this;413  }414415  /**416   * Lazy create help command.417   *418   * @return {(Command|null)}419   * @package420   */421  _getHelpCommand() {422    const hasImplicitHelpCommand = this._addImplicitHelpCommand ??423      (this.commands.length && !this._actionHandler && !this._findCommand('help'));424425    if (hasImplicitHelpCommand) {426      if (this._helpCommand === undefined) {427        this.helpCommand(undefined, undefined); // use default name and description428      }429      return this._helpCommand;430    }431    return null;432  }433434  /**435   * Add hook for life cycle event.436   *437   * @param {string} event438   * @param {Function} listener439   * @return {Command} `this` command for chaining440   */441442  hook(event, listener) {443    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];444    if (!allowedValues.includes(event)) {445      throw new Error(`Unexpected value for event passed to hook : '${event}'.446Expecting one of '${allowedValues.join("', '")}'`);447    }448    if (this._lifeCycleHooks[event]) {449      this._lifeCycleHooks[event].push(listener);450    } else {451      this._lifeCycleHooks[event] = [listener];452    }453    return this;454  }455456  /**457   * Register callback to use as replacement for calling process.exit.458   *459   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing460   * @return {Command} `this` command for chaining461   */462463  exitOverride(fn) {464    if (fn) {465      this._exitCallback = fn;466    } else {467      this._exitCallback = (err) => {468        if (err.code !== 'commander.executeSubCommandAsync') {469          throw err;470        } else {471          // Async callback from spawn events, not useful to throw.472        }473      };474    }475    return this;476  }477478  /**479   * Call process.exit, and _exitCallback if defined.480   *481   * @param {number} exitCode exit code for using with process.exit482   * @param {string} code an id string representing the error483   * @param {string} message human-readable description of the error484   * @return never485   * @private486   */487488  _exit(exitCode, code, message) {489    if (this._exitCallback) {490      this._exitCallback(new CommanderError(exitCode, code, message));491      // Expecting this line is not reached.492    }493    process.exit(exitCode);494  }495496  /**497   * Register callback `fn` for the command.498   *499   * @example500   * program501   *   .command('serve')502   *   .description('start service')503   *   .action(function() {504   *      // do work here505   *   });506   *507   * @param {Function} fn508   * @return {Command} `this` command for chaining509   */510511  action(fn) {512    const listener = (args) => {513      // The .action callback takes an extra parameter which is the command or options.514      const expectedArgsCount = this.registeredArguments.length;515      const actionArgs = args.slice(0, expectedArgsCount);516      if (this._storeOptionsAsProperties) {517        actionArgs[expectedArgsCount] = this; // backwards compatible "options"518      } else {519        actionArgs[expectedArgsCount] = this.opts();520      }521      actionArgs.push(this);522523      return fn.apply(this, actionArgs);524    };525    this._actionHandler = listener;526    return this;527  }528529  /**530   * Factory routine to create a new unattached option.531   *532   * See .option() for creating an attached option, which uses this routine to533   * create the option. You can override createOption to return a custom option.534   *535   * @param {string} flags536   * @param {string} [description]537   * @return {Option} new option538   */539540  createOption(flags, description) {541    return new Option(flags, description);542  }543544  /**545   * Wrap parseArgs to catch 'commander.invalidArgument'.546   *547   * @param {(Option | Argument)} target548   * @param {string} value549   * @param {*} previous550   * @param {string} invalidArgumentMessage551   * @private552   */553554  _callParseArg(target, value, previous, invalidArgumentMessage) {555    try {556      return target.parseArg(value, previous);557    } catch (err) {558      if (err.code === 'commander.invalidArgument') {559        const message = `${invalidArgumentMessage} ${err.message}`;560        this.error(message, { exitCode: err.exitCode, code: err.code });561      }562      throw err;563    }564  }565566  /**567   * Check for option flag conflicts.568   * Register option if no conflicts found, or throw on conflict.569   *570   * @param {Option} option571   * @api private572   */573574  _registerOption(option) {575    const matchingOption = (option.short && this._findOption(option.short)) ||576      (option.long && this._findOption(option.long));577    if (matchingOption) {578      const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;579      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'580-  already used by option '${matchingOption.flags}'`);581    }582583    this.options.push(option);584  }585586  /**587   * Check for command name and alias conflicts with existing commands.588   * Register command if no conflicts found, or throw on conflict.589   *590   * @param {Command} command591   * @api private592   */593594  _registerCommand(command) {595    const knownBy = (cmd) => {596      return [cmd.name()].concat(cmd.aliases());597    };598599    const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));600    if (alreadyUsed) {601      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');602      const newCmd = knownBy(command).join('|');603      throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);604    }605606    this.commands.push(command);607  }608609  /**610   * Add an option.611   *612   * @param {Option} option613   * @return {Command} `this` command for chaining614   */615  addOption(option) {616    this._registerOption(option);617618    const oname = option.name();619    const name = option.attributeName();620621    // store default value622    if (option.negate) {623      // --no-foo is special and defaults foo to true, unless a --foo option is already defined624      const positiveLongFlag = option.long.replace(/^--no-/, '--');625      if (!this._findOption(positiveLongFlag)) {626        this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');627      }628    } else if (option.defaultValue !== undefined) {629      this.setOptionValueWithSource(name, option.defaultValue, 'default');630    }631632    // handler for cli and env supplied values633    const handleOptionValue = (val, invalidValueMessage, valueSource) => {634      // val is null for optional option used without an optional-argument.635      // val is undefined for boolean and negated option.636      if (val == null && option.presetArg !== undefined) {637        val = option.presetArg;638      }639640      // custom processing641      const oldValue = this.getOptionValue(name);642      if (val !== null && option.parseArg) {643        val = this._callParseArg(option, val, oldValue, invalidValueMessage);644      } else if (val !== null && option.variadic) {645        val = option._concatValue(val, oldValue);646      }647648      // Fill-in appropriate missing values. Long winded but easy to follow.649      if (val == null) {650        if (option.negate) {651          val = false;652        } else if (option.isBoolean() || option.optional) {653          val = true;654        } else {655          val = ''; // not normal, parseArg might have failed or be a mock function for testing656        }657      }658      this.setOptionValueWithSource(name, val, valueSource);659    };660661    this.on('option:' + oname, (val) => {662      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;663      handleOptionValue(val, invalidValueMessage, 'cli');664    });665666    if (option.envVar) {667      this.on('optionEnv:' + oname, (val) => {668        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;669        handleOptionValue(val, invalidValueMessage, 'env');670      });671    }672673    return this;674  }675676  /**677   * Internal implementation shared by .option() and .requiredOption()678   *679   * @private680   */681  _optionEx(config, flags, description, fn, defaultValue) {682    if (typeof flags === 'object' && flags instanceof Option) {683      throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');684    }685    const option = this.createOption(flags, description);686    option.makeOptionMandatory(!!config.mandatory);687    if (typeof fn === 'function') {688      option.default(defaultValue).argParser(fn);689    } else if (fn instanceof RegExp) {690      // deprecated691      const regex = fn;692      fn = (val, def) => {693        const m = regex.exec(val);694        return m ? m[0] : def;695      };696      option.default(defaultValue).argParser(fn);697    } else {698      option.default(fn);699    }700701    return this.addOption(option);702  }703704  /**705   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.706   *707   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required708   * option-argument is indicated by `<>` and an optional option-argument by `[]`.709   *710   * See the README for more details, and see also addOption() and requiredOption().711   *712   * @example713   * program714   *     .option('-p, --pepper', 'add pepper')715   *     .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument716   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default717   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function718   *719   * @param {string} flags720   * @param {string} [description]721   * @param {(Function|*)} [parseArg] - custom option processing function or default value722   * @param {*} [defaultValue]723   * @return {Command} `this` command for chaining724   */725726  option(flags, description, parseArg, defaultValue) {727    return this._optionEx({}, flags, description, parseArg, defaultValue);728  }729730  /**731  * Add a required option which must have a value after parsing. This usually means732  * the option must be specified on the command line. (Otherwise the same as .option().)733  *734  * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.735  *736  * @param {string} flags737  * @param {string} [description]738  * @param {(Function|*)} [parseArg] - custom option processing function or default value739  * @param {*} [defaultValue]740  * @return {Command} `this` command for chaining741  */742743  requiredOption(flags, description, parseArg, defaultValue) {744    return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);745  }746747  /**748   * Alter parsing of short flags with optional values.749   *750   * @example751   * // for `.option('-f,--flag [value]'):752   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour753   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`754   *755   * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.756   */757  combineFlagAndOptionalValue(combine = true) {758    this._combineFlagAndOptionalValue = !!combine;759    return this;760  }761762  /**763   * Allow unknown options on the command line.764   *765   * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown766   * for unknown options.767   */768  allowUnknownOption(allowUnknown = true) {769    this._allowUnknownOption = !!allowUnknown;770    return this;771  }772773  /**774   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.775   *776   * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown777   * for excess arguments.778   */779  allowExcessArguments(allowExcess = true) {780    this._allowExcessArguments = !!allowExcess;781    return this;782  }783784  /**785   * Enable positional options. Positional means global options are specified before subcommands which lets786   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.787   * The default behaviour is non-positional and global options may appear anywhere on the command line.788   *789   * @param {boolean} [positional=true]790   */791  enablePositionalOptions(positional = true) {792    this._enablePositionalOptions = !!positional;793    return this;794  }795796  /**797   * Pass through options that come after command-arguments rather than treat them as command-options,798   * so actual command-options come before command-arguments. Turning this on for a subcommand requires799   * positional options to have been enabled on the program (parent commands).800   * The default behaviour is non-positional and options may appear before or after command-arguments.801   *802   * @param {boolean} [passThrough=true]803   * for unknown options.804   */805  passThroughOptions(passThrough = true) {806    this._passThroughOptions = !!passThrough;807    this._checkForBrokenPassThrough();808    return this;809  }810811  /**812   * @private813   */814815  _checkForBrokenPassThrough() {816    if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {817      throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);818    }819  }820821  /**822    * Whether to store option values as properties on command object,823    * or store separately (specify false). In both cases the option values can be accessed using .opts().824    *825    * @param {boolean} [storeAsProperties=true]826    * @return {Command} `this` command for chaining827    */828829  storeOptionsAsProperties(storeAsProperties = true) {830    if (this.options.length) {831      throw new Error('call .storeOptionsAsProperties() before adding options');832    }833    if (Object.keys(this._optionValues).length) {834      throw new Error('call .storeOptionsAsProperties() before setting option values');835    }836    this._storeOptionsAsProperties = !!storeAsProperties;837    return this;838  }839840  /**841   * Retrieve option value.842   *843   * @param {string} key844   * @return {Object} value845   */846847  getOptionValue(key) {848    if (this._storeOptionsAsProperties) {849      return this[key];850    }851    return this._optionValues[key];852  }853854  /**855   * Store option value.856   *857   * @param {string} key858   * @param {Object} value859   * @return {Command} `this` command for chaining860   */861862  setOptionValue(key, value) {863    return this.setOptionValueWithSource(key, value, undefined);864  }865866  /**867    * Store option value and where the value came from.868    *869    * @param {string} key870    * @param {Object} value871    * @param {string} source - expected values are default/config/env/cli/implied872    * @return {Command} `this` command for chaining873    */874875  setOptionValueWithSource(key, value, source) {876    if (this._storeOptionsAsProperties) {877      this[key] = value;878    } else {879      this._optionValues[key] = value;880    }881    this._optionValueSources[key] = source;882    return this;883  }884885  /**886    * Get source of option value.887    * Expected values are default | config | env | cli | implied888    *889    * @param {string} key890    * @return {string}891    */892893  getOptionValueSource(key) {894    return this._optionValueSources[key];895  }896897  /**898    * Get source of option value. See also .optsWithGlobals().899    * Expected values are default | config | env | cli | implied900    *901    * @param {string} key902    * @return {string}903    */904905  getOptionValueSourceWithGlobals(key) {906    // global overwrites local, like optsWithGlobals907    let source;908    this._getCommandAndAncestors().forEach((cmd) => {909      if (cmd.getOptionValueSource(key) !== undefined) {910        source = cmd.getOptionValueSource(key);911      }912    });913    return source;914  }915916  /**917   * Get user arguments from implied or explicit arguments.918   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.919   *920   * @private921   */922923  _prepareUserArgs(argv, parseOptions) {924    if (argv !== undefined && !Array.isArray(argv)) {925      throw new Error('first parameter to parse must be array or undefined');926    }927    parseOptions = parseOptions || {};928929    // Default to using process.argv930    if (argv === undefined) {931      argv = process.argv;932      // @ts-ignore: unknown property933      if (process.versions && process.versions.electron) {934        parseOptions.from = 'electron';935      }936    }937    this.rawArgs = argv.slice();938939    // make it a little easier for callers by supporting various argv conventions940    let userArgs;941    switch (parseOptions.from) {942      case undefined:943      case 'node':944        this._scriptPath = argv[1];945        userArgs = argv.slice(2);946        break;947      case 'electron':948        // @ts-ignore: unknown property949        if (process.defaultApp) {950          this._scriptPath = argv[1];951          userArgs = argv.slice(2);952        } else {953          userArgs = argv.slice(1);954        }955        break;956      case 'user':957        userArgs = argv.slice(0);958        break;959      default:960        throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);961    }962963    // Find default name for program from arguments.964    if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);965    this._name = this._name || 'program';966967    return userArgs;968  }969970  /**971   * Parse `argv`, setting options and invoking commands when defined.972   *973   * The default expectation is that the arguments are from node and have the application as argv[0]974   * and the script being run in argv[1], with user parameters after that.975   *976   * @example977   * program.parse(process.argv);978   * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions979   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]980   *981   * @param {string[]} [argv] - optional, defaults to process.argv982   * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron983   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'984   * @return {Command} `this` command for chaining985   */986987  parse(argv, parseOptions) {988    const userArgs = this._prepareUserArgs(argv, parseOptions);989    this._parseCommand([], userArgs);990991    return this;992  }993994  /**995   * Parse `argv`, setting options and invoking commands when defined.996   *997   * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.998   *999   * The default expectation is that the arguments are from node and have the application as argv[0]1000   * and the script being run in argv[1], with user parameters after that.1001   *1002   * @example1003   * await program.parseAsync(process.argv);1004   * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1005   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1006   *1007   * @param {string[]} [argv]1008   * @param {Object} [parseOptions]1009   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1010   * @return {Promise}1011   */10121013  async parseAsync(argv, parseOptions) {1014    const userArgs = this._prepareUserArgs(argv, parseOptions);1015    await this._parseCommand([], userArgs);10161017    return this;1018  }10191020  /**1021   * Execute a sub-command executable.1022   *1023   * @private1024   */10251026  _executeSubCommand(subcommand, args) {1027    args = args.slice();1028    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1029    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];10301031    function findFile(baseDir, baseName) {1032      // Look for specified file1033      const localBin = path.resolve(baseDir, baseName);1034      if (fs.existsSync(localBin)) return localBin;10351036      // Stop looking if candidate already has an expected extension.1037      if (sourceExt.includes(path.extname(baseName))) return undefined;10381039      // Try all the extensions.1040      const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));1041      if (foundExt) return `${localBin}${foundExt}`;10421043      return undefined;1044    }10451046    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1047    this._checkForMissingMandatoryOptions();1048    this._checkForConflictingOptions();10491050    // executableFile and executableDir might be full path, or just a name1051    let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1052    let executableDir = this._executableDir || '';1053    if (this._scriptPath) {1054      let resolvedScriptPath; // resolve possible symlink for installed npm binary1055      try {1056        resolvedScriptPath = fs.realpathSync(this._scriptPath);1057      } catch (err) {1058        resolvedScriptPath = this._scriptPath;1059      }1060      executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);1061    }10621063    // Look for a local file in preference to a command in PATH.1064    if (executableDir) {1065      let localFile = findFile(executableDir, executableFile);10661067      // Legacy search using prefix of script name instead of command name1068      if (!localFile && !subcommand._executableFile && this._scriptPath) {1069        const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1070        if (legacyName !== this._name) {1071          localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);1072        }1073      }1074      executableFile = localFile || executableFile;1075    }10761077    launchWithNode = sourceExt.includes(path.extname(executableFile));10781079    let proc;1080    if (process.platform !== 'win32') {1081      if (launchWithNode) {1082        args.unshift(executableFile);1083        // add executable arguments to spawn1084        args = incrementNodeInspectorPort(process.execArgv).concat(args);10851086        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1087      } else {1088        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1089      }1090    } else {1091      args.unshift(executableFile);1092      // add executable arguments to spawn1093      args = incrementNodeInspectorPort(process.execArgv).concat(args);1094      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1095    }10961097    if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1098      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1099      signals.forEach((signal) => {1100        // @ts-ignore1101        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, _signal) => {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-ignore1121      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-ignore1131      } 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      let command = this;1822      do {1823        const moreFlags = command.createHelp().visibleOptions(command)1824          .filter(option => option.long)1825          .map(option => option.long);1826        candidateFlags = candidateFlags.concat(moreFlags);1827        command = command.parent;1828      } while (command && !command._enablePositionalOptions);1829      suggestion = suggestSimilar(flag, candidateFlags);1830    }18311832    const message = `error: unknown option '${flag}'${suggestion}`;1833    this.error(message, { code: 'commander.unknownOption' });1834  }18351836  /**1837   * Excess arguments, more than expected.1838   *1839   * @param {string[]} receivedArgs1840   * @private1841   */18421843  _excessArguments(receivedArgs) {1844    if (this._allowExcessArguments) return;18451846    const expected = this.registeredArguments.length;1847    const s = (expected === 1) ? '' : 's';1848    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1849    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1850    this.error(message, { code: 'commander.excessArguments' });1851  }18521853  /**1854   * Unknown command.1855   *1856   * @private1857   */18581859  unknownCommand() {1860    const unknownName = this.args[0];1861    let suggestion = '';18621863    if (this._showSuggestionAfterError) {1864      const candidateNames = [];1865      this.createHelp().visibleCommands(this).forEach((command) => {1866        candidateNames.push(command.name());1867        // just visible alias1868        if (command.alias()) candidateNames.push(command.alias());1869      });1870      suggestion = suggestSimilar(unknownName, candidateNames);1871    }18721873    const message = `error: unknown command '${unknownName}'${suggestion}`;1874    this.error(message, { code: 'commander.unknownCommand' });1875  }18761877  /**1878   * Get or set the program version.1879   *1880   * This method auto-registers the "-V, --version" option which will print the version number.1881   *1882   * You can optionally supply the flags and description to override the defaults.1883   *1884   * @param {string} [str]1885   * @param {string} [flags]1886   * @param {string} [description]1887   * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments1888   */18891890  version(str, flags, description) {1891    if (str === undefined) return this._version;1892    this._version = str;1893    flags = flags || '-V, --version';1894    description = description || 'output the version number';1895    const versionOption = this.createOption(flags, description);1896    this._versionOptionName = versionOption.attributeName();1897    this._registerOption(versionOption);18981899    this.on('option:' + versionOption.name(), () => {1900      this._outputConfiguration.writeOut(`${str}\n`);1901      this._exit(0, 'commander.version', str);1902    });1903    return this;1904  }19051906  /**1907   * Set the description.1908   *1909   * @param {string} [str]1910   * @param {Object} [argsDescription]1911   * @return {(string|Command)}1912   */1913  description(str, argsDescription) {1914    if (str === undefined && argsDescription === undefined) return this._description;1915    this._description = str;1916    if (argsDescription) {1917      this._argsDescription = argsDescription;1918    }1919    return this;1920  }19211922  /**1923   * Set the summary. Used when listed as subcommand of parent.1924   *1925   * @param {string} [str]1926   * @return {(string|Command)}1927   */1928  summary(str) {1929    if (str === undefined) return this._summary;1930    this._summary = str;1931    return this;1932  }19331934  /**1935   * Set an alias for the command.1936   *1937   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1938   *1939   * @param {string} [alias]1940   * @return {(string|Command)}1941   */19421943  alias(alias) {1944    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility19451946    /** @type {Command} */1947    let command = this;1948    if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1949      // assume adding alias for last added executable subcommand, rather than this1950      command = this.commands[this.commands.length - 1];1951    }19521953    if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');1954    const matchingCommand = this.parent?._findCommand(alias);1955    if (matchingCommand) {1956      // c.f. _registerCommand1957      const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');1958      throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);1959    }19601961    command._aliases.push(alias);1962    return this;1963  }19641965  /**1966   * Set aliases for the command.1967   *1968   * Only the first alias is shown in the auto-generated help.1969   *1970   * @param {string[]} [aliases]1971   * @return {(string[]|Command)}1972   */19731974  aliases(aliases) {1975    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1976    if (aliases === undefined) return this._aliases;19771978    aliases.forEach((alias) => this.alias(alias));1979    return this;1980  }19811982  /**1983   * Set / get the command usage `str`.1984   *1985   * @param {string} [str]1986   * @return {(string|Command)}1987   */19881989  usage(str) {1990    if (str === undefined) {1991      if (this._usage) return this._usage;19921993      const args = this.registeredArguments.map((arg) => {1994        return humanReadableArgName(arg);1995      });1996      return [].concat(1997        (this.options.length || (this._helpOption !== null) ? '[options]' : []),1998        (this.commands.length ? '[command]' : []),1999        (this.registeredArguments.length ? args : [])2000      ).join(' ');

The first 2,000 of 2,299 lines.