Skip to content
Myr

command.js

This file

Path

lib/command.js

2,585 lines · 79.1 KiB · JavaScript

Last changed by

Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4

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;5859    // see configureOutput() for docs60    this._outputConfiguration = {61      writeOut: (str) => process.stdout.write(str),62      writeErr: (str) => process.stderr.write(str),63      outputError: (str, write) => write(str),64      getOutHelpWidth: () =>65        process.stdout.isTTY ? process.stdout.columns : undefined,66      getErrHelpWidth: () =>67        process.stderr.isTTY ? process.stderr.columns : undefined,68      getOutHasColors: () =>69        useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),70      getErrHasColors: () =>71        useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),72      stripColor: (str) => stripColor(str),73    };7475    this._hidden = false;76    /** @type {(Option | null | undefined)} */77    this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.78    this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited79    /** @type {Command} */80    this._helpCommand = undefined; // lazy initialised, inherited81    this._helpConfiguration = {};82  }8384  /**85   * Copy settings that are useful to have in common across root command and subcommands.86   *87   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)88   *89   * @param {Command} sourceCommand90   * @return {Command} `this` command for chaining91   */92  copyInheritedSettings(sourceCommand) {93    this._outputConfiguration = sourceCommand._outputConfiguration;94    this._helpOption = sourceCommand._helpOption;95    this._helpCommand = sourceCommand._helpCommand;96    this._helpConfiguration = sourceCommand._helpConfiguration;97    this._exitCallback = sourceCommand._exitCallback;98    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;99    this._combineFlagAndOptionalValue =100      sourceCommand._combineFlagAndOptionalValue;101    this._allowExcessArguments = sourceCommand._allowExcessArguments;102    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103    this._showHelpAfterError = sourceCommand._showHelpAfterError;104    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;105106    return this;107  }108109  /**110   * @returns {Command[]}111   * @private112   */113114  _getCommandAndAncestors() {115    const result = [];116    // eslint-disable-next-line @typescript-eslint/no-this-alias117    for (let command = this; command; command = command.parent) {118      result.push(command);119    }120    return result;121  }122123  /**124   * Define a command.125   *126   * There are two styles of command: pay attention to where to put the description.127   *128   * @example129   * // Command implemented using action handler (description is supplied separately to `.command`)130   * program131   *   .command('clone <source> [destination]')132   *   .description('clone a repository into a newly created directory')133   *   .action((source, destination) => {134   *     console.log('clone command called');135   *   });136   *137   * // Command implemented using separate executable file (description is second parameter to `.command`)138   * program139   *   .command('start <service>', 'start named service')140   *   .command('stop [service]', 'stop named service, or all if no name supplied');141   *142   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`143   * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)144   * @param {object} [execOpts] - configuration options (for executable)145   * @return {Command} returns new command for action handler, or `this` for executable command146   */147148  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {149    let desc = actionOptsOrExecDesc;150    let opts = execOpts;151    if (typeof desc === 'object' && desc !== null) {152      opts = desc;153      desc = null;154    }155    opts = opts || {};156    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);157158    const cmd = this.createCommand(name);159    if (desc) {160      cmd.description(desc);161      cmd._executableHandler = true;162    }163    if (opts.isDefault) this._defaultCommandName = cmd._name;164    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden165    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor166    if (args) cmd.arguments(args);167    this._registerCommand(cmd);168    cmd.parent = this;169    cmd.copyInheritedSettings(this);170171    if (desc) return this;172    return cmd;173  }174175  /**176   * Factory routine to create a new unattached command.177   *178   * See .command() for creating an attached subcommand, which uses this routine to179   * create the command. You can override createCommand to customise subcommands.180   *181   * @param {string} [name]182   * @return {Command} new command183   */184185  createCommand(name) {186    return new Command(name);187  }188189  /**190   * You can customise the help with a subclass of Help by overriding createHelp,191   * or by overriding Help properties using configureHelp().192   *193   * @return {Help}194   */195196  createHelp() {197    return Object.assign(new Help(), this.configureHelp());198  }199200  /**201   * You can customise the help by overriding Help properties using configureHelp(),202   * or with a subclass of Help by overriding createHelp().203   *204   * @param {object} [configuration] - configuration options205   * @return {(Command | object)} `this` command for chaining, or stored configuration206   */207208  configureHelp(configuration) {209    if (configuration === undefined) return this._helpConfiguration;210211    this._helpConfiguration = configuration;212    return this;213  }214215  /**216   * The default output goes to stdout and stderr. You can customise this for special217   * applications. You can also customise the display of errors by overriding outputError.218   *219   * The configuration properties are all functions:220   *221   *     // change how output being written, defaults to stdout and stderr222   *     writeOut(str)223   *     writeErr(str)224   *     // change how output being written for errors, defaults to writeErr225   *     outputError(str, write) // used for displaying errors and not used for displaying help226   *     // specify width for wrapping help227   *     getOutHelpWidth()228   *     getErrHelpWidth()229   *     // color support, currently only used with Help230   *     getOutHasColors()231   *     getErrHasColors()232   *     stripColor() // used to remove ANSI escape codes if output does not have colors233   *234   * @param {object} [configuration] - configuration options235   * @return {(Command | object)} `this` command for chaining, or stored configuration236   */237238  configureOutput(configuration) {239    if (configuration === undefined) return this._outputConfiguration;240241    Object.assign(this._outputConfiguration, configuration);242    return this;243  }244245  /**246   * Display the help or a custom message after an error occurs.247   *248   * @param {(boolean|string)} [displayHelp]249   * @return {Command} `this` command for chaining250   */251  showHelpAfterError(displayHelp = true) {252    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;253    this._showHelpAfterError = displayHelp;254    return this;255  }256257  /**258   * Display suggestion of similar commands for unknown commands, or options for unknown options.259   *260   * @param {boolean} [displaySuggestion]261   * @return {Command} `this` command for chaining262   */263  showSuggestionAfterError(displaySuggestion = true) {264    this._showSuggestionAfterError = !!displaySuggestion;265    return this;266  }267268  /**269   * Add a prepared subcommand.270   *271   * See .command() for creating an attached subcommand which inherits settings from its parent.272   *273   * @param {Command} cmd - new subcommand274   * @param {object} [opts] - configuration options275   * @return {Command} `this` command for chaining276   */277278  addCommand(cmd, opts) {279    if (!cmd._name) {280      throw new Error(`Command passed to .addCommand() must have a name281- specify the name in Command constructor or using .name()`);282    }283284    opts = opts || {};285    if (opts.isDefault) this._defaultCommandName = cmd._name;286    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation287288    this._registerCommand(cmd);289    cmd.parent = this;290    cmd._checkForBrokenPassThrough();291292    return this;293  }294295  /**296   * Factory routine to create a new unattached argument.297   *298   * See .argument() for creating an attached argument, which uses this routine to299   * create the argument. You can override createArgument to return a custom argument.300   *301   * @param {string} name302   * @param {string} [description]303   * @return {Argument} new argument304   */305306  createArgument(name, description) {307    return new Argument(name, description);308  }309310  /**311   * Define argument syntax for command.312   *313   * The default is that the argument is required, and you can explicitly314   * indicate this with <> around the name. Put [] around the name for an optional argument.315   *316   * @example317   * program.argument('<input-file>');318   * program.argument('[output-file]');319   *320   * @param {string} name321   * @param {string} [description]322   * @param {(Function|*)} [fn] - custom argument processing function323   * @param {*} [defaultValue]324   * @return {Command} `this` command for chaining325   */326  argument(name, description, fn, defaultValue) {327    const argument = this.createArgument(name, description);328    if (typeof fn === 'function') {329      argument.default(defaultValue).argParser(fn);330    } else {331      argument.default(fn);332    }333    this.addArgument(argument);334    return this;335  }336337  /**338   * Define argument syntax for command, adding multiple at once (without descriptions).339   *340   * See also .argument().341   *342   * @example343   * program.arguments('<cmd> [env]');344   *345   * @param {string} names346   * @return {Command} `this` command for chaining347   */348349  arguments(names) {350    names351      .trim()352      .split(/ +/)353      .forEach((detail) => {354        this.argument(detail);355      });356    return this;357  }358359  /**360   * Define argument syntax for command, adding a prepared argument.361   *362   * @param {Argument} argument363   * @return {Command} `this` command for chaining364   */365  addArgument(argument) {366    const previousArgument = this.registeredArguments.slice(-1)[0];367    if (previousArgument && previousArgument.variadic) {368      throw new Error(369        `only the last argument can be variadic '${previousArgument.name()}'`,370      );371    }372    if (373      argument.required &&374      argument.defaultValue !== undefined &&375      argument.parseArg === undefined376    ) {377      throw new Error(378        `a default value for a required argument is never used: '${argument.name()}'`,379      );380    }381    this.registeredArguments.push(argument);382    return this;383  }384385  /**386   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.387   *388   * @example389   *    program.helpCommand('help [cmd]');390   *    program.helpCommand('help [cmd]', 'show help');391   *    program.helpCommand(false); // suppress default help command392   *    program.helpCommand(true); // add help command even if no subcommands393   *394   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added395   * @param {string} [description] - custom description396   * @return {Command} `this` command for chaining397   */398399  helpCommand(enableOrNameAndArgs, description) {400    if (typeof enableOrNameAndArgs === 'boolean') {401      this._addImplicitHelpCommand = enableOrNameAndArgs;402      return this;403    }404405    enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';406    const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);407    const helpDescription = description ?? 'display help for command';408409    const helpCommand = this.createCommand(helpName);410    helpCommand.helpOption(false);411    if (helpArgs) helpCommand.arguments(helpArgs);412    if (helpDescription) helpCommand.description(helpDescription);413414    this._addImplicitHelpCommand = true;415    this._helpCommand = helpCommand;416417    return this;418  }419420  /**421   * Add prepared custom help command.422   *423   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`424   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only425   * @return {Command} `this` command for chaining426   */427  addHelpCommand(helpCommand, deprecatedDescription) {428    // If not passed an object, call through to helpCommand for backwards compatibility,429    // as addHelpCommand was originally used like helpCommand is now.430    if (typeof helpCommand !== 'object') {431      this.helpCommand(helpCommand, deprecatedDescription);432      return this;433    }434435    this._addImplicitHelpCommand = true;436    this._helpCommand = helpCommand;437    return this;438  }439440  /**441   * Lazy create help command.442   *443   * @return {(Command|null)}444   * @package445   */446  _getHelpCommand() {447    const hasImplicitHelpCommand =448      this._addImplicitHelpCommand ??449      (this.commands.length &&450        !this._actionHandler &&451        !this._findCommand('help'));452453    if (hasImplicitHelpCommand) {454      if (this._helpCommand === undefined) {455        this.helpCommand(undefined, undefined); // use default name and description456      }457      return this._helpCommand;458    }459    return null;460  }461462  /**463   * Add hook for life cycle event.464   *465   * @param {string} event466   * @param {Function} listener467   * @return {Command} `this` command for chaining468   */469470  hook(event, listener) {471    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];472    if (!allowedValues.includes(event)) {473      throw new Error(`Unexpected value for event passed to hook : '${event}'.474Expecting one of '${allowedValues.join("', '")}'`);475    }476    if (this._lifeCycleHooks[event]) {477      this._lifeCycleHooks[event].push(listener);478    } else {479      this._lifeCycleHooks[event] = [listener];480    }481    return this;482  }483484  /**485   * Register callback to use as replacement for calling process.exit.486   *487   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing488   * @return {Command} `this` command for chaining489   */490491  exitOverride(fn) {492    if (fn) {493      this._exitCallback = fn;494    } else {495      this._exitCallback = (err) => {496        if (err.code !== 'commander.executeSubCommandAsync') {497          throw err;498        } else {499          // Async callback from spawn events, not useful to throw.500        }501      };502    }503    return this;504  }505506  /**507   * Call process.exit, and _exitCallback if defined.508   *509   * @param {number} exitCode exit code for using with process.exit510   * @param {string} code an id string representing the error511   * @param {string} message human-readable description of the error512   * @return never513   * @private514   */515516  _exit(exitCode, code, message) {517    if (this._exitCallback) {518      this._exitCallback(new CommanderError(exitCode, code, message));519      // Expecting this line is not reached.520    }521    process.exit(exitCode);522  }523524  /**525   * Register callback `fn` for the command.526   *527   * @example528   * program529   *   .command('serve')530   *   .description('start service')531   *   .action(function() {532   *      // do work here533   *   });534   *535   * @param {Function} fn536   * @return {Command} `this` command for chaining537   */538539  action(fn) {540    const listener = (args) => {541      // The .action callback takes an extra parameter which is the command or options.542      const expectedArgsCount = this.registeredArguments.length;543      const actionArgs = args.slice(0, expectedArgsCount);544      if (this._storeOptionsAsProperties) {545        actionArgs[expectedArgsCount] = this; // backwards compatible "options"546      } else {547        actionArgs[expectedArgsCount] = this.opts();548      }549      actionArgs.push(this);550551      return fn.apply(this, actionArgs);552    };553    this._actionHandler = listener;554    return this;555  }556557  /**558   * Factory routine to create a new unattached option.559   *560   * See .option() for creating an attached option, which uses this routine to561   * create the option. You can override createOption to return a custom option.562   *563   * @param {string} flags564   * @param {string} [description]565   * @return {Option} new option566   */567568  createOption(flags, description) {569    return new Option(flags, description);570  }571572  /**573   * Wrap parseArgs to catch 'commander.invalidArgument'.574   *575   * @param {(Option | Argument)} target576   * @param {string} value577   * @param {*} previous578   * @param {string} invalidArgumentMessage579   * @private580   */581582  _callParseArg(target, value, previous, invalidArgumentMessage) {583    try {584      return target.parseArg(value, previous);585    } catch (err) {586      if (err.code === 'commander.invalidArgument') {587        const message = `${invalidArgumentMessage} ${err.message}`;588        this.error(message, { exitCode: err.exitCode, code: err.code });589      }590      throw err;591    }592  }593594  /**595   * Check for option flag conflicts.596   * Register option if no conflicts found, or throw on conflict.597   *598   * @param {Option} option599   * @private600   */601602  _registerOption(option) {603    const matchingOption =604      (option.short && this._findOption(option.short)) ||605      (option.long && this._findOption(option.long));606    if (matchingOption) {607      const matchingFlag =608        option.long && this._findOption(option.long)609          ? option.long610          : option.short;611      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'612-  already used by option '${matchingOption.flags}'`);613    }614615    this.options.push(option);616  }617618  /**619   * Check for command name and alias conflicts with existing commands.620   * Register command if no conflicts found, or throw on conflict.621   *622   * @param {Command} command623   * @private624   */625626  _registerCommand(command) {627    const knownBy = (cmd) => {628      return [cmd.name()].concat(cmd.aliases());629    };630631    const alreadyUsed = knownBy(command).find((name) =>632      this._findCommand(name),633    );634    if (alreadyUsed) {635      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');636      const newCmd = knownBy(command).join('|');637      throw new Error(638        `cannot add command '${newCmd}' as already have command '${existingCmd}'`,639      );640    }641642    this.commands.push(command);643  }644645  /**646   * Add an option.647   *648   * @param {Option} option649   * @return {Command} `this` command for chaining650   */651  addOption(option) {652    this._registerOption(option);653654    const oname = option.name();655    const name = option.attributeName();656657    // store default value658    if (option.negate) {659      // --no-foo is special and defaults foo to true, unless a --foo option is already defined660      const positiveLongFlag = option.long.replace(/^--no-/, '--');661      if (!this._findOption(positiveLongFlag)) {662        this.setOptionValueWithSource(663          name,664          option.defaultValue === undefined ? true : option.defaultValue,665          'default',666        );667      }668    } else if (option.defaultValue !== undefined) {669      this.setOptionValueWithSource(name, option.defaultValue, 'default');670    }671672    // handler for cli and env supplied values673    const handleOptionValue = (val, invalidValueMessage, valueSource) => {674      // val is null for optional option used without an optional-argument.675      // val is undefined for boolean and negated option.676      if (val == null && option.presetArg !== undefined) {677        val = option.presetArg;678      }679680      // custom processing681      const oldValue = this.getOptionValue(name);682      if (val !== null && option.parseArg) {683        val = this._callParseArg(option, val, oldValue, invalidValueMessage);684      } else if (val !== null && option.variadic) {685        val = option._concatValue(val, oldValue);686      }687688      // Fill-in appropriate missing values. Long winded but easy to follow.689      if (val == null) {690        if (option.negate) {691          val = false;692        } else if (option.isBoolean() || option.optional) {693          val = true;694        } else {695          val = ''; // not normal, parseArg might have failed or be a mock function for testing696        }697      }698      this.setOptionValueWithSource(name, val, valueSource);699    };700701    this.on('option:' + oname, (val) => {702      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;703      handleOptionValue(val, invalidValueMessage, 'cli');704    });705706    if (option.envVar) {707      this.on('optionEnv:' + oname, (val) => {708        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;709        handleOptionValue(val, invalidValueMessage, 'env');710      });711    }712713    return this;714  }715716  /**717   * Internal implementation shared by .option() and .requiredOption()718   *719   * @return {Command} `this` command for chaining720   * @private721   */722  _optionEx(config, flags, description, fn, defaultValue) {723    if (typeof flags === 'object' && flags instanceof Option) {724      throw new Error(725        'To add an Option object use addOption() instead of option() or requiredOption()',726      );727    }728    const option = this.createOption(flags, description);729    option.makeOptionMandatory(!!config.mandatory);730    if (typeof fn === 'function') {731      option.default(defaultValue).argParser(fn);732    } else if (fn instanceof RegExp) {733      // deprecated734      const regex = fn;735      fn = (val, def) => {736        const m = regex.exec(val);737        return m ? m[0] : def;738      };739      option.default(defaultValue).argParser(fn);740    } else {741      option.default(fn);742    }743744    return this.addOption(option);745  }746747  /**748   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.749   *750   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required751   * option-argument is indicated by `<>` and an optional option-argument by `[]`.752   *753   * See the README for more details, and see also addOption() and requiredOption().754   *755   * @example756   * program757   *     .option('-p, --pepper', 'add pepper')758   *     .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument759   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default760   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function761   *762   * @param {string} flags763   * @param {string} [description]764   * @param {(Function|*)} [parseArg] - custom option processing function or default value765   * @param {*} [defaultValue]766   * @return {Command} `this` command for chaining767   */768769  option(flags, description, parseArg, defaultValue) {770    return this._optionEx({}, flags, description, parseArg, defaultValue);771  }772773  /**774   * Add a required option which must have a value after parsing. This usually means775   * the option must be specified on the command line. (Otherwise the same as .option().)776   *777   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.778   *779   * @param {string} flags780   * @param {string} [description]781   * @param {(Function|*)} [parseArg] - custom option processing function or default value782   * @param {*} [defaultValue]783   * @return {Command} `this` command for chaining784   */785786  requiredOption(flags, description, parseArg, defaultValue) {787    return this._optionEx(788      { mandatory: true },789      flags,790      description,791      parseArg,792      defaultValue,793    );794  }795796  /**797   * Alter parsing of short flags with optional values.798   *799   * @example800   * // for `.option('-f,--flag [value]'):801   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour802   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`803   *804   * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.805   * @return {Command} `this` command for chaining806   */807  combineFlagAndOptionalValue(combine = true) {808    this._combineFlagAndOptionalValue = !!combine;809    return this;810  }811812  /**813   * Allow unknown options on the command line.814   *815   * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.816   * @return {Command} `this` command for chaining817   */818  allowUnknownOption(allowUnknown = true) {819    this._allowUnknownOption = !!allowUnknown;820    return this;821  }822823  /**824   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.825   *826   * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.827   * @return {Command} `this` command for chaining828   */829  allowExcessArguments(allowExcess = true) {830    this._allowExcessArguments = !!allowExcess;831    return this;832  }833834  /**835   * Enable positional options. Positional means global options are specified before subcommands which lets836   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.837   * The default behaviour is non-positional and global options may appear anywhere on the command line.838   *839   * @param {boolean} [positional]840   * @return {Command} `this` command for chaining841   */842  enablePositionalOptions(positional = true) {843    this._enablePositionalOptions = !!positional;844    return this;845  }846847  /**848   * Pass through options that come after command-arguments rather than treat them as command-options,849   * so actual command-options come before command-arguments. Turning this on for a subcommand requires850   * positional options to have been enabled on the program (parent commands).851   * The default behaviour is non-positional and options may appear before or after command-arguments.852   *853   * @param {boolean} [passThrough] for unknown options.854   * @return {Command} `this` command for chaining855   */856  passThroughOptions(passThrough = true) {857    this._passThroughOptions = !!passThrough;858    this._checkForBrokenPassThrough();859    return this;860  }861862  /**863   * @private864   */865866  _checkForBrokenPassThrough() {867    if (868      this.parent &&869      this._passThroughOptions &&870      !this.parent._enablePositionalOptions871    ) {872      throw new Error(873        `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,874      );875    }876  }877878  /**879   * Whether to store option values as properties on command object,880   * or store separately (specify false). In both cases the option values can be accessed using .opts().881   *882   * @param {boolean} [storeAsProperties=true]883   * @return {Command} `this` command for chaining884   */885886  storeOptionsAsProperties(storeAsProperties = true) {887    if (this.options.length) {888      throw new Error('call .storeOptionsAsProperties() before adding options');889    }890    if (Object.keys(this._optionValues).length) {891      throw new Error(892        'call .storeOptionsAsProperties() before setting option values',893      );894    }895    this._storeOptionsAsProperties = !!storeAsProperties;896    return this;897  }898899  /**900   * Retrieve option value.901   *902   * @param {string} key903   * @return {object} value904   */905906  getOptionValue(key) {907    if (this._storeOptionsAsProperties) {908      return this[key];909    }910    return this._optionValues[key];911  }912913  /**914   * Store option value.915   *916   * @param {string} key917   * @param {object} value918   * @return {Command} `this` command for chaining919   */920921  setOptionValue(key, value) {922    return this.setOptionValueWithSource(key, value, undefined);923  }924925  /**926   * Store option value and where the value came from.927   *928   * @param {string} key929   * @param {object} value930   * @param {string} source - expected values are default/config/env/cli/implied931   * @return {Command} `this` command for chaining932   */933934  setOptionValueWithSource(key, value, source) {935    if (this._storeOptionsAsProperties) {936      this[key] = value;937    } else {938      this._optionValues[key] = value;939    }940    this._optionValueSources[key] = source;941    return this;942  }943944  /**945   * Get source of option value.946   * Expected values are default | config | env | cli | implied947   *948   * @param {string} key949   * @return {string}950   */951952  getOptionValueSource(key) {953    return this._optionValueSources[key];954  }955956  /**957   * Get source of option value. See also .optsWithGlobals().958   * Expected values are default | config | env | cli | implied959   *960   * @param {string} key961   * @return {string}962   */963964  getOptionValueSourceWithGlobals(key) {965    // global overwrites local, like optsWithGlobals966    let source;967    this._getCommandAndAncestors().forEach((cmd) => {968      if (cmd.getOptionValueSource(key) !== undefined) {969        source = cmd.getOptionValueSource(key);970      }971    });972    return source;973  }974975  /**976   * Get user arguments from implied or explicit arguments.977   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.978   *979   * @private980   */981982  _prepareUserArgs(argv, parseOptions) {983    if (argv !== undefined && !Array.isArray(argv)) {984      throw new Error('first parameter to parse must be array or undefined');985    }986    parseOptions = parseOptions || {};987988    // auto-detect argument conventions if nothing supplied989    if (argv === undefined && parseOptions.from === undefined) {990      if (process.versions?.electron) {991        parseOptions.from = 'electron';992      }993      // check node specific options for scenarios where user CLI args follow executable without scriptname994      const execArgv = process.execArgv ?? [];995      if (996        execArgv.includes('-e') ||997        execArgv.includes('--eval') ||998        execArgv.includes('-p') ||999        execArgv.includes('--print')1000      ) {1001        parseOptions.from = 'eval'; // internal usage, not documented1002      }1003    }10041005    // default to using process.argv1006    if (argv === undefined) {1007      argv = process.argv;1008    }1009    this.rawArgs = argv.slice();10101011    // extract the user args and scriptPath1012    let userArgs;1013    switch (parseOptions.from) {1014      case undefined:1015      case 'node':1016        this._scriptPath = argv[1];1017        userArgs = argv.slice(2);1018        break;1019      case 'electron':1020        // @ts-ignore: because defaultApp is an unknown property1021        if (process.defaultApp) {1022          this._scriptPath = argv[1];1023          userArgs = argv.slice(2);1024        } else {1025          userArgs = argv.slice(1);1026        }1027        break;1028      case 'user':1029        userArgs = argv.slice(0);1030        break;1031      case 'eval':1032        userArgs = argv.slice(1);1033        break;1034      default:1035        throw new Error(1036          `unexpected parse option { from: '${parseOptions.from}' }`,1037        );1038    }10391040    // Find default name for program from arguments.1041    if (!this._name && this._scriptPath)1042      this.nameFromFilename(this._scriptPath);1043    this._name = this._name || 'program';10441045    return userArgs;1046  }10471048  /**1049   * Parse `argv`, setting options and invoking commands when defined.1050   *1051   * Use parseAsync instead of parse if any of your action handlers are async.1052   *1053   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1054   *1055   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1056   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1057   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1058   * - `'user'`: just user arguments1059   *1060   * @example1061   * program.parse(); // parse process.argv and auto-detect electron and special node flags1062   * program.parse(process.argv); // assume argv[0] is app and argv[1] is script1063   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1064   *1065   * @param {string[]} [argv] - optional, defaults to process.argv1066   * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1067   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1068   * @return {Command} `this` command for chaining1069   */10701071  parse(argv, parseOptions) {1072    const userArgs = this._prepareUserArgs(argv, parseOptions);1073    this._parseCommand([], userArgs);10741075    return this;1076  }10771078  /**1079   * Parse `argv`, setting options and invoking commands when defined.1080   *1081   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1082   *1083   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1084   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1085   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1086   * - `'user'`: just user arguments1087   *1088   * @example1089   * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1090   * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script1091   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1092   *1093   * @param {string[]} [argv]1094   * @param {object} [parseOptions]1095   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1096   * @return {Promise}1097   */10981099  async parseAsync(argv, parseOptions) {1100    const userArgs = this._prepareUserArgs(argv, parseOptions);1101    await this._parseCommand([], userArgs);11021103    return this;1104  }11051106  /**1107   * Execute a sub-command executable.1108   *1109   * @private1110   */11111112  _executeSubCommand(subcommand, args) {1113    args = args.slice();1114    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1115    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];11161117    function findFile(baseDir, baseName) {1118      // Look for specified file1119      const localBin = path.resolve(baseDir, baseName);1120      if (fs.existsSync(localBin)) return localBin;11211122      // Stop looking if candidate already has an expected extension.1123      if (sourceExt.includes(path.extname(baseName))) return undefined;11241125      // Try all the extensions.1126      const foundExt = sourceExt.find((ext) =>1127        fs.existsSync(`${localBin}${ext}`),1128      );1129      if (foundExt) return `${localBin}${foundExt}`;11301131      return undefined;1132    }11331134    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1135    this._checkForMissingMandatoryOptions();1136    this._checkForConflictingOptions();11371138    // executableFile and executableDir might be full path, or just a name1139    let executableFile =1140      subcommand._executableFile || `${this._name}-${subcommand._name}`;1141    let executableDir = this._executableDir || '';1142    if (this._scriptPath) {1143      let resolvedScriptPath; // resolve possible symlink for installed npm binary1144      try {1145        resolvedScriptPath = fs.realpathSync(this._scriptPath);1146      } catch {1147        resolvedScriptPath = this._scriptPath;1148      }1149      executableDir = path.resolve(1150        path.dirname(resolvedScriptPath),1151        executableDir,1152      );1153    }11541155    // Look for a local file in preference to a command in PATH.1156    if (executableDir) {1157      let localFile = findFile(executableDir, executableFile);11581159      // Legacy search using prefix of script name instead of command name1160      if (!localFile && !subcommand._executableFile && this._scriptPath) {1161        const legacyName = path.basename(1162          this._scriptPath,1163          path.extname(this._scriptPath),1164        );1165        if (legacyName !== this._name) {1166          localFile = findFile(1167            executableDir,1168            `${legacyName}-${subcommand._name}`,1169          );1170        }1171      }1172      executableFile = localFile || executableFile;1173    }11741175    launchWithNode = sourceExt.includes(path.extname(executableFile));11761177    let proc;1178    if (process.platform !== 'win32') {1179      if (launchWithNode) {1180        args.unshift(executableFile);1181        // add executable arguments to spawn1182        args = incrementNodeInspectorPort(process.execArgv).concat(args);11831184        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1185      } else {1186        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1187      }1188    } else {1189      args.unshift(executableFile);1190      // add executable arguments to spawn1191      args = incrementNodeInspectorPort(process.execArgv).concat(args);1192      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1193    }11941195    if (!proc.killed) {1196      // testing mainly to avoid leak warnings during unit tests with mocked spawn1197      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1198      signals.forEach((signal) => {1199        process.on(signal, () => {1200          if (proc.killed === false && proc.exitCode === null) {1201            // @ts-ignore because signals not typed to known strings1202            proc.kill(signal);1203          }1204        });1205      });1206    }12071208    // By default terminate process when spawned process terminates.1209    const exitCallback = this._exitCallback;1210    proc.on('close', (code) => {1211      code = code ?? 1; // code is null if spawned process terminated due to a signal1212      if (!exitCallback) {1213        process.exit(code);1214      } else {1215        exitCallback(1216          new CommanderError(1217            code,1218            'commander.executeSubCommandAsync',1219            '(close)',1220          ),1221        );1222      }1223    });1224    proc.on('error', (err) => {1225      // @ts-ignore: because err.code is an unknown property1226      if (err.code === 'ENOENT') {1227        const executableDirMessage = executableDir1228          ? `searched for local subcommand relative to directory '${executableDir}'`1229          : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1230        const executableMissing = `'${executableFile}' does not exist1231 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1232 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1233 - ${executableDirMessage}`;1234        throw new Error(executableMissing);1235        // @ts-ignore: because err.code is an unknown property1236      } else if (err.code === 'EACCES') {1237        throw new Error(`'${executableFile}' not executable`);1238      }1239      if (!exitCallback) {1240        process.exit(1);1241      } else {1242        const wrappedError = new CommanderError(1243          1,1244          'commander.executeSubCommandAsync',1245          '(error)',1246        );1247        wrappedError.nestedError = err;1248        exitCallback(wrappedError);1249      }1250    });12511252    // Store the reference to the child process1253    this.runningCommand = proc;1254  }12551256  /**1257   * @private1258   */12591260  _dispatchSubcommand(commandName, operands, unknown) {1261    const subCommand = this._findCommand(commandName);1262    if (!subCommand) this.help({ error: true });12631264    let promiseChain;1265    promiseChain = this._chainOrCallSubCommandHook(1266      promiseChain,1267      subCommand,1268      'preSubcommand',1269    );1270    promiseChain = this._chainOrCall(promiseChain, () => {1271      if (subCommand._executableHandler) {1272        this._executeSubCommand(subCommand, operands.concat(unknown));1273      } else {1274        return subCommand._parseCommand(operands, unknown);1275      }1276    });1277    return promiseChain;1278  }12791280  /**1281   * Invoke help directly if possible, or dispatch if necessary.1282   * e.g. help foo1283   *1284   * @private1285   */12861287  _dispatchHelpCommand(subcommandName) {1288    if (!subcommandName) {1289      this.help();1290    }1291    const subCommand = this._findCommand(subcommandName);1292    if (subCommand && !subCommand._executableHandler) {1293      subCommand.help();1294    }12951296    // Fallback to parsing the help flag to invoke the help.1297    return this._dispatchSubcommand(1298      subcommandName,1299      [],1300      [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1301    );1302  }13031304  /**1305   * Check this.args against expected this.registeredArguments.1306   *1307   * @private1308   */13091310  _checkNumberOfArguments() {1311    // too few1312    this.registeredArguments.forEach((arg, i) => {1313      if (arg.required && this.args[i] == null) {1314        this.missingArgument(arg.name());1315      }1316    });1317    // too many1318    if (1319      this.registeredArguments.length > 0 &&1320      this.registeredArguments[this.registeredArguments.length - 1].variadic1321    ) {1322      return;1323    }1324    if (this.args.length > this.registeredArguments.length) {1325      this._excessArguments(this.args);1326    }1327  }13281329  /**1330   * Process this.args using this.registeredArguments and save as this.processedArgs!1331   *1332   * @private1333   */13341335  _processArguments() {1336    const myParseArg = (argument, value, previous) => {1337      // Extra processing for nice error message on parsing failure.1338      let parsedValue = value;1339      if (value !== null && argument.parseArg) {1340        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1341        parsedValue = this._callParseArg(1342          argument,1343          value,1344          previous,1345          invalidValueMessage,1346        );1347      }1348      return parsedValue;1349    };13501351    this._checkNumberOfArguments();13521353    const processedArgs = [];1354    this.registeredArguments.forEach((declaredArg, index) => {1355      let value = declaredArg.defaultValue;1356      if (declaredArg.variadic) {1357        // Collect together remaining arguments for passing together as an array.1358        if (index < this.args.length) {1359          value = this.args.slice(index);1360          if (declaredArg.parseArg) {1361            value = value.reduce((processed, v) => {1362              return myParseArg(declaredArg, v, processed);1363            }, declaredArg.defaultValue);1364          }1365        } else if (value === undefined) {1366          value = [];1367        }1368      } else if (index < this.args.length) {1369        value = this.args[index];1370        if (declaredArg.parseArg) {1371          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1372        }1373      }1374      processedArgs[index] = value;1375    });1376    this.processedArgs = processedArgs;1377  }13781379  /**1380   * Once we have a promise we chain, but call synchronously until then.1381   *1382   * @param {(Promise|undefined)} promise1383   * @param {Function} fn1384   * @return {(Promise|undefined)}1385   * @private1386   */13871388  _chainOrCall(promise, fn) {1389    // thenable1390    if (promise && promise.then && typeof promise.then === 'function') {1391      // already have a promise, chain callback1392      return promise.then(() => fn());1393    }1394    // callback might return a promise1395    return fn();1396  }13971398  /**1399   *1400   * @param {(Promise|undefined)} promise1401   * @param {string} event1402   * @return {(Promise|undefined)}1403   * @private1404   */14051406  _chainOrCallHooks(promise, event) {1407    let result = promise;1408    const hooks = [];1409    this._getCommandAndAncestors()1410      .reverse()1411      .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1412      .forEach((hookedCommand) => {1413        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1414          hooks.push({ hookedCommand, callback });1415        });1416      });1417    if (event === 'postAction') {1418      hooks.reverse();1419    }14201421    hooks.forEach((hookDetail) => {1422      result = this._chainOrCall(result, () => {1423        return hookDetail.callback(hookDetail.hookedCommand, this);1424      });1425    });1426    return result;1427  }14281429  /**1430   *1431   * @param {(Promise|undefined)} promise1432   * @param {Command} subCommand1433   * @param {string} event1434   * @return {(Promise|undefined)}1435   * @private1436   */14371438  _chainOrCallSubCommandHook(promise, subCommand, event) {1439    let result = promise;1440    if (this._lifeCycleHooks[event] !== undefined) {1441      this._lifeCycleHooks[event].forEach((hook) => {1442        result = this._chainOrCall(result, () => {1443          return hook(this, subCommand);1444        });1445      });1446    }1447    return result;1448  }14491450  /**1451   * Process arguments in context of this command.1452   * Returns action result, in case it is a promise.1453   *1454   * @private1455   */14561457  _parseCommand(operands, unknown) {1458    const parsed = this.parseOptions(unknown);1459    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1460    this._parseOptionsImplied();1461    operands = operands.concat(parsed.operands);1462    unknown = parsed.unknown;1463    this.args = operands.concat(unknown);14641465    if (operands && this._findCommand(operands[0])) {1466      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1467    }1468    if (1469      this._getHelpCommand() &&1470      operands[0] === this._getHelpCommand().name()1471    ) {1472      return this._dispatchHelpCommand(operands[1]);1473    }1474    if (this._defaultCommandName) {1475      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1476      return this._dispatchSubcommand(1477        this._defaultCommandName,1478        operands,1479        unknown,1480      );1481    }1482    if (1483      this.commands.length &&1484      this.args.length === 0 &&1485      !this._actionHandler &&1486      !this._defaultCommandName1487    ) {1488      // probably missing subcommand and no handler, user needs help (and exit)1489      this.help({ error: true });1490    }14911492    this._outputHelpIfRequested(parsed.unknown);1493    this._checkForMissingMandatoryOptions();1494    this._checkForConflictingOptions();14951496    // We do not always call this check to avoid masking a "better" error, like unknown command.1497    const checkForUnknownOptions = () => {1498      if (parsed.unknown.length > 0) {1499        this.unknownOption(parsed.unknown[0]);1500      }1501    };15021503    const commandEvent = `command:${this.name()}`;1504    if (this._actionHandler) {1505      checkForUnknownOptions();1506      this._processArguments();15071508      let promiseChain;1509      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1510      promiseChain = this._chainOrCall(promiseChain, () =>1511        this._actionHandler(this.processedArgs),1512      );1513      if (this.parent) {1514        promiseChain = this._chainOrCall(promiseChain, () => {1515          this.parent.emit(commandEvent, operands, unknown); // legacy1516        });1517      }1518      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1519      return promiseChain;1520    }1521    if (this.parent && this.parent.listenerCount(commandEvent)) {1522      checkForUnknownOptions();1523      this._processArguments();1524      this.parent.emit(commandEvent, operands, unknown); // legacy1525    } else if (operands.length) {1526      if (this._findCommand('*')) {1527        // legacy default command1528        return this._dispatchSubcommand('*', operands, unknown);1529      }1530      if (this.listenerCount('command:*')) {1531        // skip option check, emit event for possible misspelling suggestion1532        this.emit('command:*', operands, unknown);1533      } else if (this.commands.length) {1534        this.unknownCommand();1535      } else {1536        checkForUnknownOptions();1537        this._processArguments();1538      }1539    } else if (this.commands.length) {1540      checkForUnknownOptions();1541      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1542      this.help({ error: true });1543    } else {1544      checkForUnknownOptions();1545      this._processArguments();1546      // fall through for caller to handle after calling .parse()1547    }1548  }15491550  /**1551   * Find matching command.1552   *1553   * @private1554   * @return {Command | undefined}1555   */1556  _findCommand(name) {1557    if (!name) return undefined;1558    return this.commands.find(1559      (cmd) => cmd._name === name || cmd._aliases.includes(name),1560    );1561  }15621563  /**1564   * Return an option matching `arg` if any.1565   *1566   * @param {string} arg1567   * @return {Option}1568   * @package1569   */15701571  _findOption(arg) {1572    return this.options.find((option) => option.is(arg));1573  }15741575  /**1576   * Display an error message if a mandatory option does not have a value.1577   * Called after checking for help flags in leaf subcommand.1578   *1579   * @private1580   */15811582  _checkForMissingMandatoryOptions() {1583    // Walk up hierarchy so can call in subcommand after checking for displaying help.1584    this._getCommandAndAncestors().forEach((cmd) => {1585      cmd.options.forEach((anOption) => {1586        if (1587          anOption.mandatory &&1588          cmd.getOptionValue(anOption.attributeName()) === undefined1589        ) {1590          cmd.missingMandatoryOptionValue(anOption);1591        }1592      });1593    });1594  }15951596  /**1597   * Display an error message if conflicting options are used together in this.1598   *1599   * @private1600   */1601  _checkForConflictingLocalOptions() {1602    const definedNonDefaultOptions = this.options.filter((option) => {1603      const optionKey = option.attributeName();1604      if (this.getOptionValue(optionKey) === undefined) {1605        return false;1606      }1607      return this.getOptionValueSource(optionKey) !== 'default';1608    });16091610    const optionsWithConflicting = definedNonDefaultOptions.filter(1611      (option) => option.conflictsWith.length > 0,1612    );16131614    optionsWithConflicting.forEach((option) => {1615      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1616        option.conflictsWith.includes(defined.attributeName()),1617      );1618      if (conflictingAndDefined) {1619        this._conflictingOption(option, conflictingAndDefined);1620      }1621    });1622  }16231624  /**1625   * Display an error message if conflicting options are used together.1626   * Called after checking for help flags in leaf subcommand.1627   *1628   * @private1629   */1630  _checkForConflictingOptions() {1631    // Walk up hierarchy so can call in subcommand after checking for displaying help.1632    this._getCommandAndAncestors().forEach((cmd) => {1633      cmd._checkForConflictingLocalOptions();1634    });1635  }16361637  /**1638   * Parse options from `argv` removing known options,1639   * and return argv split into operands and unknown arguments.1640   *1641   * Examples:1642   *1643   *     argv => operands, unknown1644   *     --known kkk op => [op], []1645   *     op --known kkk => [op], []1646   *     sub --unknown uuu op => [sub], [--unknown uuu op]1647   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1648   *1649   * @param {string[]} argv1650   * @return {{operands: string[], unknown: string[]}}1651   */16521653  parseOptions(argv) {1654    const operands = []; // operands, not options or values1655    const unknown = []; // first unknown option and remaining unknown args1656    let dest = operands;1657    const args = argv.slice();16581659    function maybeOption(arg) {1660      return arg.length > 1 && arg[0] === '-';1661    }16621663    // parse options1664    let activeVariadicOption = null;1665    while (args.length) {1666      const arg = args.shift();16671668      // literal1669      if (arg === '--') {1670        if (dest === unknown) dest.push(arg);1671        dest.push(...args);1672        break;1673      }16741675      if (activeVariadicOption && !maybeOption(arg)) {1676        this.emit(`option:${activeVariadicOption.name()}`, arg);1677        continue;1678      }1679      activeVariadicOption = null;16801681      if (maybeOption(arg)) {1682        const option = this._findOption(arg);1683        // recognised option, call listener to assign value with possible custom processing1684        if (option) {1685          if (option.required) {1686            const value = args.shift();1687            if (value === undefined) this.optionMissingArgument(option);1688            this.emit(`option:${option.name()}`, value);1689          } else if (option.optional) {1690            let value = null;1691            // historical behaviour is optional value is following arg unless an option1692            if (args.length > 0 && !maybeOption(args[0])) {1693              value = args.shift();1694            }1695            this.emit(`option:${option.name()}`, value);1696          } else {1697            // boolean flag1698            this.emit(`option:${option.name()}`);1699          }1700          activeVariadicOption = option.variadic ? option : null;1701          continue;1702        }1703      }17041705      // Look for combo options following single dash, eat first one if known.1706      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1707        const option = this._findOption(`-${arg[1]}`);1708        if (option) {1709          if (1710            option.required ||1711            (option.optional && this._combineFlagAndOptionalValue)1712          ) {1713            // option with value following in same argument1714            this.emit(`option:${option.name()}`, arg.slice(2));1715          } else {1716            // boolean option, emit and put back remainder of arg for further processing1717            this.emit(`option:${option.name()}`);1718            args.unshift(`-${arg.slice(2)}`);1719          }1720          continue;1721        }1722      }17231724      // Look for known long flag with value, like --foo=bar1725      if (/^--[^=]+=/.test(arg)) {1726        const index = arg.indexOf('=');1727        const option = this._findOption(arg.slice(0, index));1728        if (option && (option.required || option.optional)) {1729          this.emit(`option:${option.name()}`, arg.slice(index + 1));1730          continue;1731        }1732      }17331734      // Not a recognised option by this command.1735      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.17361737      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1738      if (maybeOption(arg)) {1739        dest = unknown;1740      }17411742      // If using positionalOptions, stop processing our options at subcommand.1743      if (1744        (this._enablePositionalOptions || this._passThroughOptions) &&1745        operands.length === 0 &&1746        unknown.length === 01747      ) {1748        if (this._findCommand(arg)) {1749          operands.push(arg);1750          if (args.length > 0) unknown.push(...args);1751          break;1752        } else if (1753          this._getHelpCommand() &&1754          arg === this._getHelpCommand().name()1755        ) {1756          operands.push(arg);1757          if (args.length > 0) operands.push(...args);1758          break;1759        } else if (this._defaultCommandName) {1760          unknown.push(arg);1761          if (args.length > 0) unknown.push(...args);1762          break;1763        }1764      }17651766      // If using passThroughOptions, stop processing options at first command-argument.1767      if (this._passThroughOptions) {1768        dest.push(arg);1769        if (args.length > 0) dest.push(...args);1770        break;1771      }17721773      // add arg1774      dest.push(arg);1775    }17761777    return { operands, unknown };1778  }17791780  /**1781   * Return an object containing local option values as key-value pairs.1782   *1783   * @return {object}1784   */1785  opts() {1786    if (this._storeOptionsAsProperties) {1787      // Preserve original behaviour so backwards compatible when still using properties1788      const result = {};1789      const len = this.options.length;17901791      for (let i = 0; i < len; i++) {1792        const key = this.options[i].attributeName();1793        result[key] =1794          key === this._versionOptionName ? this._version : this[key];1795      }1796      return result;1797    }17981799    return this._optionValues;1800  }18011802  /**1803   * Return an object containing merged local and global option values as key-value pairs.1804   *1805   * @return {object}1806   */1807  optsWithGlobals() {1808    // globals overwrite locals1809    return this._getCommandAndAncestors().reduce(1810      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1811      {},1812    );1813  }18141815  /**1816   * Display error message and exit (or call exitOverride).1817   *1818   * @param {string} message1819   * @param {object} [errorOptions]1820   * @param {string} [errorOptions.code] - an id string representing the error1821   * @param {number} [errorOptions.exitCode] - used with process.exit1822   */1823  error(message, errorOptions) {1824    // output handling1825    this._outputConfiguration.outputError(1826      `${message}\n`,1827      this._outputConfiguration.writeErr,1828    );1829    if (typeof this._showHelpAfterError === 'string') {1830      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1831    } else if (this._showHelpAfterError) {1832      this._outputConfiguration.writeErr('\n');1833      this.outputHelp({ error: true });1834    }18351836    // exit handling1837    const config = errorOptions || {};1838    const exitCode = config.exitCode || 1;1839    const code = config.code || 'commander.error';1840    this._exit(exitCode, code, message);1841  }18421843  /**1844   * Apply any option related environment variables, if option does1845   * not have a value from cli or client code.1846   *1847   * @private1848   */1849  _parseOptionsEnv() {1850    this.options.forEach((option) => {1851      if (option.envVar && option.envVar in process.env) {1852        const optionKey = option.attributeName();1853        // Priority check. Do not overwrite cli or options from unknown source (client-code).1854        if (1855          this.getOptionValue(optionKey) === undefined ||1856          ['default', 'config', 'env'].includes(1857            this.getOptionValueSource(optionKey),1858          )1859        ) {1860          if (option.required || option.optional) {1861            // option can take a value1862            // keep very simple, optional always takes value1863            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1864          } else {1865            // boolean1866            // keep very simple, only care that envVar defined and not the value1867            this.emit(`optionEnv:${option.name()}`);1868          }1869        }1870      }1871    });1872  }18731874  /**1875   * Apply any implied option values, if option is undefined or default value.1876   *1877   * @private1878   */1879  _parseOptionsImplied() {1880    const dualHelper = new DualOptions(this.options);1881    const hasCustomOptionValue = (optionKey) => {1882      return (1883        this.getOptionValue(optionKey) !== undefined &&1884        !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1885      );1886    };1887    this.options1888      .filter(1889        (option) =>1890          option.implied !== undefined &&1891          hasCustomOptionValue(option.attributeName()) &&1892          dualHelper.valueFromOption(1893            this.getOptionValue(option.attributeName()),1894            option,1895          ),1896      )1897      .forEach((option) => {1898        Object.keys(option.implied)1899          .filter((impliedKey) => !hasCustomOptionValue(impliedKey))1900          .forEach((impliedKey) => {1901            this.setOptionValueWithSource(1902              impliedKey,1903              option.implied[impliedKey],1904              'implied',1905            );1906          });1907      });1908  }19091910  /**1911   * Argument `name` is missing.1912   *1913   * @param {string} name1914   * @private1915   */19161917  missingArgument(name) {1918    const message = `error: missing required argument '${name}'`;1919    this.error(message, { code: 'commander.missingArgument' });1920  }19211922  /**1923   * `Option` is missing an argument.1924   *1925   * @param {Option} option1926   * @private1927   */19281929  optionMissingArgument(option) {1930    const message = `error: option '${option.flags}' argument missing`;1931    this.error(message, { code: 'commander.optionMissingArgument' });1932  }19331934  /**1935   * `Option` does not have a value, and is a mandatory option.1936   *1937   * @param {Option} option1938   * @private1939   */19401941  missingMandatoryOptionValue(option) {1942    const message = `error: required option '${option.flags}' not specified`;1943    this.error(message, { code: 'commander.missingMandatoryOptionValue' });1944  }19451946  /**1947   * `Option` conflicts with another option.1948   *1949   * @param {Option} option1950   * @param {Option} conflictingOption1951   * @private1952   */1953  _conflictingOption(option, conflictingOption) {1954    // The calling code does not know whether a negated option is the source of the1955    // value, so do some work to take an educated guess.1956    const findBestOptionFromValue = (option) => {1957      const optionKey = option.attributeName();1958      const optionValue = this.getOptionValue(optionKey);1959      const negativeOption = this.options.find(1960        (target) => target.negate && optionKey === target.attributeName(),1961      );1962      const positiveOption = this.options.find(1963        (target) => !target.negate && optionKey === target.attributeName(),1964      );1965      if (1966        negativeOption &&1967        ((negativeOption.presetArg === undefined && optionValue === false) ||1968          (negativeOption.presetArg !== undefined &&1969            optionValue === negativeOption.presetArg))1970      ) {1971        return negativeOption;1972      }1973      return positiveOption || option;1974    };19751976    const getErrorMessage = (option) => {1977      const bestOption = findBestOptionFromValue(option);1978      const optionKey = bestOption.attributeName();1979      const source = this.getOptionValueSource(optionKey);1980      if (source === 'env') {1981        return `environment variable '${bestOption.envVar}'`;1982      }1983      return `option '${bestOption.flags}'`;1984    };19851986    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1987    this.error(message, { code: 'commander.conflictingOption' });1988  }19891990  /**1991   * Unknown option `flag`.1992   *1993   * @param {string} flag1994   * @private1995   */19961997  unknownOption(flag) {1998    if (this._allowUnknownOption) return;1999    let suggestion = '';2000

The first 2,000 of 2,585 lines.