Skip to content
Myr

command.js

This file

Path

lib/command.js

2,778 lines · 85.2 KiB · JavaScript

Last changed by

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

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 = Object.assign(249      {},250      this._outputConfiguration,251      configuration,252    );253    return this;254  }255256  /**257   * Display the help or a custom message after an error occurs.258   *259   * @param {(boolean|string)} [displayHelp]260   * @return {Command} `this` command for chaining261   */262  showHelpAfterError(displayHelp = true) {263    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;264    this._showHelpAfterError = displayHelp;265    return this;266  }267268  /**269   * Display suggestion of similar commands for unknown commands, or options for unknown options.270   *271   * @param {boolean} [displaySuggestion]272   * @return {Command} `this` command for chaining273   */274  showSuggestionAfterError(displaySuggestion = true) {275    this._showSuggestionAfterError = !!displaySuggestion;276    return this;277  }278279  /**280   * Add a prepared subcommand.281   *282   * See .command() for creating an attached subcommand which inherits settings from its parent.283   *284   * @param {Command} cmd - new subcommand285   * @param {object} [opts] - configuration options286   * @return {Command} `this` command for chaining287   */288289  addCommand(cmd, opts) {290    if (!cmd._name) {291      throw new Error(`Command passed to .addCommand() must have a name292- specify the name in Command constructor or using .name()`);293    }294295    opts = opts || {};296    if (opts.isDefault) this._defaultCommandName = cmd._name;297    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation298299    this._registerCommand(cmd);300    cmd.parent = this;301    cmd._checkForBrokenPassThrough();302303    return this;304  }305306  /**307   * Factory routine to create a new unattached argument.308   *309   * See .argument() for creating an attached argument, which uses this routine to310   * create the argument. You can override createArgument to return a custom argument.311   *312   * @param {string} name313   * @param {string} [description]314   * @return {Argument} new argument315   */316317  createArgument(name, description) {318    return new Argument(name, description);319  }320321  /**322   * Define argument syntax for command.323   *324   * The default is that the argument is required, and you can explicitly325   * indicate this with <> around the name. Put [] around the name for an optional argument.326   *327   * @example328   * program.argument('<input-file>');329   * program.argument('[output-file]');330   *331   * @param {string} name332   * @param {string} [description]333   * @param {(Function|*)} [parseArg] - custom argument processing function or default value334   * @param {*} [defaultValue]335   * @return {Command} `this` command for chaining336   */337  argument(name, description, parseArg, defaultValue) {338    const argument = this.createArgument(name, description);339    if (typeof parseArg === 'function') {340      argument.default(defaultValue).argParser(parseArg);341    } else {342      argument.default(parseArg);343    }344    this.addArgument(argument);345    return this;346  }347348  /**349   * Define argument syntax for command, adding multiple at once (without descriptions).350   *351   * See also .argument().352   *353   * @example354   * program.arguments('<cmd> [env]');355   *356   * @param {string} names357   * @return {Command} `this` command for chaining358   */359360  arguments(names) {361    names362      .trim()363      .split(/ +/)364      .forEach((detail) => {365        this.argument(detail);366      });367    return this;368  }369370  /**371   * Define argument syntax for command, adding a prepared argument.372   *373   * @param {Argument} argument374   * @return {Command} `this` command for chaining375   */376  addArgument(argument) {377    const previousArgument = this.registeredArguments.slice(-1)[0];378    if (previousArgument && previousArgument.variadic) {379      throw new Error(380        `only the last argument can be variadic '${previousArgument.name()}'`,381      );382    }383    if (384      argument.required &&385      argument.defaultValue !== undefined &&386      argument.parseArg === undefined387    ) {388      throw new Error(389        `a default value for a required argument is never used: '${argument.name()}'`,390      );391    }392    this.registeredArguments.push(argument);393    return this;394  }395396  /**397   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.398   *399   * @example400   *    program.helpCommand('help [cmd]');401   *    program.helpCommand('help [cmd]', 'show help');402   *    program.helpCommand(false); // suppress default help command403   *    program.helpCommand(true); // add help command even if no subcommands404   *405   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added406   * @param {string} [description] - custom description407   * @return {Command} `this` command for chaining408   */409410  helpCommand(enableOrNameAndArgs, description) {411    if (typeof enableOrNameAndArgs === 'boolean') {412      this._addImplicitHelpCommand = enableOrNameAndArgs;413      if (enableOrNameAndArgs && this._defaultCommandGroup) {414        // make the command to store the group415        this._initCommandGroup(this._getHelpCommand());416      }417      return this;418    }419420    const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';421    const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);422    const helpDescription = description ?? 'display help for command';423424    const helpCommand = this.createCommand(helpName);425    helpCommand.helpOption(false);426    if (helpArgs) helpCommand.arguments(helpArgs);427    if (helpDescription) helpCommand.description(helpDescription);428429    this._addImplicitHelpCommand = true;430    this._helpCommand = helpCommand;431    // init group unless lazy create432    if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);433434    return this;435  }436437  /**438   * Add prepared custom help command.439   *440   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`441   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only442   * @return {Command} `this` command for chaining443   */444  addHelpCommand(helpCommand, deprecatedDescription) {445    // If not passed an object, call through to helpCommand for backwards compatibility,446    // as addHelpCommand was originally used like helpCommand is now.447    if (typeof helpCommand !== 'object') {448      this.helpCommand(helpCommand, deprecatedDescription);449      return this;450    }451452    this._addImplicitHelpCommand = true;453    this._helpCommand = helpCommand;454    this._initCommandGroup(helpCommand);455    return this;456  }457458  /**459   * Lazy create help command.460   *461   * @return {(Command|null)}462   * @package463   */464  _getHelpCommand() {465    const hasImplicitHelpCommand =466      this._addImplicitHelpCommand ??467      (this.commands.length &&468        !this._actionHandler &&469        !this._findCommand('help'));470471    if (hasImplicitHelpCommand) {472      if (this._helpCommand === undefined) {473        this.helpCommand(undefined, undefined); // use default name and description474      }475      return this._helpCommand;476    }477    return null;478  }479480  /**481   * Add hook for life cycle event.482   *483   * @param {string} event484   * @param {Function} listener485   * @return {Command} `this` command for chaining486   */487488  hook(event, listener) {489    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];490    if (!allowedValues.includes(event)) {491      throw new Error(`Unexpected value for event passed to hook : '${event}'.492Expecting one of '${allowedValues.join("', '")}'`);493    }494    if (this._lifeCycleHooks[event]) {495      this._lifeCycleHooks[event].push(listener);496    } else {497      this._lifeCycleHooks[event] = [listener];498    }499    return this;500  }501502  /**503   * Register callback to use as replacement for calling process.exit.504   *505   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing506   * @return {Command} `this` command for chaining507   */508509  exitOverride(fn) {510    if (fn) {511      this._exitCallback = fn;512    } else {513      this._exitCallback = (err) => {514        if (err.code !== 'commander.executeSubCommandAsync') {515          throw err;516        } else {517          // Async callback from spawn events, not useful to throw.518        }519      };520    }521    return this;522  }523524  /**525   * Call process.exit, and _exitCallback if defined.526   *527   * @param {number} exitCode exit code for using with process.exit528   * @param {string} code an id string representing the error529   * @param {string} message human-readable description of the error530   * @return never531   * @private532   */533534  _exit(exitCode, code, message) {535    if (this._exitCallback) {536      this._exitCallback(new CommanderError(exitCode, code, message));537      // Expecting this line is not reached.538    }539    process.exit(exitCode);540  }541542  /**543   * Register callback `fn` for the command.544   *545   * @example546   * program547   *   .command('serve')548   *   .description('start service')549   *   .action(function() {550   *      // do work here551   *   });552   *553   * @param {Function} fn554   * @return {Command} `this` command for chaining555   */556557  action(fn) {558    const listener = (args) => {559      // The .action callback takes an extra parameter which is the command or options.560      const expectedArgsCount = this.registeredArguments.length;561      const actionArgs = args.slice(0, expectedArgsCount);562      if (this._storeOptionsAsProperties) {563        actionArgs[expectedArgsCount] = this; // backwards compatible "options"564      } else {565        actionArgs[expectedArgsCount] = this.opts();566      }567      actionArgs.push(this);568569      return fn.apply(this, actionArgs);570    };571    this._actionHandler = listener;572    return this;573  }574575  /**576   * Factory routine to create a new unattached option.577   *578   * See .option() for creating an attached option, which uses this routine to579   * create the option. You can override createOption to return a custom option.580   *581   * @param {string} flags582   * @param {string} [description]583   * @return {Option} new option584   */585586  createOption(flags, description) {587    return new Option(flags, description);588  }589590  /**591   * Wrap parseArgs to catch 'commander.invalidArgument'.592   *593   * @param {(Option | Argument)} target594   * @param {string} value595   * @param {*} previous596   * @param {string} invalidArgumentMessage597   * @private598   */599600  _callParseArg(target, value, previous, invalidArgumentMessage) {601    try {602      return target.parseArg(value, previous);603    } catch (err) {604      if (err.code === 'commander.invalidArgument') {605        const message = `${invalidArgumentMessage} ${err.message}`;606        this.error(message, { exitCode: err.exitCode, code: err.code });607      }608      throw err;609    }610  }611612  /**613   * Check for option flag conflicts.614   * Register option if no conflicts found, or throw on conflict.615   *616   * @param {Option} option617   * @private618   */619620  _registerOption(option) {621    const matchingOption =622      (option.short && this._findOption(option.short)) ||623      (option.long && this._findOption(option.long));624    if (matchingOption) {625      const matchingFlag =626        option.long && this._findOption(option.long)627          ? option.long628          : option.short;629      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'630-  already used by option '${matchingOption.flags}'`);631    }632633    this._initOptionGroup(option);634    this.options.push(option);635  }636637  /**638   * Check for command name and alias conflicts with existing commands.639   * Register command if no conflicts found, or throw on conflict.640   *641   * @param {Command} command642   * @private643   */644645  _registerCommand(command) {646    const knownBy = (cmd) => {647      return [cmd.name()].concat(cmd.aliases());648    };649650    const alreadyUsed = knownBy(command).find((name) =>651      this._findCommand(name),652    );653    if (alreadyUsed) {654      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');655      const newCmd = knownBy(command).join('|');656      throw new Error(657        `cannot add command '${newCmd}' as already have command '${existingCmd}'`,658      );659    }660661    this._initCommandGroup(command);662    this.commands.push(command);663  }664665  /**666   * Add an option.667   *668   * @param {Option} option669   * @return {Command} `this` command for chaining670   */671  addOption(option) {672    this._registerOption(option);673674    const oname = option.name();675    const name = option.attributeName();676677    // store default value678    if (option.negate) {679      // --no-foo is special and defaults foo to true, unless a --foo option is already defined680      const positiveLongFlag = option.long.replace(/^--no-/, '--');681      if (!this._findOption(positiveLongFlag)) {682        this.setOptionValueWithSource(683          name,684          option.defaultValue === undefined ? true : option.defaultValue,685          'default',686        );687      }688    } else if (option.defaultValue !== undefined) {689      this.setOptionValueWithSource(name, option.defaultValue, 'default');690    }691692    // handler for cli and env supplied values693    const handleOptionValue = (val, invalidValueMessage, valueSource) => {694      // val is null for optional option used without an optional-argument.695      // val is undefined for boolean and negated option.696      if (val == null && option.presetArg !== undefined) {697        val = option.presetArg;698      }699700      // custom processing701      const oldValue = this.getOptionValue(name);702      if (val !== null && option.parseArg) {703        val = this._callParseArg(option, val, oldValue, invalidValueMessage);704      } else if (val !== null && option.variadic) {705        val = option._concatValue(val, oldValue);706      }707708      // Fill-in appropriate missing values. Long winded but easy to follow.709      if (val == null) {710        if (option.negate) {711          val = false;712        } else if (option.isBoolean() || option.optional) {713          val = true;714        } else {715          val = ''; // not normal, parseArg might have failed or be a mock function for testing716        }717      }718      this.setOptionValueWithSource(name, val, valueSource);719    };720721    this.on('option:' + oname, (val) => {722      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;723      handleOptionValue(val, invalidValueMessage, 'cli');724    });725726    if (option.envVar) {727      this.on('optionEnv:' + oname, (val) => {728        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;729        handleOptionValue(val, invalidValueMessage, 'env');730      });731    }732733    return this;734  }735736  /**737   * Internal implementation shared by .option() and .requiredOption()738   *739   * @return {Command} `this` command for chaining740   * @private741   */742  _optionEx(config, flags, description, fn, defaultValue) {743    if (typeof flags === 'object' && flags instanceof Option) {744      throw new Error(745        'To add an Option object use addOption() instead of option() or requiredOption()',746      );747    }748    const option = this.createOption(flags, description);749    option.makeOptionMandatory(!!config.mandatory);750    if (typeof fn === 'function') {751      option.default(defaultValue).argParser(fn);752    } else if (fn instanceof RegExp) {753      // deprecated754      const regex = fn;755      fn = (val, def) => {756        const m = regex.exec(val);757        return m ? m[0] : def;758      };759      option.default(defaultValue).argParser(fn);760    } else {761      option.default(fn);762    }763764    return this.addOption(option);765  }766767  /**768   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.769   *770   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required771   * option-argument is indicated by `<>` and an optional option-argument by `[]`.772   *773   * See the README for more details, and see also addOption() and requiredOption().774   *775   * @example776   * program777   *     .option('-p, --pepper', 'add pepper')778   *     .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument779   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default780   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function781   *782   * @param {string} flags783   * @param {string} [description]784   * @param {(Function|*)} [parseArg] - custom option processing function or default value785   * @param {*} [defaultValue]786   * @return {Command} `this` command for chaining787   */788789  option(flags, description, parseArg, defaultValue) {790    return this._optionEx({}, flags, description, parseArg, defaultValue);791  }792793  /**794   * Add a required option which must have a value after parsing. This usually means795   * the option must be specified on the command line. (Otherwise the same as .option().)796   *797   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.798   *799   * @param {string} flags800   * @param {string} [description]801   * @param {(Function|*)} [parseArg] - custom option processing function or default value802   * @param {*} [defaultValue]803   * @return {Command} `this` command for chaining804   */805806  requiredOption(flags, description, parseArg, defaultValue) {807    return this._optionEx(808      { mandatory: true },809      flags,810      description,811      parseArg,812      defaultValue,813    );814  }815816  /**817   * Alter parsing of short flags with optional values.818   *819   * @example820   * // for `.option('-f,--flag [value]'):821   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour822   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`823   *824   * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.825   * @return {Command} `this` command for chaining826   */827  combineFlagAndOptionalValue(combine = true) {828    this._combineFlagAndOptionalValue = !!combine;829    return this;830  }831832  /**833   * Allow unknown options on the command line.834   *835   * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.836   * @return {Command} `this` command for chaining837   */838  allowUnknownOption(allowUnknown = true) {839    this._allowUnknownOption = !!allowUnknown;840    return this;841  }842843  /**844   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.845   *846   * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.847   * @return {Command} `this` command for chaining848   */849  allowExcessArguments(allowExcess = true) {850    this._allowExcessArguments = !!allowExcess;851    return this;852  }853854  /**855   * Enable positional options. Positional means global options are specified before subcommands which lets856   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.857   * The default behaviour is non-positional and global options may appear anywhere on the command line.858   *859   * @param {boolean} [positional]860   * @return {Command} `this` command for chaining861   */862  enablePositionalOptions(positional = true) {863    this._enablePositionalOptions = !!positional;864    return this;865  }866867  /**868   * Pass through options that come after command-arguments rather than treat them as command-options,869   * so actual command-options come before command-arguments. Turning this on for a subcommand requires870   * positional options to have been enabled on the program (parent commands).871   * The default behaviour is non-positional and options may appear before or after command-arguments.872   *873   * @param {boolean} [passThrough] for unknown options.874   * @return {Command} `this` command for chaining875   */876  passThroughOptions(passThrough = true) {877    this._passThroughOptions = !!passThrough;878    this._checkForBrokenPassThrough();879    return this;880  }881882  /**883   * @private884   */885886  _checkForBrokenPassThrough() {887    if (888      this.parent &&889      this._passThroughOptions &&890      !this.parent._enablePositionalOptions891    ) {892      throw new Error(893        `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,894      );895    }896  }897898  /**899   * Whether to store option values as properties on command object,900   * or store separately (specify false). In both cases the option values can be accessed using .opts().901   *902   * @param {boolean} [storeAsProperties=true]903   * @return {Command} `this` command for chaining904   */905906  storeOptionsAsProperties(storeAsProperties = true) {907    if (this.options.length) {908      throw new Error('call .storeOptionsAsProperties() before adding options');909    }910    if (Object.keys(this._optionValues).length) {911      throw new Error(912        'call .storeOptionsAsProperties() before setting option values',913      );914    }915    this._storeOptionsAsProperties = !!storeAsProperties;916    return this;917  }918919  /**920   * Retrieve option value.921   *922   * @param {string} key923   * @return {object} value924   */925926  getOptionValue(key) {927    if (this._storeOptionsAsProperties) {928      return this[key];929    }930    return this._optionValues[key];931  }932933  /**934   * Store option value.935   *936   * @param {string} key937   * @param {object} value938   * @return {Command} `this` command for chaining939   */940941  setOptionValue(key, value) {942    return this.setOptionValueWithSource(key, value, undefined);943  }944945  /**946   * Store option value and where the value came from.947   *948   * @param {string} key949   * @param {object} value950   * @param {string} source - expected values are default/config/env/cli/implied951   * @return {Command} `this` command for chaining952   */953954  setOptionValueWithSource(key, value, source) {955    if (this._storeOptionsAsProperties) {956      this[key] = value;957    } else {958      this._optionValues[key] = value;959    }960    this._optionValueSources[key] = source;961    return this;962  }963964  /**965   * Get source of option value.966   * Expected values are default | config | env | cli | implied967   *968   * @param {string} key969   * @return {string}970   */971972  getOptionValueSource(key) {973    return this._optionValueSources[key];974  }975976  /**977   * Get source of option value. See also .optsWithGlobals().978   * Expected values are default | config | env | cli | implied979   *980   * @param {string} key981   * @return {string}982   */983984  getOptionValueSourceWithGlobals(key) {985    // global overwrites local, like optsWithGlobals986    let source;987    this._getCommandAndAncestors().forEach((cmd) => {988      if (cmd.getOptionValueSource(key) !== undefined) {989        source = cmd.getOptionValueSource(key);990      }991    });992    return source;993  }994995  /**996   * Get user arguments from implied or explicit arguments.997   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.998   *999   * @private1000   */10011002  _prepareUserArgs(argv, parseOptions) {1003    if (argv !== undefined && !Array.isArray(argv)) {1004      throw new Error('first parameter to parse must be array or undefined');1005    }1006    parseOptions = parseOptions || {};10071008    // auto-detect argument conventions if nothing supplied1009    if (argv === undefined && parseOptions.from === undefined) {1010      if (process.versions?.electron) {1011        parseOptions.from = 'electron';1012      }1013      // check node specific options for scenarios where user CLI args follow executable without scriptname1014      const execArgv = process.execArgv ?? [];1015      if (1016        execArgv.includes('-e') ||1017        execArgv.includes('--eval') ||1018        execArgv.includes('-p') ||1019        execArgv.includes('--print')1020      ) {1021        parseOptions.from = 'eval'; // internal usage, not documented1022      }1023    }10241025    // default to using process.argv1026    if (argv === undefined) {1027      argv = process.argv;1028    }1029    this.rawArgs = argv.slice();10301031    // extract the user args and scriptPath1032    let userArgs;1033    switch (parseOptions.from) {1034      case undefined:1035      case 'node':1036        this._scriptPath = argv[1];1037        userArgs = argv.slice(2);1038        break;1039      case 'electron':1040        // @ts-ignore: because defaultApp is an unknown property1041        if (process.defaultApp) {1042          this._scriptPath = argv[1];1043          userArgs = argv.slice(2);1044        } else {1045          userArgs = argv.slice(1);1046        }1047        break;1048      case 'user':1049        userArgs = argv.slice(0);1050        break;1051      case 'eval':1052        userArgs = argv.slice(1);1053        break;1054      default:1055        throw new Error(1056          `unexpected parse option { from: '${parseOptions.from}' }`,1057        );1058    }10591060    // Find default name for program from arguments.1061    if (!this._name && this._scriptPath)1062      this.nameFromFilename(this._scriptPath);1063    this._name = this._name || 'program';10641065    return userArgs;1066  }10671068  /**1069   * Parse `argv`, setting options and invoking commands when defined.1070   *1071   * Use parseAsync instead of parse if any of your action handlers are async.1072   *1073   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1074   *1075   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1076   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1077   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1078   * - `'user'`: just user arguments1079   *1080   * @example1081   * program.parse(); // parse process.argv and auto-detect electron and special node flags1082   * program.parse(process.argv); // assume argv[0] is app and argv[1] is script1083   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1084   *1085   * @param {string[]} [argv] - optional, defaults to process.argv1086   * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1087   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1088   * @return {Command} `this` command for chaining1089   */10901091  parse(argv, parseOptions) {1092    this._prepareForParse();1093    const userArgs = this._prepareUserArgs(argv, parseOptions);1094    this._parseCommand([], userArgs);10951096    return this;1097  }10981099  /**1100   * Parse `argv`, setting options and invoking commands when defined.1101   *1102   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1103   *1104   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1105   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1106   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1107   * - `'user'`: just user arguments1108   *1109   * @example1110   * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1111   * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script1112   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1113   *1114   * @param {string[]} [argv]1115   * @param {object} [parseOptions]1116   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1117   * @return {Promise}1118   */11191120  async parseAsync(argv, parseOptions) {1121    this._prepareForParse();1122    const userArgs = this._prepareUserArgs(argv, parseOptions);1123    await this._parseCommand([], userArgs);11241125    return this;1126  }11271128  _prepareForParse() {1129    if (this._savedState === null) {1130      this.saveStateBeforeParse();1131    } else {1132      this.restoreStateBeforeParse();1133    }1134  }11351136  /**1137   * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.1138   * Not usually called directly, but available for subclasses to save their custom state.1139   *1140   * This is called in a lazy way. Only commands used in parsing chain will have state saved.1141   */1142  saveStateBeforeParse() {1143    this._savedState = {1144      // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1145      _name: this._name,1146      // option values before parse have default values (including false for negated options)1147      // shallow clones1148      _optionValues: { ...this._optionValues },1149      _optionValueSources: { ...this._optionValueSources },1150    };1151  }11521153  /**1154   * Restore state before parse for calls after the first.1155   * Not usually called directly, but available for subclasses to save their custom state.1156   *1157   * This is called in a lazy way. Only commands used in parsing chain will have state restored.1158   */1159  restoreStateBeforeParse() {1160    if (this._storeOptionsAsProperties)1161      throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1162- either make a new Command for each call to parse, or stop storing options as properties`);11631164    // clear state from _prepareUserArgs1165    this._name = this._savedState._name;1166    this._scriptPath = null;1167    this.rawArgs = [];1168    // clear state from setOptionValueWithSource1169    this._optionValues = { ...this._savedState._optionValues };1170    this._optionValueSources = { ...this._savedState._optionValueSources };1171    // clear state from _parseCommand1172    this.args = [];1173    // clear state from _processArguments1174    this.processedArgs = [];1175  }11761177  /**1178   * Throw if expected executable is missing. Add lots of help for author.1179   *1180   * @param {string} executableFile1181   * @param {string} executableDir1182   * @param {string} subcommandName1183   */1184  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1185    if (fs.existsSync(executableFile)) return;11861187    const executableDirMessage = executableDir1188      ? `searched for local subcommand relative to directory '${executableDir}'`1189      : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1190    const executableMissing = `'${executableFile}' does not exist1191 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1192 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1193 - ${executableDirMessage}`;1194    throw new Error(executableMissing);1195  }11961197  /**1198   * Execute a sub-command executable.1199   *1200   * @private1201   */12021203  _executeSubCommand(subcommand, args) {1204    args = args.slice();1205    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1206    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12071208    function findFile(baseDir, baseName) {1209      // Look for specified file1210      const localBin = path.resolve(baseDir, baseName);1211      if (fs.existsSync(localBin)) return localBin;12121213      // Stop looking if candidate already has an expected extension.1214      if (sourceExt.includes(path.extname(baseName))) return undefined;12151216      // Try all the extensions.1217      const foundExt = sourceExt.find((ext) =>1218        fs.existsSync(`${localBin}${ext}`),1219      );1220      if (foundExt) return `${localBin}${foundExt}`;12211222      return undefined;1223    }12241225    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1226    this._checkForMissingMandatoryOptions();1227    this._checkForConflictingOptions();12281229    // executableFile and executableDir might be full path, or just a name1230    let executableFile =1231      subcommand._executableFile || `${this._name}-${subcommand._name}`;1232    let executableDir = this._executableDir || '';1233    if (this._scriptPath) {1234      let resolvedScriptPath; // resolve possible symlink for installed npm binary1235      try {1236        resolvedScriptPath = fs.realpathSync(this._scriptPath);1237      } catch {1238        resolvedScriptPath = this._scriptPath;1239      }1240      executableDir = path.resolve(1241        path.dirname(resolvedScriptPath),1242        executableDir,1243      );1244    }12451246    // Look for a local file in preference to a command in PATH.1247    if (executableDir) {1248      let localFile = findFile(executableDir, executableFile);12491250      // Legacy search using prefix of script name instead of command name1251      if (!localFile && !subcommand._executableFile && this._scriptPath) {1252        const legacyName = path.basename(1253          this._scriptPath,1254          path.extname(this._scriptPath),1255        );1256        if (legacyName !== this._name) {1257          localFile = findFile(1258            executableDir,1259            `${legacyName}-${subcommand._name}`,1260          );1261        }1262      }1263      executableFile = localFile || executableFile;1264    }12651266    launchWithNode = sourceExt.includes(path.extname(executableFile));12671268    let proc;1269    if (process.platform !== 'win32') {1270      if (launchWithNode) {1271        args.unshift(executableFile);1272        // add executable arguments to spawn1273        args = incrementNodeInspectorPort(process.execArgv).concat(args);12741275        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1276      } else {1277        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1278      }1279    } else {1280      this._checkForMissingExecutable(1281        executableFile,1282        executableDir,1283        subcommand._name,1284      );1285      args.unshift(executableFile);1286      // add executable arguments to spawn1287      args = incrementNodeInspectorPort(process.execArgv).concat(args);1288      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1289    }12901291    if (!proc.killed) {1292      // testing mainly to avoid leak warnings during unit tests with mocked spawn1293      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1294      signals.forEach((signal) => {1295        process.on(signal, () => {1296          if (proc.killed === false && proc.exitCode === null) {1297            // @ts-ignore because signals not typed to known strings1298            proc.kill(signal);1299          }1300        });1301      });1302    }13031304    // By default terminate process when spawned process terminates.1305    const exitCallback = this._exitCallback;1306    proc.on('close', (code) => {1307      code = code ?? 1; // code is null if spawned process terminated due to a signal1308      if (!exitCallback) {1309        process.exit(code);1310      } else {1311        exitCallback(1312          new CommanderError(1313            code,1314            'commander.executeSubCommandAsync',1315            '(close)',1316          ),1317        );1318      }1319    });1320    proc.on('error', (err) => {1321      // @ts-ignore: because err.code is an unknown property1322      if (err.code === 'ENOENT') {1323        this._checkForMissingExecutable(1324          executableFile,1325          executableDir,1326          subcommand._name,1327        );1328        // @ts-ignore: because err.code is an unknown property1329      } else if (err.code === 'EACCES') {1330        throw new Error(`'${executableFile}' not executable`);1331      }1332      if (!exitCallback) {1333        process.exit(1);1334      } else {1335        const wrappedError = new CommanderError(1336          1,1337          'commander.executeSubCommandAsync',1338          '(error)',1339        );1340        wrappedError.nestedError = err;1341        exitCallback(wrappedError);1342      }1343    });13441345    // Store the reference to the child process1346    this.runningCommand = proc;1347  }13481349  /**1350   * @private1351   */13521353  _dispatchSubcommand(commandName, operands, unknown) {1354    const subCommand = this._findCommand(commandName);1355    if (!subCommand) this.help({ error: true });13561357    subCommand._prepareForParse();1358    let promiseChain;1359    promiseChain = this._chainOrCallSubCommandHook(1360      promiseChain,1361      subCommand,1362      'preSubcommand',1363    );1364    promiseChain = this._chainOrCall(promiseChain, () => {1365      if (subCommand._executableHandler) {1366        this._executeSubCommand(subCommand, operands.concat(unknown));1367      } else {1368        return subCommand._parseCommand(operands, unknown);1369      }1370    });1371    return promiseChain;1372  }13731374  /**1375   * Invoke help directly if possible, or dispatch if necessary.1376   * e.g. help foo1377   *1378   * @private1379   */13801381  _dispatchHelpCommand(subcommandName) {1382    if (!subcommandName) {1383      this.help();1384    }1385    const subCommand = this._findCommand(subcommandName);1386    if (subCommand && !subCommand._executableHandler) {1387      subCommand.help();1388    }13891390    // Fallback to parsing the help flag to invoke the help.1391    return this._dispatchSubcommand(1392      subcommandName,1393      [],1394      [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1395    );1396  }13971398  /**1399   * Check this.args against expected this.registeredArguments.1400   *1401   * @private1402   */14031404  _checkNumberOfArguments() {1405    // too few1406    this.registeredArguments.forEach((arg, i) => {1407      if (arg.required && this.args[i] == null) {1408        this.missingArgument(arg.name());1409      }1410    });1411    // too many1412    if (1413      this.registeredArguments.length > 0 &&1414      this.registeredArguments[this.registeredArguments.length - 1].variadic1415    ) {1416      return;1417    }1418    if (this.args.length > this.registeredArguments.length) {1419      this._excessArguments(this.args);1420    }1421  }14221423  /**1424   * Process this.args using this.registeredArguments and save as this.processedArgs!1425   *1426   * @private1427   */14281429  _processArguments() {1430    const myParseArg = (argument, value, previous) => {1431      // Extra processing for nice error message on parsing failure.1432      let parsedValue = value;1433      if (value !== null && argument.parseArg) {1434        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1435        parsedValue = this._callParseArg(1436          argument,1437          value,1438          previous,1439          invalidValueMessage,1440        );1441      }1442      return parsedValue;1443    };14441445    this._checkNumberOfArguments();14461447    const processedArgs = [];1448    this.registeredArguments.forEach((declaredArg, index) => {1449      let value = declaredArg.defaultValue;1450      if (declaredArg.variadic) {1451        // Collect together remaining arguments for passing together as an array.1452        if (index < this.args.length) {1453          value = this.args.slice(index);1454          if (declaredArg.parseArg) {1455            value = value.reduce((processed, v) => {1456              return myParseArg(declaredArg, v, processed);1457            }, declaredArg.defaultValue);1458          }1459        } else if (value === undefined) {1460          value = [];1461        }1462      } else if (index < this.args.length) {1463        value = this.args[index];1464        if (declaredArg.parseArg) {1465          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1466        }1467      }1468      processedArgs[index] = value;1469    });1470    this.processedArgs = processedArgs;1471  }14721473  /**1474   * Once we have a promise we chain, but call synchronously until then.1475   *1476   * @param {(Promise|undefined)} promise1477   * @param {Function} fn1478   * @return {(Promise|undefined)}1479   * @private1480   */14811482  _chainOrCall(promise, fn) {1483    // thenable1484    if (promise && promise.then && typeof promise.then === 'function') {1485      // already have a promise, chain callback1486      return promise.then(() => fn());1487    }1488    // callback might return a promise1489    return fn();1490  }14911492  /**1493   *1494   * @param {(Promise|undefined)} promise1495   * @param {string} event1496   * @return {(Promise|undefined)}1497   * @private1498   */14991500  _chainOrCallHooks(promise, event) {1501    let result = promise;1502    const hooks = [];1503    this._getCommandAndAncestors()1504      .reverse()1505      .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1506      .forEach((hookedCommand) => {1507        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1508          hooks.push({ hookedCommand, callback });1509        });1510      });1511    if (event === 'postAction') {1512      hooks.reverse();1513    }15141515    hooks.forEach((hookDetail) => {1516      result = this._chainOrCall(result, () => {1517        return hookDetail.callback(hookDetail.hookedCommand, this);1518      });1519    });1520    return result;1521  }15221523  /**1524   *1525   * @param {(Promise|undefined)} promise1526   * @param {Command} subCommand1527   * @param {string} event1528   * @return {(Promise|undefined)}1529   * @private1530   */15311532  _chainOrCallSubCommandHook(promise, subCommand, event) {1533    let result = promise;1534    if (this._lifeCycleHooks[event] !== undefined) {1535      this._lifeCycleHooks[event].forEach((hook) => {1536        result = this._chainOrCall(result, () => {1537          return hook(this, subCommand);1538        });1539      });1540    }1541    return result;1542  }15431544  /**1545   * Process arguments in context of this command.1546   * Returns action result, in case it is a promise.1547   *1548   * @private1549   */15501551  _parseCommand(operands, unknown) {1552    const parsed = this.parseOptions(unknown);1553    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1554    this._parseOptionsImplied();1555    operands = operands.concat(parsed.operands);1556    unknown = parsed.unknown;1557    this.args = operands.concat(unknown);15581559    if (operands && this._findCommand(operands[0])) {1560      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1561    }1562    if (1563      this._getHelpCommand() &&1564      operands[0] === this._getHelpCommand().name()1565    ) {1566      return this._dispatchHelpCommand(operands[1]);1567    }1568    if (this._defaultCommandName) {1569      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1570      return this._dispatchSubcommand(1571        this._defaultCommandName,1572        operands,1573        unknown,1574      );1575    }1576    if (1577      this.commands.length &&1578      this.args.length === 0 &&1579      !this._actionHandler &&1580      !this._defaultCommandName1581    ) {1582      // probably missing subcommand and no handler, user needs help (and exit)1583      this.help({ error: true });1584    }15851586    this._outputHelpIfRequested(parsed.unknown);1587    this._checkForMissingMandatoryOptions();1588    this._checkForConflictingOptions();15891590    // We do not always call this check to avoid masking a "better" error, like unknown command.1591    const checkForUnknownOptions = () => {1592      if (parsed.unknown.length > 0) {1593        this.unknownOption(parsed.unknown[0]);1594      }1595    };15961597    const commandEvent = `command:${this.name()}`;1598    if (this._actionHandler) {1599      checkForUnknownOptions();1600      this._processArguments();16011602      let promiseChain;1603      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1604      promiseChain = this._chainOrCall(promiseChain, () =>1605        this._actionHandler(this.processedArgs),1606      );1607      if (this.parent) {1608        promiseChain = this._chainOrCall(promiseChain, () => {1609          this.parent.emit(commandEvent, operands, unknown); // legacy1610        });1611      }1612      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1613      return promiseChain;1614    }1615    if (this.parent && this.parent.listenerCount(commandEvent)) {1616      checkForUnknownOptions();1617      this._processArguments();1618      this.parent.emit(commandEvent, operands, unknown); // legacy1619    } else if (operands.length) {1620      if (this._findCommand('*')) {1621        // legacy default command1622        return this._dispatchSubcommand('*', operands, unknown);1623      }1624      if (this.listenerCount('command:*')) {1625        // skip option check, emit event for possible misspelling suggestion1626        this.emit('command:*', operands, unknown);1627      } else if (this.commands.length) {1628        this.unknownCommand();1629      } else {1630        checkForUnknownOptions();1631        this._processArguments();1632      }1633    } else if (this.commands.length) {1634      checkForUnknownOptions();1635      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1636      this.help({ error: true });1637    } else {1638      checkForUnknownOptions();1639      this._processArguments();1640      // fall through for caller to handle after calling .parse()1641    }1642  }16431644  /**1645   * Find matching command.1646   *1647   * @private1648   * @return {Command | undefined}1649   */1650  _findCommand(name) {1651    if (!name) return undefined;1652    return this.commands.find(1653      (cmd) => cmd._name === name || cmd._aliases.includes(name),1654    );1655  }16561657  /**1658   * Return an option matching `arg` if any.1659   *1660   * @param {string} arg1661   * @return {Option}1662   * @package1663   */16641665  _findOption(arg) {1666    return this.options.find((option) => option.is(arg));1667  }16681669  /**1670   * Display an error message if a mandatory option does not have a value.1671   * Called after checking for help flags in leaf subcommand.1672   *1673   * @private1674   */16751676  _checkForMissingMandatoryOptions() {1677    // Walk up hierarchy so can call in subcommand after checking for displaying help.1678    this._getCommandAndAncestors().forEach((cmd) => {1679      cmd.options.forEach((anOption) => {1680        if (1681          anOption.mandatory &&1682          cmd.getOptionValue(anOption.attributeName()) === undefined1683        ) {1684          cmd.missingMandatoryOptionValue(anOption);1685        }1686      });1687    });1688  }16891690  /**1691   * Display an error message if conflicting options are used together in this.1692   *1693   * @private1694   */1695  _checkForConflictingLocalOptions() {1696    const definedNonDefaultOptions = this.options.filter((option) => {1697      const optionKey = option.attributeName();1698      if (this.getOptionValue(optionKey) === undefined) {1699        return false;1700      }1701      return this.getOptionValueSource(optionKey) !== 'default';1702    });17031704    const optionsWithConflicting = definedNonDefaultOptions.filter(1705      (option) => option.conflictsWith.length > 0,1706    );17071708    optionsWithConflicting.forEach((option) => {1709      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1710        option.conflictsWith.includes(defined.attributeName()),1711      );1712      if (conflictingAndDefined) {1713        this._conflictingOption(option, conflictingAndDefined);1714      }1715    });1716  }17171718  /**1719   * Display an error message if conflicting options are used together.1720   * Called after checking for help flags in leaf subcommand.1721   *1722   * @private1723   */1724  _checkForConflictingOptions() {1725    // Walk up hierarchy so can call in subcommand after checking for displaying help.1726    this._getCommandAndAncestors().forEach((cmd) => {1727      cmd._checkForConflictingLocalOptions();1728    });1729  }17301731  /**1732   * Parse options from `argv` removing known options,1733   * and return argv split into operands and unknown arguments.1734   *1735   * Side effects: modifies command by storing options. Does not reset state if called again.1736   *1737   * Examples:1738   *1739   *     argv => operands, unknown1740   *     --known kkk op => [op], []1741   *     op --known kkk => [op], []1742   *     sub --unknown uuu op => [sub], [--unknown uuu op]1743   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1744   *1745   * @param {string[]} argv1746   * @return {{operands: string[], unknown: string[]}}1747   */17481749  parseOptions(argv) {1750    const operands = []; // operands, not options or values1751    const unknown = []; // first unknown option and remaining unknown args1752    let dest = operands;1753    const args = argv.slice();17541755    function maybeOption(arg) {1756      return arg.length > 1 && arg[0] === '-';1757    }17581759    const negativeNumberArg = (arg) => {1760      // return false if not a negative number1761      if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;1762      // negative number is ok unless digit used as an option in command hierarchy1763      return !this._getCommandAndAncestors().some((cmd) =>1764        cmd.options1765          .map((opt) => opt.short)1766          .some((short) => /^-\d$/.test(short)),1767      );1768    };17691770    // parse options1771    let activeVariadicOption = null;1772    while (args.length) {1773      const arg = args.shift();17741775      // literal1776      if (arg === '--') {1777        if (dest === unknown) dest.push(arg);1778        dest.push(...args);1779        break;1780      }17811782      if (1783        activeVariadicOption &&1784        (!maybeOption(arg) || negativeNumberArg(arg))1785      ) {1786        this.emit(`option:${activeVariadicOption.name()}`, arg);1787        continue;1788      }1789      activeVariadicOption = null;17901791      if (maybeOption(arg)) {1792        const option = this._findOption(arg);1793        // recognised option, call listener to assign value with possible custom processing1794        if (option) {1795          if (option.required) {1796            const value = args.shift();1797            if (value === undefined) this.optionMissingArgument(option);1798            this.emit(`option:${option.name()}`, value);1799          } else if (option.optional) {1800            let value = null;1801            // historical behaviour is optional value is following arg unless an option1802            if (1803              args.length > 0 &&1804              (!maybeOption(args[0]) || negativeNumberArg(args[0]))1805            ) {1806              value = args.shift();1807            }1808            this.emit(`option:${option.name()}`, value);1809          } else {1810            // boolean flag1811            this.emit(`option:${option.name()}`);1812          }1813          activeVariadicOption = option.variadic ? option : null;1814          continue;1815        }1816      }18171818      // Look for combo options following single dash, eat first one if known.1819      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1820        const option = this._findOption(`-${arg[1]}`);1821        if (option) {1822          if (1823            option.required ||1824            (option.optional && this._combineFlagAndOptionalValue)1825          ) {1826            // option with value following in same argument1827            this.emit(`option:${option.name()}`, arg.slice(2));1828          } else {1829            // boolean option, emit and put back remainder of arg for further processing1830            this.emit(`option:${option.name()}`);1831            args.unshift(`-${arg.slice(2)}`);1832          }1833          continue;1834        }1835      }18361837      // Look for known long flag with value, like --foo=bar1838      if (/^--[^=]+=/.test(arg)) {1839        const index = arg.indexOf('=');1840        const option = this._findOption(arg.slice(0, index));1841        if (option && (option.required || option.optional)) {1842          this.emit(`option:${option.name()}`, arg.slice(index + 1));1843          continue;1844        }1845      }18461847      // Not a recognised option by this command.1848      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18491850      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1851      // A negative number in a leaf command is not an unknown option.1852      if (1853        dest === operands &&1854        maybeOption(arg) &&1855        !(this.commands.length === 0 && negativeNumberArg(arg))1856      ) {1857        dest = unknown;1858      }18591860      // If using positionalOptions, stop processing our options at subcommand.1861      if (1862        (this._enablePositionalOptions || this._passThroughOptions) &&1863        operands.length === 0 &&1864        unknown.length === 01865      ) {1866        if (this._findCommand(arg)) {1867          operands.push(arg);1868          if (args.length > 0) unknown.push(...args);1869          break;1870        } else if (1871          this._getHelpCommand() &&1872          arg === this._getHelpCommand().name()1873        ) {1874          operands.push(arg);1875          if (args.length > 0) operands.push(...args);1876          break;1877        } else if (this._defaultCommandName) {1878          unknown.push(arg);1879          if (args.length > 0) unknown.push(...args);1880          break;1881        }1882      }18831884      // If using passThroughOptions, stop processing options at first command-argument.1885      if (this._passThroughOptions) {1886        dest.push(arg);1887        if (args.length > 0) dest.push(...args);1888        break;1889      }18901891      // add arg1892      dest.push(arg);1893    }18941895    return { operands, unknown };1896  }18971898  /**1899   * Return an object containing local option values as key-value pairs.1900   *1901   * @return {object}1902   */1903  opts() {1904    if (this._storeOptionsAsProperties) {1905      // Preserve original behaviour so backwards compatible when still using properties1906      const result = {};1907      const len = this.options.length;19081909      for (let i = 0; i < len; i++) {1910        const key = this.options[i].attributeName();1911        result[key] =1912          key === this._versionOptionName ? this._version : this[key];1913      }1914      return result;1915    }19161917    return this._optionValues;1918  }19191920  /**1921   * Return an object containing merged local and global option values as key-value pairs.1922   *1923   * @return {object}1924   */1925  optsWithGlobals() {1926    // globals overwrite locals1927    return this._getCommandAndAncestors().reduce(1928      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1929      {},1930    );1931  }19321933  /**1934   * Display error message and exit (or call exitOverride).1935   *1936   * @param {string} message1937   * @param {object} [errorOptions]1938   * @param {string} [errorOptions.code] - an id string representing the error1939   * @param {number} [errorOptions.exitCode] - used with process.exit1940   */1941  error(message, errorOptions) {1942    // output handling1943    this._outputConfiguration.outputError(1944      `${message}\n`,1945      this._outputConfiguration.writeErr,1946    );1947    if (typeof this._showHelpAfterError === 'string') {1948      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1949    } else if (this._showHelpAfterError) {1950      this._outputConfiguration.writeErr('\n');1951      this.outputHelp({ error: true });1952    }19531954    // exit handling1955    const config = errorOptions || {};1956    const exitCode = config.exitCode || 1;1957    const code = config.code || 'commander.error';1958    this._exit(exitCode, code, message);1959  }19601961  /**1962   * Apply any option related environment variables, if option does1963   * not have a value from cli or client code.1964   *1965   * @private1966   */1967  _parseOptionsEnv() {1968    this.options.forEach((option) => {1969      if (option.envVar && option.envVar in process.env) {1970        const optionKey = option.attributeName();1971        // Priority check. Do not overwrite cli or options from unknown source (client-code).1972        if (1973          this.getOptionValue(optionKey) === undefined ||1974          ['default', 'config', 'env'].includes(1975            this.getOptionValueSource(optionKey),1976          )1977        ) {1978          if (option.required || option.optional) {1979            // option can take a value1980            // keep very simple, optional always takes value1981            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1982          } else {1983            // boolean1984            // keep very simple, only care that envVar defined and not the value1985            this.emit(`optionEnv:${option.name()}`);1986          }1987        }1988      }1989    });1990  }19911992  /**1993   * Apply any implied option values, if option is undefined or default value.1994   *1995   * @private1996   */1997  _parseOptionsImplied() {1998    const dualHelper = new DualOptions(this.options);1999    const hasCustomOptionValue = (optionKey) => {2000      return (

The first 2,000 of 2,778 lines.