Skip to content
Myr

command.js

This file

Path

lib/command.js

2,791 lines · 85.7 KiB · JavaScript

Last changed by

Merge from develop (#2482)John Geebefore adoptionb51c0ea

History of this file

Take it

1const EventEmitter = require('node:events').EventEmitter;2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help, stripColor } = 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 = false;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;58    this._savedState = null; // used in save/restoreStateBeforeParse5960    // see configureOutput() for docs61    this._outputConfiguration = {62      writeOut: (str) => process.stdout.write(str),63      writeErr: (str) => process.stderr.write(str),64      outputError: (str, write) => write(str),65      getOutHelpWidth: () =>66        process.stdout.isTTY ? process.stdout.columns : undefined,67      getErrHelpWidth: () =>68        process.stderr.isTTY ? process.stderr.columns : undefined,69      getOutHasColors: () =>70        useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),71      getErrHasColors: () =>72        useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),73      stripColor: (str) => stripColor(str),74    };7576    this._hidden = false;77    /** @type {(Option | null | undefined)} */78    this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.79    this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80    /** @type {Command} */81    this._helpCommand = undefined; // lazy initialised, inherited82    this._helpConfiguration = {};83    /** @type {string | undefined} */84    this._helpGroupHeading = undefined; // soft initialised when added to parent85    /** @type {string | undefined} */86    this._defaultCommandGroup = undefined;87    /** @type {string | undefined} */88    this._defaultOptionGroup = undefined;89  }9091  /**92   * Copy settings that are useful to have in common across root command and subcommands.93   *94   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)95   *96   * @param {Command} sourceCommand97   * @return {Command} `this` command for chaining98   */99  copyInheritedSettings(sourceCommand) {100    this._outputConfiguration = sourceCommand._outputConfiguration;101    this._helpOption = sourceCommand._helpOption;102    this._helpCommand = sourceCommand._helpCommand;103    this._helpConfiguration = sourceCommand._helpConfiguration;104    this._exitCallback = sourceCommand._exitCallback;105    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;106    this._combineFlagAndOptionalValue =107      sourceCommand._combineFlagAndOptionalValue;108    this._allowExcessArguments = sourceCommand._allowExcessArguments;109    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;110    this._showHelpAfterError = sourceCommand._showHelpAfterError;111    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;112113    return this;114  }115116  /**117   * @returns {Command[]}118   * @private119   */120121  _getCommandAndAncestors() {122    const result = [];123    // eslint-disable-next-line @typescript-eslint/no-this-alias124    for (let command = this; command; command = command.parent) {125      result.push(command);126    }127    return result;128  }129130  /**131   * Define a command.132   *133   * There are two styles of command: pay attention to where to put the description.134   *135   * @example136   * // Command implemented using action handler (description is supplied separately to `.command`)137   * program138   *   .command('clone <source> [destination]')139   *   .description('clone a repository into a newly created directory')140   *   .action((source, destination) => {141   *     console.log('clone command called');142   *   });143   *144   * // Command implemented using separate executable file (description is second parameter to `.command`)145   * program146   *   .command('start <service>', 'start named service')147   *   .command('stop [service]', 'stop named service, or all if no name supplied');148   *149   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`150   * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)151   * @param {object} [execOpts] - configuration options (for executable)152   * @return {Command} returns new command for action handler, or `this` for executable command153   */154155  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {156    let desc = actionOptsOrExecDesc;157    let opts = execOpts;158    if (typeof desc === 'object' && desc !== null) {159      opts = desc;160      desc = null;161    }162    opts = opts || {};163    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);164165    const cmd = this.createCommand(name);166    if (desc) {167      cmd.description(desc);168      cmd._executableHandler = true;169    }170    if (opts.isDefault) this._defaultCommandName = cmd._name;171    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden172    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor173    if (args) cmd.arguments(args);174    this._registerCommand(cmd);175    cmd.parent = this;176    cmd.copyInheritedSettings(this);177178    if (desc) return this;179    return cmd;180  }181182  /**183   * Factory routine to create a new unattached command.184   *185   * See .command() for creating an attached subcommand, which uses this routine to186   * create the command. You can override createCommand to customise subcommands.187   *188   * @param {string} [name]189   * @return {Command} new command190   */191192  createCommand(name) {193    return new Command(name);194  }195196  /**197   * You can customise the help with a subclass of Help by overriding createHelp,198   * or by overriding Help properties using configureHelp().199   *200   * @return {Help}201   */202203  createHelp() {204    return Object.assign(new Help(), this.configureHelp());205  }206207  /**208   * You can customise the help by overriding Help properties using configureHelp(),209   * or with a subclass of Help by overriding createHelp().210   *211   * @param {object} [configuration] - configuration options212   * @return {(Command | object)} `this` command for chaining, or stored configuration213   */214215  configureHelp(configuration) {216    if (configuration === undefined) return this._helpConfiguration;217218    this._helpConfiguration = configuration;219    return this;220  }221222  /**223   * The default output goes to stdout and stderr. You can customise this for special224   * applications. You can also customise the display of errors by overriding outputError.225   *226   * The configuration properties are all functions:227   *228   *     // change how output being written, defaults to stdout and stderr229   *     writeOut(str)230   *     writeErr(str)231   *     // change how output being written for errors, defaults to writeErr232   *     outputError(str, write) // used for displaying errors and not used for displaying help233   *     // specify width for wrapping help234   *     getOutHelpWidth()235   *     getErrHelpWidth()236   *     // color support, currently only used with Help237   *     getOutHasColors()238   *     getErrHasColors()239   *     stripColor() // used to remove ANSI escape codes if output does not have colors240   *241   * @param {object} [configuration] - configuration options242   * @return {(Command | object)} `this` command for chaining, or stored configuration243   */244245  configureOutput(configuration) {246    if (configuration === undefined) return this._outputConfiguration;247248    this._outputConfiguration = {249      ...this._outputConfiguration,250      ...configuration,251    };252    return this;253  }254255  /**256   * Display the help or a custom message after an error occurs.257   *258   * @param {(boolean|string)} [displayHelp]259   * @return {Command} `this` command for chaining260   */261  showHelpAfterError(displayHelp = true) {262    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;263    this._showHelpAfterError = displayHelp;264    return this;265  }266267  /**268   * Display suggestion of similar commands for unknown commands, or options for unknown options.269   *270   * @param {boolean} [displaySuggestion]271   * @return {Command} `this` command for chaining272   */273  showSuggestionAfterError(displaySuggestion = true) {274    this._showSuggestionAfterError = !!displaySuggestion;275    return this;276  }277278  /**279   * Add a prepared subcommand.280   *281   * See .command() for creating an attached subcommand which inherits settings from its parent.282   *283   * @param {Command} cmd - new subcommand284   * @param {object} [opts] - configuration options285   * @return {Command} `this` command for chaining286   */287288  addCommand(cmd, opts) {289    if (!cmd._name) {290      throw new Error(`Command passed to .addCommand() must have a name291- specify the name in Command constructor or using .name()`);292    }293294    opts = opts || {};295    if (opts.isDefault) this._defaultCommandName = cmd._name;296    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation297298    this._registerCommand(cmd);299    cmd.parent = this;300    cmd._checkForBrokenPassThrough();301302    return this;303  }304305  /**306   * Factory routine to create a new unattached argument.307   *308   * See .argument() for creating an attached argument, which uses this routine to309   * create the argument. You can override createArgument to return a custom argument.310   *311   * @param {string} name312   * @param {string} [description]313   * @return {Argument} new argument314   */315316  createArgument(name, description) {317    return new Argument(name, description);318  }319320  /**321   * Define argument syntax for command.322   *323   * The default is that the argument is required, and you can explicitly324   * indicate this with <> around the name. Put [] around the name for an optional argument.325   *326   * @example327   * program.argument('<input-file>');328   * program.argument('[output-file]');329   *330   * @param {string} name331   * @param {string} [description]332   * @param {(Function|*)} [parseArg] - custom argument processing function or default value333   * @param {*} [defaultValue]334   * @return {Command} `this` command for chaining335   */336  argument(name, description, parseArg, defaultValue) {337    const argument = this.createArgument(name, description);338    if (typeof parseArg === 'function') {339      argument.default(defaultValue).argParser(parseArg);340    } else {341      argument.default(parseArg);342    }343    this.addArgument(argument);344    return this;345  }346347  /**348   * Define argument syntax for command, adding multiple at once (without descriptions).349   *350   * See also .argument().351   *352   * @example353   * program.arguments('<cmd> [env]');354   *355   * @param {string} names356   * @return {Command} `this` command for chaining357   */358359  arguments(names) {360    names361      .trim()362      .split(/ +/)363      .forEach((detail) => {364        this.argument(detail);365      });366    return this;367  }368369  /**370   * Define argument syntax for command, adding a prepared argument.371   *372   * @param {Argument} argument373   * @return {Command} `this` command for chaining374   */375  addArgument(argument) {376    const previousArgument = this.registeredArguments.slice(-1)[0];377    if (previousArgument?.variadic) {378      throw new Error(379        `only the last argument can be variadic '${previousArgument.name()}'`,380      );381    }382    if (383      argument.required &&384      argument.defaultValue !== undefined &&385      argument.parseArg === undefined386    ) {387      throw new Error(388        `a default value for a required argument is never used: '${argument.name()}'`,389      );390    }391    this.registeredArguments.push(argument);392    return this;393  }394395  /**396   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.397   *398   * @example399   *    program.helpCommand('help [cmd]');400   *    program.helpCommand('help [cmd]', 'show help');401   *    program.helpCommand(false); // suppress default help command402   *    program.helpCommand(true); // add help command even if no subcommands403   *404   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added405   * @param {string} [description] - custom description406   * @return {Command} `this` command for chaining407   */408409  helpCommand(enableOrNameAndArgs, description) {410    if (typeof enableOrNameAndArgs === 'boolean') {411      this._addImplicitHelpCommand = enableOrNameAndArgs;412      if (enableOrNameAndArgs && this._defaultCommandGroup) {413        // make the command to store the group414        this._initCommandGroup(this._getHelpCommand());415      }416      return this;417    }418419    const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';420    const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);421    const helpDescription = description ?? 'display help for command';422423    const helpCommand = this.createCommand(helpName);424    helpCommand.helpOption(false);425    if (helpArgs) helpCommand.arguments(helpArgs);426    if (helpDescription) helpCommand.description(helpDescription);427428    this._addImplicitHelpCommand = true;429    this._helpCommand = helpCommand;430    // init group unless lazy create431    if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);432433    return this;434  }435436  /**437   * Add prepared custom help command.438   *439   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`440   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only441   * @return {Command} `this` command for chaining442   */443  addHelpCommand(helpCommand, deprecatedDescription) {444    // If not passed an object, call through to helpCommand for backwards compatibility,445    // as addHelpCommand was originally used like helpCommand is now.446    if (typeof helpCommand !== 'object') {447      this.helpCommand(helpCommand, deprecatedDescription);448      return this;449    }450451    this._addImplicitHelpCommand = true;452    this._helpCommand = helpCommand;453    this._initCommandGroup(helpCommand);454    return this;455  }456457  /**458   * Lazy create help command.459   *460   * @return {(Command|null)}461   * @package462   */463  _getHelpCommand() {464    const hasImplicitHelpCommand =465      this._addImplicitHelpCommand ??466      (this.commands.length &&467        !this._actionHandler &&468        !this._findCommand('help'));469470    if (hasImplicitHelpCommand) {471      if (this._helpCommand === undefined) {472        this.helpCommand(undefined, undefined); // use default name and description473      }474      return this._helpCommand;475    }476    return null;477  }478479  /**480   * Add hook for life cycle event.481   *482   * @param {string} event483   * @param {Function} listener484   * @return {Command} `this` command for chaining485   */486487  hook(event, listener) {488    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];489    if (!allowedValues.includes(event)) {490      throw new Error(`Unexpected value for event passed to hook : '${event}'.491Expecting one of '${allowedValues.join("', '")}'`);492    }493    if (this._lifeCycleHooks[event]) {494      this._lifeCycleHooks[event].push(listener);495    } else {496      this._lifeCycleHooks[event] = [listener];497    }498    return this;499  }500501  /**502   * Register callback to use as replacement for calling process.exit.503   *504   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing505   * @return {Command} `this` command for chaining506   */507508  exitOverride(fn) {509    if (fn) {510      this._exitCallback = fn;511    } else {512      this._exitCallback = (err) => {513        if (err.code !== 'commander.executeSubCommandAsync') {514          throw err;515        } else {516          // Async callback from spawn events, not useful to throw.517        }518      };519    }520    return this;521  }522523  /**524   * Call process.exit, and _exitCallback if defined.525   *526   * @param {number} exitCode exit code for using with process.exit527   * @param {string} code an id string representing the error528   * @param {string} message human-readable description of the error529   * @return never530   * @private531   */532533  _exit(exitCode, code, message) {534    if (this._exitCallback) {535      this._exitCallback(new CommanderError(exitCode, code, message));536      // Expecting this line is not reached.537    }538    process.exit(exitCode);539  }540541  /**542   * Register callback `fn` for the command.543   *544   * @example545   * program546   *   .command('serve')547   *   .description('start service')548   *   .action(function() {549   *      // do work here550   *   });551   *552   * @param {Function} fn553   * @return {Command} `this` command for chaining554   */555556  action(fn) {557    const listener = (args) => {558      // The .action callback takes an extra parameter which is the command or options.559      const expectedArgsCount = this.registeredArguments.length;560      const actionArgs = args.slice(0, expectedArgsCount);561      if (this._storeOptionsAsProperties) {562        actionArgs[expectedArgsCount] = this; // backwards compatible "options"563      } else {564        actionArgs[expectedArgsCount] = this.opts();565      }566      actionArgs.push(this);567568      return fn.apply(this, actionArgs);569    };570    this._actionHandler = listener;571    return this;572  }573574  /**575   * Factory routine to create a new unattached option.576   *577   * See .option() for creating an attached option, which uses this routine to578   * create the option. You can override createOption to return a custom option.579   *580   * @param {string} flags581   * @param {string} [description]582   * @return {Option} new option583   */584585  createOption(flags, description) {586    return new Option(flags, description);587  }588589  /**590   * Wrap parseArgs to catch 'commander.invalidArgument'.591   *592   * @param {(Option | Argument)} target593   * @param {string} value594   * @param {*} previous595   * @param {string} invalidArgumentMessage596   * @private597   */598599  _callParseArg(target, value, previous, invalidArgumentMessage) {600    try {601      return target.parseArg(value, previous);602    } catch (err) {603      if (err.code === 'commander.invalidArgument') {604        const message = `${invalidArgumentMessage} ${err.message}`;605        this.error(message, { exitCode: err.exitCode, code: err.code });606      }607      throw err;608    }609  }610611  /**612   * Check for option flag conflicts.613   * Register option if no conflicts found, or throw on conflict.614   *615   * @param {Option} option616   * @private617   */618619  _registerOption(option) {620    const matchingOption =621      (option.short && this._findOption(option.short)) ||622      (option.long && this._findOption(option.long));623    if (matchingOption) {624      const matchingFlag =625        option.long && this._findOption(option.long)626          ? option.long627          : option.short;628      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'629-  already used by option '${matchingOption.flags}'`);630    }631632    this._initOptionGroup(option);633    this.options.push(option);634  }635636  /**637   * Check for command name and alias conflicts with existing commands.638   * Register command if no conflicts found, or throw on conflict.639   *640   * @param {Command} command641   * @private642   */643644  _registerCommand(command) {645    const knownBy = (cmd) => {646      return [cmd.name()].concat(cmd.aliases());647    };648649    const alreadyUsed = knownBy(command).find((name) =>650      this._findCommand(name),651    );652    if (alreadyUsed) {653      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');654      const newCmd = knownBy(command).join('|');655      throw new Error(656        `cannot add command '${newCmd}' as already have command '${existingCmd}'`,657      );658    }659660    this._initCommandGroup(command);661    this.commands.push(command);662  }663664  /**665   * Add an option.666   *667   * @param {Option} option668   * @return {Command} `this` command for chaining669   */670  addOption(option) {671    this._registerOption(option);672673    const oname = option.name();674    const name = option.attributeName();675676    // store default value677    if (option.defaultValue !== undefined) {678      this.setOptionValueWithSource(name, option.defaultValue, 'default');679    }680681    // handler for cli and env supplied values682    const handleOptionValue = (val, invalidValueMessage, valueSource) => {683      // val is null for optional option used without an optional-argument.684      // val is undefined for boolean and negated option.685      if (val == null && option.presetArg !== undefined) {686        val = option.presetArg;687      }688689      // custom processing690      const oldValue = this.getOptionValue(name);691      if (val !== null && option.parseArg) {692        val = this._callParseArg(option, val, oldValue, invalidValueMessage);693      } else if (val !== null && option.variadic) {694        val = option._collectValue(val, oldValue);695      }696697      // Fill-in appropriate missing values. Long winded but easy to follow.698      if (val == null) {699        if (option.negate) {700          val = false;701        } else if (option.isBoolean() || option.optional) {702          val = true;703        } else {704          val = ''; // not normal, parseArg might have failed or be a mock function for testing705        }706      }707      this.setOptionValueWithSource(name, val, valueSource);708    };709710    this.on('option:' + oname, (val) => {711      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;712      handleOptionValue(val, invalidValueMessage, 'cli');713    });714715    if (option.envVar) {716      this.on('optionEnv:' + oname, (val) => {717        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;718        handleOptionValue(val, invalidValueMessage, 'env');719      });720    }721722    return this;723  }724725  /**726   * Internal implementation shared by .option() and .requiredOption()727   *728   * @return {Command} `this` command for chaining729   * @private730   */731  _optionEx(config, flags, description, fn, defaultValue) {732    if (typeof flags === 'object' && flags instanceof Option) {733      throw new Error(734        'To add an Option object use addOption() instead of option() or requiredOption()',735      );736    }737    const option = this.createOption(flags, description);738    option.makeOptionMandatory(!!config.mandatory);739    if (typeof fn === 'function') {740      option.default(defaultValue).argParser(fn);741    } else if (fn instanceof RegExp) {742      // deprecated743      const regex = fn;744      fn = (val, def) => {745        const m = regex.exec(val);746        return m ? m[0] : def;747      };748      option.default(defaultValue).argParser(fn);749    } else {750      option.default(fn);751    }752753    return this.addOption(option);754  }755756  /**757   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.758   *759   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required760   * option-argument is indicated by `<>` and an optional option-argument by `[]`.761   *762   * See the README for more details, and see also addOption() and requiredOption().763   *764   * @example765   * program766   *     .option('-p, --pepper', 'add pepper')767   *     .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument768   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default769   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function770   *771   * @param {string} flags772   * @param {string} [description]773   * @param {(Function|*)} [parseArg] - custom option processing function or default value774   * @param {*} [defaultValue]775   * @return {Command} `this` command for chaining776   */777778  option(flags, description, parseArg, defaultValue) {779    return this._optionEx({}, flags, description, parseArg, defaultValue);780  }781782  /**783   * Add a required option which must have a value after parsing. This usually means784   * the option must be specified on the command line. (Otherwise the same as .option().)785   *786   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.787   *788   * @param {string} flags789   * @param {string} [description]790   * @param {(Function|*)} [parseArg] - custom option processing function or default value791   * @param {*} [defaultValue]792   * @return {Command} `this` command for chaining793   */794795  requiredOption(flags, description, parseArg, defaultValue) {796    return this._optionEx(797      { mandatory: true },798      flags,799      description,800      parseArg,801      defaultValue,802    );803  }804805  /**806   * Alter parsing of short flags with optional values.807   *808   * @example809   * // for `.option('-f,--flag [value]'):810   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour811   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`812   *813   * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.814   * @return {Command} `this` command for chaining815   */816  combineFlagAndOptionalValue(combine = true) {817    this._combineFlagAndOptionalValue = !!combine;818    return this;819  }820821  /**822   * Allow unknown options on the command line.823   *824   * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.825   * @return {Command} `this` command for chaining826   */827  allowUnknownOption(allowUnknown = true) {828    this._allowUnknownOption = !!allowUnknown;829    return this;830  }831832  /**833   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.834   *835   * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.836   * @return {Command} `this` command for chaining837   */838  allowExcessArguments(allowExcess = true) {839    this._allowExcessArguments = !!allowExcess;840    return this;841  }842843  /**844   * Enable positional options. Positional means global options are specified before subcommands which lets845   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.846   * The default behaviour is non-positional and global options may appear anywhere on the command line.847   *848   * @param {boolean} [positional]849   * @return {Command} `this` command for chaining850   */851  enablePositionalOptions(positional = true) {852    this._enablePositionalOptions = !!positional;853    return this;854  }855856  /**857   * Pass through options that come after command-arguments rather than treat them as command-options,858   * so actual command-options come before command-arguments. Turning this on for a subcommand requires859   * positional options to have been enabled on the program (parent commands).860   * The default behaviour is non-positional and options may appear before or after command-arguments.861   *862   * @param {boolean} [passThrough] for unknown options.863   * @return {Command} `this` command for chaining864   */865  passThroughOptions(passThrough = true) {866    this._passThroughOptions = !!passThrough;867    this._checkForBrokenPassThrough();868    return this;869  }870871  /**872   * @private873   */874875  _checkForBrokenPassThrough() {876    if (877      this.parent &&878      this._passThroughOptions &&879      !this.parent._enablePositionalOptions880    ) {881      throw new Error(882        `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,883      );884    }885  }886887  /**888   * Whether to store option values as properties on command object,889   * or store separately (specify false). In both cases the option values can be accessed using .opts().890   *891   * @param {boolean} [storeAsProperties=true]892   * @return {Command} `this` command for chaining893   */894895  storeOptionsAsProperties(storeAsProperties = true) {896    if (this.options.length) {897      throw new Error('call .storeOptionsAsProperties() before adding options');898    }899    if (Object.keys(this._optionValues).length) {900      throw new Error(901        'call .storeOptionsAsProperties() before setting option values',902      );903    }904    this._storeOptionsAsProperties = !!storeAsProperties;905    return this;906  }907908  /**909   * Retrieve option value.910   *911   * @param {string} key912   * @return {object} value913   */914915  getOptionValue(key) {916    if (this._storeOptionsAsProperties) {917      return this[key];918    }919    return this._optionValues[key];920  }921922  /**923   * Store option value.924   *925   * @param {string} key926   * @param {object} value927   * @return {Command} `this` command for chaining928   */929930  setOptionValue(key, value) {931    return this.setOptionValueWithSource(key, value, undefined);932  }933934  /**935   * Store option value and where the value came from.936   *937   * @param {string} key938   * @param {object} value939   * @param {string} source - expected values are default/config/env/cli/implied940   * @return {Command} `this` command for chaining941   */942943  setOptionValueWithSource(key, value, source) {944    if (this._storeOptionsAsProperties) {945      this[key] = value;946    } else {947      this._optionValues[key] = value;948    }949    this._optionValueSources[key] = source;950    return this;951  }952953  /**954   * Get source of option value.955   * Expected values are default | config | env | cli | implied956   *957   * @param {string} key958   * @return {string}959   */960961  getOptionValueSource(key) {962    return this._optionValueSources[key];963  }964965  /**966   * Get source of option value. See also .optsWithGlobals().967   * Expected values are default | config | env | cli | implied968   *969   * @param {string} key970   * @return {string}971   */972973  getOptionValueSourceWithGlobals(key) {974    // global overwrites local, like optsWithGlobals975    let source;976    this._getCommandAndAncestors().forEach((cmd) => {977      if (cmd.getOptionValueSource(key) !== undefined) {978        source = cmd.getOptionValueSource(key);979      }980    });981    return source;982  }983984  /**985   * Get user arguments from implied or explicit arguments.986   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.987   *988   * @private989   */990991  _prepareUserArgs(argv, parseOptions) {992    if (argv !== undefined && !Array.isArray(argv)) {993      throw new Error('first parameter to parse must be array or undefined');994    }995    parseOptions = parseOptions || {};996997    // auto-detect argument conventions if nothing supplied998    if (argv === undefined && parseOptions.from === undefined) {999      if (process.versions?.electron) {1000        parseOptions.from = 'electron';1001      }1002      // check node specific options for scenarios where user CLI args follow executable without scriptname1003      const execArgv = process.execArgv ?? [];1004      if (1005        execArgv.includes('-e') ||1006        execArgv.includes('--eval') ||1007        execArgv.includes('-p') ||1008        execArgv.includes('--print')1009      ) {1010        parseOptions.from = 'eval'; // internal usage, not documented1011      }1012    }10131014    // default to using process.argv1015    if (argv === undefined) {1016      argv = process.argv;1017    }1018    this.rawArgs = argv.slice();10191020    // extract the user args and scriptPath1021    let userArgs;1022    switch (parseOptions.from) {1023      case undefined:1024      case 'node':1025        this._scriptPath = argv[1];1026        userArgs = argv.slice(2);1027        break;1028      case 'electron':1029        // @ts-ignore: because defaultApp is an unknown property1030        if (process.defaultApp) {1031          this._scriptPath = argv[1];1032          userArgs = argv.slice(2);1033        } else {1034          userArgs = argv.slice(1);1035        }1036        break;1037      case 'user':1038        userArgs = argv.slice(0);1039        break;1040      case 'eval':1041        userArgs = argv.slice(1);1042        break;1043      default:1044        throw new Error(1045          `unexpected parse option { from: '${parseOptions.from}' }`,1046        );1047    }10481049    // Find default name for program from arguments.1050    if (!this._name && this._scriptPath)1051      this.nameFromFilename(this._scriptPath);1052    this._name = this._name || 'program';10531054    return userArgs;1055  }10561057  /**1058   * Parse `argv`, setting options and invoking commands when defined.1059   *1060   * Use parseAsync instead of parse if any of your action handlers are async.1061   *1062   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1063   *1064   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1065   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1066   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1067   * - `'user'`: just user arguments1068   *1069   * @example1070   * program.parse(); // parse process.argv and auto-detect electron and special node flags1071   * program.parse(process.argv); // assume argv[0] is app and argv[1] is script1072   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1073   *1074   * @param {string[]} [argv] - optional, defaults to process.argv1075   * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1076   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1077   * @return {Command} `this` command for chaining1078   */10791080  parse(argv, parseOptions) {1081    this._prepareForParse();1082    const userArgs = this._prepareUserArgs(argv, parseOptions);1083    this._parseCommand([], userArgs);10841085    return this;1086  }10871088  /**1089   * Parse `argv`, setting options and invoking commands when defined.1090   *1091   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1092   *1093   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1094   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1095   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1096   * - `'user'`: just user arguments1097   *1098   * @example1099   * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1100   * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script1101   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1102   *1103   * @param {string[]} [argv]1104   * @param {object} [parseOptions]1105   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1106   * @return {Promise}1107   */11081109  async parseAsync(argv, parseOptions) {1110    this._prepareForParse();1111    const userArgs = this._prepareUserArgs(argv, parseOptions);1112    await this._parseCommand([], userArgs);11131114    return this;1115  }11161117  _prepareForParse() {1118    // Save the state the first time, then restore the state before each subsequent parse.1119    if (this._savedState === null) {1120      // Do the special default of lone negated option to true, now that we have all the options.1121      // Filter for negated options that have not been processed already.1122      this.options1123        .filter(1124          (option) =>1125            option.negate &&1126            option.defaultValue === undefined &&1127            this.getOptionValue(option.attributeName()) === undefined,1128        )1129        .forEach((option) => {1130          // check for lone negated option: --no-foo without a --foo option1131          const positiveLongFlag = option.long.replace(/^--no-/, '--');1132          if (!this._findOption(positiveLongFlag)) {1133            this.setOptionValueWithSource(1134              option.attributeName(),1135              true,1136              'default',1137            );1138          }1139        });11401141      this.saveStateBeforeParse();1142    } else {1143      this.restoreStateBeforeParse();1144    }1145  }11461147  /**1148   * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.1149   * Not usually called directly, but available for subclasses to save their custom state.1150   *1151   * This is called in a lazy way. Only commands used in parsing chain will have state saved.1152   */1153  saveStateBeforeParse() {1154    this._savedState = {1155      // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1156      _name: this._name,1157      // option values before parse have default values (including false for negated options)1158      // shallow clones1159      _optionValues: { ...this._optionValues },1160      _optionValueSources: { ...this._optionValueSources },1161    };1162  }11631164  /**1165   * Restore state before parse for calls after the first.1166   * Not usually called directly, but available for subclasses to save their custom state.1167   *1168   * This is called in a lazy way. Only commands used in parsing chain will have state restored.1169   */1170  restoreStateBeforeParse() {1171    if (this._storeOptionsAsProperties)1172      throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1173- either make a new Command for each call to parse, or stop storing options as properties`);11741175    // clear state from _prepareUserArgs1176    this._name = this._savedState._name;1177    this._scriptPath = null;1178    this.rawArgs = [];1179    // clear state from setOptionValueWithSource1180    this._optionValues = { ...this._savedState._optionValues };1181    this._optionValueSources = { ...this._savedState._optionValueSources };1182    // clear state from _parseCommand1183    this.args = [];1184    // clear state from _processArguments1185    this.processedArgs = [];1186  }11871188  /**1189   * Throw if expected executable is missing. Add lots of help for author.1190   *1191   * @param {string} executableFile1192   * @param {string} executableDir1193   * @param {string} subcommandName1194   */1195  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1196    if (fs.existsSync(executableFile)) return;11971198    const executableDirMessage = executableDir1199      ? `searched for local subcommand relative to directory '${executableDir}'`1200      : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1201    const executableMissing = `'${executableFile}' does not exist1202 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1203 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1204 - ${executableDirMessage}`;1205    throw new Error(executableMissing);1206  }12071208  /**1209   * Execute a sub-command executable.1210   *1211   * @private1212   */12131214  _executeSubCommand(subcommand, args) {1215    args = args.slice();1216    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1217    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12181219    function findFile(baseDir, baseName) {1220      // Look for specified file1221      const localBin = path.resolve(baseDir, baseName);1222      if (fs.existsSync(localBin)) return localBin;12231224      // Stop looking if candidate already has an expected extension.1225      if (sourceExt.includes(path.extname(baseName))) return undefined;12261227      // Try all the extensions.1228      const foundExt = sourceExt.find((ext) =>1229        fs.existsSync(`${localBin}${ext}`),1230      );1231      if (foundExt) return `${localBin}${foundExt}`;12321233      return undefined;1234    }12351236    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1237    this._checkForMissingMandatoryOptions();1238    this._checkForConflictingOptions();12391240    // executableFile and executableDir might be full path, or just a name1241    let executableFile =1242      subcommand._executableFile || `${this._name}-${subcommand._name}`;1243    let executableDir = this._executableDir || '';1244    if (this._scriptPath) {1245      let resolvedScriptPath; // resolve possible symlink for installed npm binary1246      try {1247        resolvedScriptPath = fs.realpathSync(this._scriptPath);1248      } catch {1249        resolvedScriptPath = this._scriptPath;1250      }1251      executableDir = path.resolve(1252        path.dirname(resolvedScriptPath),1253        executableDir,1254      );1255    }12561257    // Look for a local file in preference to a command in PATH.1258    if (executableDir) {1259      let localFile = findFile(executableDir, executableFile);12601261      // Legacy search using prefix of script name instead of command name1262      if (!localFile && !subcommand._executableFile && this._scriptPath) {1263        const legacyName = path.basename(1264          this._scriptPath,1265          path.extname(this._scriptPath),1266        );1267        if (legacyName !== this._name) {1268          localFile = findFile(1269            executableDir,1270            `${legacyName}-${subcommand._name}`,1271          );1272        }1273      }1274      executableFile = localFile || executableFile;1275    }12761277    launchWithNode = sourceExt.includes(path.extname(executableFile));12781279    let proc;1280    if (process.platform !== 'win32') {1281      if (launchWithNode) {1282        args.unshift(executableFile);1283        // add executable arguments to spawn1284        args = incrementNodeInspectorPort(process.execArgv).concat(args);12851286        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1287      } else {1288        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1289      }1290    } else {1291      this._checkForMissingExecutable(1292        executableFile,1293        executableDir,1294        subcommand._name,1295      );1296      args.unshift(executableFile);1297      // add executable arguments to spawn1298      args = incrementNodeInspectorPort(process.execArgv).concat(args);1299      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1300    }13011302    if (!proc.killed) {1303      // testing mainly to avoid leak warnings during unit tests with mocked spawn1304      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1305      signals.forEach((signal) => {1306        process.on(signal, () => {1307          if (proc.killed === false && proc.exitCode === null) {1308            // @ts-ignore because signals not typed to known strings1309            proc.kill(signal);1310          }1311        });1312      });1313    }13141315    // By default terminate process when spawned process terminates.1316    const exitCallback = this._exitCallback;1317    proc.on('close', (code) => {1318      code = code ?? 1; // code is null if spawned process terminated due to a signal1319      if (!exitCallback) {1320        process.exit(code);1321      } else {1322        exitCallback(1323          new CommanderError(1324            code,1325            'commander.executeSubCommandAsync',1326            '(close)',1327          ),1328        );1329      }1330    });1331    proc.on('error', (err) => {1332      // @ts-ignore: because err.code is an unknown property1333      if (err.code === 'ENOENT') {1334        this._checkForMissingExecutable(1335          executableFile,1336          executableDir,1337          subcommand._name,1338        );1339        // @ts-ignore: because err.code is an unknown property1340      } else if (err.code === 'EACCES') {1341        throw new Error(`'${executableFile}' not executable`);1342      }1343      if (!exitCallback) {1344        process.exit(1);1345      } else {1346        const wrappedError = new CommanderError(1347          1,1348          'commander.executeSubCommandAsync',1349          '(error)',1350        );1351        wrappedError.nestedError = err;1352        exitCallback(wrappedError);1353      }1354    });13551356    // Store the reference to the child process1357    this.runningCommand = proc;1358  }13591360  /**1361   * @private1362   */13631364  _dispatchSubcommand(commandName, operands, unknown) {1365    const subCommand = this._findCommand(commandName);1366    if (!subCommand) this.help({ error: true });13671368    subCommand._prepareForParse();1369    let promiseChain;1370    promiseChain = this._chainOrCallSubCommandHook(1371      promiseChain,1372      subCommand,1373      'preSubcommand',1374    );1375    promiseChain = this._chainOrCall(promiseChain, () => {1376      if (subCommand._executableHandler) {1377        this._executeSubCommand(subCommand, operands.concat(unknown));1378      } else {1379        return subCommand._parseCommand(operands, unknown);1380      }1381    });1382    return promiseChain;1383  }13841385  /**1386   * Invoke help directly if possible, or dispatch if necessary.1387   * e.g. help foo1388   *1389   * @private1390   */13911392  _dispatchHelpCommand(subcommandName) {1393    if (!subcommandName) {1394      this.help();1395    }1396    const subCommand = this._findCommand(subcommandName);1397    if (subCommand && !subCommand._executableHandler) {1398      subCommand.help();1399    }14001401    // Fallback to parsing the help flag to invoke the help.1402    return this._dispatchSubcommand(1403      subcommandName,1404      [],1405      [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1406    );1407  }14081409  /**1410   * Check this.args against expected this.registeredArguments.1411   *1412   * @private1413   */14141415  _checkNumberOfArguments() {1416    // too few1417    this.registeredArguments.forEach((arg, i) => {1418      if (arg.required && this.args[i] == null) {1419        this.missingArgument(arg.name());1420      }1421    });1422    // too many1423    if (1424      this.registeredArguments.length > 0 &&1425      this.registeredArguments[this.registeredArguments.length - 1].variadic1426    ) {1427      return;1428    }1429    if (this.args.length > this.registeredArguments.length) {1430      this._excessArguments(this.args);1431    }1432  }14331434  /**1435   * Process this.args using this.registeredArguments and save as this.processedArgs!1436   *1437   * @private1438   */14391440  _processArguments() {1441    const myParseArg = (argument, value, previous) => {1442      // Extra processing for nice error message on parsing failure.1443      let parsedValue = value;1444      if (value !== null && argument.parseArg) {1445        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1446        parsedValue = this._callParseArg(1447          argument,1448          value,1449          previous,1450          invalidValueMessage,1451        );1452      }1453      return parsedValue;1454    };14551456    this._checkNumberOfArguments();14571458    const processedArgs = [];1459    this.registeredArguments.forEach((declaredArg, index) => {1460      let value = declaredArg.defaultValue;1461      if (declaredArg.variadic) {1462        // Collect together remaining arguments for passing together as an array.1463        if (index < this.args.length) {1464          value = this.args.slice(index);1465          if (declaredArg.parseArg) {1466            value = value.reduce((processed, v) => {1467              return myParseArg(declaredArg, v, processed);1468            }, declaredArg.defaultValue);1469          }1470        } else if (value === undefined) {1471          value = [];1472        }1473      } else if (index < this.args.length) {1474        value = this.args[index];1475        if (declaredArg.parseArg) {1476          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1477        }1478      }1479      processedArgs[index] = value;1480    });1481    this.processedArgs = processedArgs;1482  }14831484  /**1485   * Once we have a promise we chain, but call synchronously until then.1486   *1487   * @param {(Promise|undefined)} promise1488   * @param {Function} fn1489   * @return {(Promise|undefined)}1490   * @private1491   */14921493  _chainOrCall(promise, fn) {1494    // thenable1495    if (promise?.then && typeof promise.then === 'function') {1496      // already have a promise, chain callback1497      return promise.then(() => fn());1498    }1499    // callback might return a promise1500    return fn();1501  }15021503  /**1504   *1505   * @param {(Promise|undefined)} promise1506   * @param {string} event1507   * @return {(Promise|undefined)}1508   * @private1509   */15101511  _chainOrCallHooks(promise, event) {1512    let result = promise;1513    const hooks = [];1514    this._getCommandAndAncestors()1515      .reverse()1516      .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1517      .forEach((hookedCommand) => {1518        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1519          hooks.push({ hookedCommand, callback });1520        });1521      });1522    if (event === 'postAction') {1523      hooks.reverse();1524    }15251526    hooks.forEach((hookDetail) => {1527      result = this._chainOrCall(result, () => {1528        return hookDetail.callback(hookDetail.hookedCommand, this);1529      });1530    });1531    return result;1532  }15331534  /**1535   *1536   * @param {(Promise|undefined)} promise1537   * @param {Command} subCommand1538   * @param {string} event1539   * @return {(Promise|undefined)}1540   * @private1541   */15421543  _chainOrCallSubCommandHook(promise, subCommand, event) {1544    let result = promise;1545    if (this._lifeCycleHooks[event] !== undefined) {1546      this._lifeCycleHooks[event].forEach((hook) => {1547        result = this._chainOrCall(result, () => {1548          return hook(this, subCommand);1549        });1550      });1551    }1552    return result;1553  }15541555  /**1556   * Process arguments in context of this command.1557   * Returns action result, in case it is a promise.1558   *1559   * @private1560   */15611562  _parseCommand(operands, unknown) {1563    const parsed = this.parseOptions(unknown);1564    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1565    this._parseOptionsImplied();1566    operands = operands.concat(parsed.operands);1567    unknown = parsed.unknown;1568    this.args = operands.concat(unknown);15691570    if (operands && this._findCommand(operands[0])) {1571      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1572    }1573    if (1574      this._getHelpCommand() &&1575      operands[0] === this._getHelpCommand().name()1576    ) {1577      return this._dispatchHelpCommand(operands[1]);1578    }1579    if (this._defaultCommandName) {1580      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1581      return this._dispatchSubcommand(1582        this._defaultCommandName,1583        operands,1584        unknown,1585      );1586    }1587    if (1588      this.commands.length &&1589      this.args.length === 0 &&1590      !this._actionHandler &&1591      !this._defaultCommandName1592    ) {1593      // probably missing subcommand and no handler, user needs help (and exit)1594      this.help({ error: true });1595    }15961597    this._outputHelpIfRequested(parsed.unknown);1598    this._checkForMissingMandatoryOptions();1599    this._checkForConflictingOptions();16001601    // We do not always call this check to avoid masking a "better" error, like unknown command.1602    const checkForUnknownOptions = () => {1603      if (parsed.unknown.length > 0) {1604        this.unknownOption(parsed.unknown[0]);1605      }1606    };16071608    const commandEvent = `command:${this.name()}`;1609    if (this._actionHandler) {1610      checkForUnknownOptions();1611      this._processArguments();16121613      let promiseChain;1614      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1615      promiseChain = this._chainOrCall(promiseChain, () =>1616        this._actionHandler(this.processedArgs),1617      );1618      if (this.parent) {1619        promiseChain = this._chainOrCall(promiseChain, () => {1620          this.parent.emit(commandEvent, operands, unknown); // legacy1621        });1622      }1623      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1624      return promiseChain;1625    }1626    if (this.parent?.listenerCount(commandEvent)) {1627      checkForUnknownOptions();1628      this._processArguments();1629      this.parent.emit(commandEvent, operands, unknown); // legacy1630    } else if (operands.length) {1631      if (this._findCommand('*')) {1632        // legacy default command1633        return this._dispatchSubcommand('*', operands, unknown);1634      }1635      if (this.listenerCount('command:*')) {1636        // skip option check, emit event for possible misspelling suggestion1637        this.emit('command:*', operands, unknown);1638      } else if (this.commands.length) {1639        this.unknownCommand();1640      } else {1641        checkForUnknownOptions();1642        this._processArguments();1643      }1644    } else if (this.commands.length) {1645      checkForUnknownOptions();1646      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1647      this.help({ error: true });1648    } else {1649      checkForUnknownOptions();1650      this._processArguments();1651      // fall through for caller to handle after calling .parse()1652    }1653  }16541655  /**1656   * Find matching command.1657   *1658   * @private1659   * @return {Command | undefined}1660   */1661  _findCommand(name) {1662    if (!name) return undefined;1663    return this.commands.find(1664      (cmd) => cmd._name === name || cmd._aliases.includes(name),1665    );1666  }16671668  /**1669   * Return an option matching `arg` if any.1670   *1671   * @param {string} arg1672   * @return {Option}1673   * @package1674   */16751676  _findOption(arg) {1677    return this.options.find((option) => option.is(arg));1678  }16791680  /**1681   * Display an error message if a mandatory option does not have a value.1682   * Called after checking for help flags in leaf subcommand.1683   *1684   * @private1685   */16861687  _checkForMissingMandatoryOptions() {1688    // Walk up hierarchy so can call in subcommand after checking for displaying help.1689    this._getCommandAndAncestors().forEach((cmd) => {1690      cmd.options.forEach((anOption) => {1691        if (1692          anOption.mandatory &&1693          cmd.getOptionValue(anOption.attributeName()) === undefined1694        ) {1695          cmd.missingMandatoryOptionValue(anOption);1696        }1697      });1698    });1699  }17001701  /**1702   * Display an error message if conflicting options are used together in this.1703   *1704   * @private1705   */1706  _checkForConflictingLocalOptions() {1707    const definedNonDefaultOptions = this.options.filter((option) => {1708      const optionKey = option.attributeName();1709      if (this.getOptionValue(optionKey) === undefined) {1710        return false;1711      }1712      return this.getOptionValueSource(optionKey) !== 'default';1713    });17141715    const optionsWithConflicting = definedNonDefaultOptions.filter(1716      (option) => option.conflictsWith.length > 0,1717    );17181719    optionsWithConflicting.forEach((option) => {1720      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1721        option.conflictsWith.includes(defined.attributeName()),1722      );1723      if (conflictingAndDefined) {1724        this._conflictingOption(option, conflictingAndDefined);1725      }1726    });1727  }17281729  /**1730   * Display an error message if conflicting options are used together.1731   * Called after checking for help flags in leaf subcommand.1732   *1733   * @private1734   */1735  _checkForConflictingOptions() {1736    // Walk up hierarchy so can call in subcommand after checking for displaying help.1737    this._getCommandAndAncestors().forEach((cmd) => {1738      cmd._checkForConflictingLocalOptions();1739    });1740  }17411742  /**1743   * Parse options from `argv` removing known options,1744   * and return argv split into operands and unknown arguments.1745   *1746   * Side effects: modifies command by storing options. Does not reset state if called again.1747   *1748   * Examples:1749   *1750   *     argv => operands, unknown1751   *     --known kkk op => [op], []1752   *     op --known kkk => [op], []1753   *     sub --unknown uuu op => [sub], [--unknown uuu op]1754   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1755   *1756   * @param {string[]} args1757   * @return {{operands: string[], unknown: string[]}}1758   */17591760  parseOptions(args) {1761    const operands = []; // operands, not options or values1762    const unknown = []; // first unknown option and remaining unknown args1763    let dest = operands;17641765    function maybeOption(arg) {1766      return arg.length > 1 && arg[0] === '-';1767    }17681769    const negativeNumberArg = (arg) => {1770      // return false if not a negative number1771      if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;1772      // negative number is ok unless digit used as an option in command hierarchy1773      return !this._getCommandAndAncestors().some((cmd) =>1774        cmd.options1775          .map((opt) => opt.short)1776          .some((short) => /^-\d$/.test(short)),1777      );1778    };17791780    // parse options1781    let activeVariadicOption = null;1782    let activeGroup = null; // working through group of short options, like -abc1783    let i = 0;1784    while (i < args.length || activeGroup) {1785      const arg = activeGroup ?? args[i++];1786      activeGroup = null;17871788      // literal1789      if (arg === '--') {1790        if (dest === unknown) dest.push(arg);1791        dest.push(...args.slice(i));1792        break;1793      }17941795      if (1796        activeVariadicOption &&1797        (!maybeOption(arg) || negativeNumberArg(arg))1798      ) {1799        this.emit(`option:${activeVariadicOption.name()}`, arg);1800        continue;1801      }1802      activeVariadicOption = null;18031804      if (maybeOption(arg)) {1805        const option = this._findOption(arg);1806        // recognised option, call listener to assign value with possible custom processing1807        if (option) {1808          if (option.required) {1809            const value = args[i++];1810            if (value === undefined) this.optionMissingArgument(option);1811            this.emit(`option:${option.name()}`, value);1812          } else if (option.optional) {1813            let value = null;1814            // historical behaviour is optional value is following arg unless an option1815            if (1816              i < args.length &&1817              (!maybeOption(args[i]) || negativeNumberArg(args[i]))1818            ) {1819              value = args[i++];1820            }1821            this.emit(`option:${option.name()}`, value);1822          } else {1823            // boolean flag1824            this.emit(`option:${option.name()}`);1825          }1826          activeVariadicOption = option.variadic ? option : null;1827          continue;1828        }1829      }18301831      // Look for combo options following single dash, eat first one if known.1832      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1833        const option = this._findOption(`-${arg[1]}`);1834        if (option) {1835          if (1836            option.required ||1837            (option.optional && this._combineFlagAndOptionalValue)1838          ) {1839            // option with value following in same argument1840            this.emit(`option:${option.name()}`, arg.slice(2));1841          } else {1842            // boolean option1843            this.emit(`option:${option.name()}`);1844            // remove the processed option and keep processing group1845            activeGroup = `-${arg.slice(2)}`;1846          }1847          continue;1848        }1849      }18501851      // Look for known long flag with value, like --foo=bar1852      if (/^--[^=]+=/.test(arg)) {1853        const index = arg.indexOf('=');1854        const option = this._findOption(arg.slice(0, index));1855        if (option && (option.required || option.optional)) {1856          this.emit(`option:${option.name()}`, arg.slice(index + 1));1857          continue;1858        }1859      }18601861      // Not a recognised option by this command.1862      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18631864      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1865      // A negative number in a leaf command is not an unknown option.1866      if (1867        dest === operands &&1868        maybeOption(arg) &&1869        !(this.commands.length === 0 && negativeNumberArg(arg))1870      ) {1871        dest = unknown;1872      }18731874      // If using positionalOptions, stop processing our options at subcommand.1875      if (1876        (this._enablePositionalOptions || this._passThroughOptions) &&1877        operands.length === 0 &&1878        unknown.length === 01879      ) {1880        if (this._findCommand(arg)) {1881          operands.push(arg);1882          unknown.push(...args.slice(i));1883          break;1884        } else if (1885          this._getHelpCommand() &&1886          arg === this._getHelpCommand().name()1887        ) {1888          operands.push(arg, ...args.slice(i));1889          break;1890        } else if (this._defaultCommandName) {1891          unknown.push(arg, ...args.slice(i));1892          break;1893        }1894      }18951896      // If using passThroughOptions, stop processing options at first command-argument.1897      if (this._passThroughOptions) {1898        dest.push(arg, ...args.slice(i));1899        break;1900      }19011902      // add arg1903      dest.push(arg);1904    }19051906    return { operands, unknown };1907  }19081909  /**1910   * Return an object containing local option values as key-value pairs.1911   *1912   * @return {object}1913   */1914  opts() {1915    if (this._storeOptionsAsProperties) {1916      // Preserve original behaviour so backwards compatible when still using properties1917      const result = {};1918      const len = this.options.length;19191920      for (let i = 0; i < len; i++) {1921        const key = this.options[i].attributeName();1922        result[key] =1923          key === this._versionOptionName ? this._version : this[key];1924      }1925      return result;1926    }19271928    return this._optionValues;1929  }19301931  /**1932   * Return an object containing merged local and global option values as key-value pairs.1933   *1934   * @return {object}1935   */1936  optsWithGlobals() {1937    // globals overwrite locals1938    return this._getCommandAndAncestors().reduce(1939      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1940      {},1941    );1942  }19431944  /**1945   * Display error message and exit (or call exitOverride).1946   *1947   * @param {string} message1948   * @param {object} [errorOptions]1949   * @param {string} [errorOptions.code] - an id string representing the error1950   * @param {number} [errorOptions.exitCode] - used with process.exit1951   */1952  error(message, errorOptions) {1953    // output handling1954    this._outputConfiguration.outputError(1955      `${message}\n`,1956      this._outputConfiguration.writeErr,1957    );1958    if (typeof this._showHelpAfterError === 'string') {1959      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1960    } else if (this._showHelpAfterError) {1961      this._outputConfiguration.writeErr('\n');1962      this.outputHelp({ error: true });1963    }19641965    // exit handling1966    const config = errorOptions || {};1967    const exitCode = config.exitCode || 1;1968    const code = config.code || 'commander.error';1969    this._exit(exitCode, code, message);1970  }19711972  /**1973   * Apply any option related environment variables, if option does1974   * not have a value from cli or client code.1975   *1976   * @private1977   */1978  _parseOptionsEnv() {1979    this.options.forEach((option) => {1980      if (option.envVar && option.envVar in process.env) {1981        const optionKey = option.attributeName();1982        // Priority check. Do not overwrite cli or options from unknown source (client-code).1983        if (1984          this.getOptionValue(optionKey) === undefined ||1985          ['default', 'config', 'env'].includes(1986            this.getOptionValueSource(optionKey),1987          )1988        ) {1989          if (option.required || option.optional) {1990            // option can take a value1991            // keep very simple, optional always takes value1992            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1993          } else {1994            // boolean1995            // keep very simple, only care that envVar defined and not the value1996            this.emit(`optionEnv:${option.name()}`);1997          }1998        }1999      }2000    });

The first 2,000 of 2,791 lines.