Skip to content
Myr

command.js

This file

Path

lib/command.js

2,098 lines · 66.0 KiB · JavaScript

Last changed by

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

History of this file

Take it

1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');5const process = require('process');67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, splitOptionFlags } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213// @ts-check1415class Command extends EventEmitter {16  /**17   * Initialize a new `Command`.18   *19   * @param {string} [name]20   */2122  constructor(name) {23    super();24    /** @type {Command[]} */25    this.commands = [];26    /** @type {Option[]} */27    this.options = [];28    this.parent = null;29    this._allowUnknownOption = false;30    this._allowExcessArguments = true;31    /** @type {Argument[]} */32    this._args = [];33    /** @type {string[]} */34    this.args = []; // cli args with options removed35    this.rawArgs = [];36    this.processedArgs = []; // like .args but after custom processing and collecting variadic37    this._scriptPath = null;38    this._name = name || '';39    this._optionValues = {};40    this._optionValueSources = {}; // default < config < env < cli41    this._storeOptionsAsProperties = false;42    this._actionHandler = null;43    this._executableHandler = false;44    this._executableFile = null; // custom name for executable45    this._executableDir = null; // custom search directory for subcommands46    this._defaultCommandName = null;47    this._exitCallback = null;48    this._aliases = [];49    this._combineFlagAndOptionalValue = true;50    this._description = '';51    this._argsDescription = undefined; // legacy52    this._enablePositionalOptions = false;53    this._passThroughOptions = false;54    this._lifeCycleHooks = {}; // a hash of arrays55    /** @type {boolean | string} */56    this._showHelpAfterError = false;57    this._showSuggestionAfterError = true;5859    // see .configureOutput() for docs60    this._outputConfiguration = {61      writeOut: (str) => process.stdout.write(str),62      writeErr: (str) => process.stderr.write(str),63      getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64      getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65      outputError: (str, write) => write(str)66    };6768    this._hidden = false;69    this._hasHelpOption = true;70    this._helpFlags = '-h, --help';71    this._helpDescription = 'display help for command';72    this._helpShortFlag = '-h';73    this._helpLongFlag = '--help';74    this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false75    this._helpCommandName = 'help';76    this._helpCommandnameAndArgs = 'help [command]';77    this._helpCommandDescription = 'display help for command';78    this._helpConfiguration = {};79  }8081  /**82   * Copy settings that are useful to have in common across root command and subcommands.83   *84   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)85   *86   * @param {Command} sourceCommand87   * @return {Command} `this` command for chaining88   */89  copyInheritedSettings(sourceCommand) {90    this._outputConfiguration = sourceCommand._outputConfiguration;91    this._hasHelpOption = sourceCommand._hasHelpOption;92    this._helpFlags = sourceCommand._helpFlags;93    this._helpDescription = sourceCommand._helpDescription;94    this._helpShortFlag = sourceCommand._helpShortFlag;95    this._helpLongFlag = sourceCommand._helpLongFlag;96    this._helpCommandName = sourceCommand._helpCommandName;97    this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;98    this._helpCommandDescription = sourceCommand._helpCommandDescription;99    this._helpConfiguration = sourceCommand._helpConfiguration;100    this._exitCallback = sourceCommand._exitCallback;101    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;102    this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;103    this._allowExcessArguments = sourceCommand._allowExcessArguments;104    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;105    this._showHelpAfterError = sourceCommand._showHelpAfterError;106    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;107108    return this;109  }110111  /**112   * Define a command.113   *114   * There are two styles of command: pay attention to where to put the description.115   *116   * @example117   * // Command implemented using action handler (description is supplied separately to `.command`)118   * program119   *   .command('clone <source> [destination]')120   *   .description('clone a repository into a newly created directory')121   *   .action((source, destination) => {122   *     console.log('clone command called');123   *   });124   *125   * // Command implemented using separate executable file (description is second parameter to `.command`)126   * program127   *   .command('start <service>', 'start named service')128   *   .command('stop [service]', 'stop named service, or all if no name supplied');129   *130   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`131   * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)132   * @param {Object} [execOpts] - configuration options (for executable)133   * @return {Command} returns new command for action handler, or `this` for executable command134   */135136  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {137    let desc = actionOptsOrExecDesc;138    let opts = execOpts;139    if (typeof desc === 'object' && desc !== null) {140      opts = desc;141      desc = null;142    }143    opts = opts || {};144    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);145146    const cmd = this.createCommand(name);147    if (desc) {148      cmd.description(desc);149      cmd._executableHandler = true;150    }151    if (opts.isDefault) this._defaultCommandName = cmd._name;152    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden153    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor154    if (args) cmd.arguments(args);155    this.commands.push(cmd);156    cmd.parent = this;157    cmd.copyInheritedSettings(this);158159    if (desc) return this;160    return cmd;161  }162163  /**164   * Factory routine to create a new unattached command.165   *166   * See .command() for creating an attached subcommand, which uses this routine to167   * create the command. You can override createCommand to customise subcommands.168   *169   * @param {string} [name]170   * @return {Command} new command171   */172173  createCommand(name) {174    return new Command(name);175  }176177  /**178   * You can customise the help with a subclass of Help by overriding createHelp,179   * or by overriding Help properties using configureHelp().180   *181   * @return {Help}182   */183184  createHelp() {185    return Object.assign(new Help(), this.configureHelp());186  }187188  /**189   * You can customise the help by overriding Help properties using configureHelp(),190   * or with a subclass of Help by overriding createHelp().191   *192   * @param {Object} [configuration] - configuration options193   * @return {Command|Object} `this` command for chaining, or stored configuration194   */195196  configureHelp(configuration) {197    if (configuration === undefined) return this._helpConfiguration;198199    this._helpConfiguration = configuration;200    return this;201  }202203  /**204   * The default output goes to stdout and stderr. You can customise this for special205   * applications. You can also customise the display of errors by overriding outputError.206   *207   * The configuration properties are all functions:208   *209   *     // functions to change where being written, stdout and stderr210   *     writeOut(str)211   *     writeErr(str)212   *     // matching functions to specify width for wrapping help213   *     getOutHelpWidth()214   *     getErrHelpWidth()215   *     // functions based on what is being written out216   *     outputError(str, write) // used for displaying errors, and not used for displaying help217   *218   * @param {Object} [configuration] - configuration options219   * @return {Command|Object} `this` command for chaining, or stored configuration220   */221222  configureOutput(configuration) {223    if (configuration === undefined) return this._outputConfiguration;224225    Object.assign(this._outputConfiguration, configuration);226    return this;227  }228229  /**230   * Display the help or a custom message after an error occurs.231   *232   * @param {boolean|string} [displayHelp]233   * @return {Command} `this` command for chaining234   */235  showHelpAfterError(displayHelp = true) {236    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;237    this._showHelpAfterError = displayHelp;238    return this;239  }240241  /**242   * Display suggestion of similar commands for unknown commands, or options for unknown options.243   *244   * @param {boolean} [displaySuggestion]245   * @return {Command} `this` command for chaining246   */247  showSuggestionAfterError(displaySuggestion = true) {248    this._showSuggestionAfterError = !!displaySuggestion;249    return this;250  }251252  /**253   * Add a prepared subcommand.254   *255   * See .command() for creating an attached subcommand which inherits settings from its parent.256   *257   * @param {Command} cmd - new subcommand258   * @param {Object} [opts] - configuration options259   * @return {Command} `this` command for chaining260   */261262  addCommand(cmd, opts) {263    if (!cmd._name) {264      throw new Error(`Command passed to .addCommand() must have a name265- specify the name in Command constructor or using .name()`);266    }267268    opts = opts || {};269    if (opts.isDefault) this._defaultCommandName = cmd._name;270    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation271272    this.commands.push(cmd);273    cmd.parent = this;274    return this;275  }276277  /**278   * Factory routine to create a new unattached argument.279   *280   * See .argument() for creating an attached argument, which uses this routine to281   * create the argument. You can override createArgument to return a custom argument.282   *283   * @param {string} name284   * @param {string} [description]285   * @return {Argument} new argument286   */287288  createArgument(name, description) {289    return new Argument(name, description);290  }291292  /**293   * Define argument syntax for command.294   *295   * The default is that the argument is required, and you can explicitly296   * indicate this with <> around the name. Put [] around the name for an optional argument.297   *298   * @example299   * program.argument('<input-file>');300   * program.argument('[output-file]');301   *302   * @param {string} name303   * @param {string} [description]304   * @param {Function|*} [fn] - custom argument processing function305   * @param {*} [defaultValue]306   * @return {Command} `this` command for chaining307   */308  argument(name, description, fn, defaultValue) {309    const argument = this.createArgument(name, description);310    if (typeof fn === 'function') {311      argument.default(defaultValue).argParser(fn);312    } else {313      argument.default(fn);314    }315    this.addArgument(argument);316    return this;317  }318319  /**320   * Define argument syntax for command, adding multiple at once (without descriptions).321   *322   * See also .argument().323   *324   * @example325   * program.arguments('<cmd> [env]');326   *327   * @param {string} names328   * @return {Command} `this` command for chaining329   */330331  arguments(names) {332    names.split(/ +/).forEach((detail) => {333      this.argument(detail);334    });335    return this;336  }337338  /**339   * Define argument syntax for command, adding a prepared argument.340   *341   * @param {Argument} argument342   * @return {Command} `this` command for chaining343   */344  addArgument(argument) {345    const previousArgument = this._args.slice(-1)[0];346    if (previousArgument && previousArgument.variadic) {347      throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);348    }349    if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {350      throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);351    }352    this._args.push(argument);353    return this;354  }355356  /**357   * Override default decision whether to add implicit help command.358   *359   *    addHelpCommand() // force on360   *    addHelpCommand(false); // force off361   *    addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details362   *363   * @return {Command} `this` command for chaining364   */365366  addHelpCommand(enableOrNameAndArgs, description) {367    if (enableOrNameAndArgs === false) {368      this._addImplicitHelpCommand = false;369    } else {370      this._addImplicitHelpCommand = true;371      if (typeof enableOrNameAndArgs === 'string') {372        this._helpCommandName = enableOrNameAndArgs.split(' ')[0];373        this._helpCommandnameAndArgs = enableOrNameAndArgs;374      }375      this._helpCommandDescription = description || this._helpCommandDescription;376    }377    return this;378  }379380  /**381   * @return {boolean}382   * @api private383   */384385  _hasImplicitHelpCommand() {386    if (this._addImplicitHelpCommand === undefined) {387      return this.commands.length && !this._actionHandler && !this._findCommand('help');388    }389    return this._addImplicitHelpCommand;390  }391392  /**393   * Add hook for life cycle event.394   *395   * @param {string} event396   * @param {Function} listener397   * @return {Command} `this` command for chaining398   */399400  hook(event, listener) {401    const allowedValues = ['preAction', 'postAction'];402    if (!allowedValues.includes(event)) {403      throw new Error(`Unexpected value for event passed to hook : '${event}'.404Expecting one of '${allowedValues.join("', '")}'`);405    }406    if (this._lifeCycleHooks[event]) {407      this._lifeCycleHooks[event].push(listener);408    } else {409      this._lifeCycleHooks[event] = [listener];410    }411    return this;412  }413414  /**415   * Register callback to use as replacement for calling process.exit.416   *417   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing418   * @return {Command} `this` command for chaining419   */420421  exitOverride(fn) {422    if (fn) {423      this._exitCallback = fn;424    } else {425      this._exitCallback = (err) => {426        if (err.code !== 'commander.executeSubCommandAsync') {427          throw err;428        } else {429          // Async callback from spawn events, not useful to throw.430        }431      };432    }433    return this;434  }435436  /**437   * Call process.exit, and _exitCallback if defined.438   *439   * @param {number} exitCode exit code for using with process.exit440   * @param {string} code an id string representing the error441   * @param {string} message human-readable description of the error442   * @return never443   * @api private444   */445446  _exit(exitCode, code, message) {447    if (this._exitCallback) {448      this._exitCallback(new CommanderError(exitCode, code, message));449      // Expecting this line is not reached.450    }451    process.exit(exitCode);452  }453454  /**455   * Register callback `fn` for the command.456   *457   * @example458   * program459   *   .command('serve')460   *   .description('start service')461   *   .action(function() {462   *      // do work here463   *   });464   *465   * @param {Function} fn466   * @return {Command} `this` command for chaining467   */468469  action(fn) {470    const listener = (args) => {471      // The .action callback takes an extra parameter which is the command or options.472      const expectedArgsCount = this._args.length;473      const actionArgs = args.slice(0, expectedArgsCount);474      if (this._storeOptionsAsProperties) {475        actionArgs[expectedArgsCount] = this; // backwards compatible "options"476      } else {477        actionArgs[expectedArgsCount] = this.opts();478      }479      actionArgs.push(this);480481      return fn.apply(this, actionArgs);482    };483    this._actionHandler = listener;484    return this;485  }486487  /**488   * Factory routine to create a new unattached option.489   *490   * See .option() for creating an attached option, which uses this routine to491   * create the option. You can override createOption to return a custom option.492   *493   * @param {string} flags494   * @param {string} [description]495   * @return {Option} new option496   */497498  createOption(flags, description) {499    return new Option(flags, description);500  }501502  /**503   * Add an option.504   *505   * @param {Option} option506   * @return {Command} `this` command for chaining507   */508  addOption(option) {509    const oname = option.name();510    const name = option.attributeName();511512    // store default value513    if (option.negate) {514      // --no-foo is special and defaults foo to true, unless a --foo option is already defined515      const positiveLongFlag = option.long.replace(/^--no-/, '--');516      if (!this._findOption(positiveLongFlag)) {517        this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');518      }519    } else if (option.defaultValue !== undefined) {520      this.setOptionValueWithSource(name, option.defaultValue, 'default');521    }522523    // register the option524    this.options.push(option);525526    // handler for cli and env supplied values527    const handleOptionValue = (val, invalidValueMessage, valueSource) => {528      // val is null for optional option used without an optional-argument.529      // val is undefined for boolean and negated option.530      if (val == null && option.presetArg !== undefined) {531        val = option.presetArg;532      }533534      // custom processing535      const oldValue = this.getOptionValue(name);536      if (val !== null && option.parseArg) {537        try {538          val = option.parseArg(val, oldValue);539        } catch (err) {540          if (err.code === 'commander.invalidArgument') {541            const message = `${invalidValueMessage} ${err.message}`;542            this.error(message, { exitCode: err.exitCode, code: err.code });543          }544          throw err;545        }546      } else if (val !== null && option.variadic) {547        val = option._concatValue(val, oldValue);548      }549550      // Fill-in appropriate missing values. Long winded but easy to follow.551      if (val == null) {552        if (option.negate) {553          val = false;554        } else if (option.isBoolean() || option.optional) {555          val = true;556        } else {557          val = ''; // not normal, parseArg might have failed or be a mock function for testing558        }559      }560      this.setOptionValueWithSource(name, val, valueSource);561    };562563    this.on('option:' + oname, (val) => {564      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;565      handleOptionValue(val, invalidValueMessage, 'cli');566    });567568    if (option.envVar) {569      this.on('optionEnv:' + oname, (val) => {570        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;571        handleOptionValue(val, invalidValueMessage, 'env');572      });573    }574575    return this;576  }577578  /**579   * Internal implementation shared by .option() and .requiredOption()580   *581   * @api private582   */583  _optionEx(config, flags, description, fn, defaultValue) {584    if (typeof flags === 'object' && flags instanceof Option) {585      throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');586    }587    const option = this.createOption(flags, description);588    option.makeOptionMandatory(!!config.mandatory);589    if (typeof fn === 'function') {590      option.default(defaultValue).argParser(fn);591    } else if (fn instanceof RegExp) {592      // deprecated593      const regex = fn;594      fn = (val, def) => {595        const m = regex.exec(val);596        return m ? m[0] : def;597      };598      option.default(defaultValue).argParser(fn);599    } else {600      option.default(fn);601    }602603    return this.addOption(option);604  }605606  /**607   * Define option with `flags`, `description` and optional608   * coercion `fn`.609   *610   * The `flags` string contains the short and/or long flags,611   * separated by comma, a pipe or space. The following are all valid612   * all will output this way when `--help` is used.613   *614   *     "-p, --pepper"615   *     "-p|--pepper"616   *     "-p --pepper"617   *618   * @example619   * // simple boolean defaulting to undefined620   * program.option('-p, --pepper', 'add pepper');621   *622   * program.pepper623   * // => undefined624   *625   * --pepper626   * program.pepper627   * // => true628   *629   * // simple boolean defaulting to true (unless non-negated option is also defined)630   * program.option('-C, --no-cheese', 'remove cheese');631   *632   * program.cheese633   * // => true634   *635   * --no-cheese636   * program.cheese637   * // => false638   *639   * // required argument640   * program.option('-C, --chdir <path>', 'change the working directory');641   *642   * --chdir /tmp643   * program.chdir644   * // => "/tmp"645   *646   * // optional argument647   * program.option('-c, --cheese [type]', 'add cheese [marble]');648   *649   * @param {string} flags650   * @param {string} [description]651   * @param {Function|*} [fn] - custom option processing function or default value652   * @param {*} [defaultValue]653   * @return {Command} `this` command for chaining654   */655656  option(flags, description, fn, defaultValue) {657    return this._optionEx({}, flags, description, fn, defaultValue);658  }659660  /**661  * Add a required option which must have a value after parsing. This usually means662  * the option must be specified on the command line. (Otherwise the same as .option().)663  *664  * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.665  *666  * @param {string} flags667  * @param {string} [description]668  * @param {Function|*} [fn] - custom option processing function or default value669  * @param {*} [defaultValue]670  * @return {Command} `this` command for chaining671  */672673  requiredOption(flags, description, fn, defaultValue) {674    return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);675  }676677  /**678   * Alter parsing of short flags with optional values.679   *680   * @example681   * // for `.option('-f,--flag [value]'):682   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour683   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`684   *685   * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.686   */687  combineFlagAndOptionalValue(combine = true) {688    this._combineFlagAndOptionalValue = !!combine;689    return this;690  }691692  /**693   * Allow unknown options on the command line.694   *695   * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown696   * for unknown options.697   */698  allowUnknownOption(allowUnknown = true) {699    this._allowUnknownOption = !!allowUnknown;700    return this;701  }702703  /**704   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.705   *706   * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown707   * for excess arguments.708   */709  allowExcessArguments(allowExcess = true) {710    this._allowExcessArguments = !!allowExcess;711    return this;712  }713714  /**715   * Enable positional options. Positional means global options are specified before subcommands which lets716   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.717   * The default behaviour is non-positional and global options may appear anywhere on the command line.718   *719   * @param {Boolean} [positional=true]720   */721  enablePositionalOptions(positional = true) {722    this._enablePositionalOptions = !!positional;723    return this;724  }725726  /**727   * Pass through options that come after command-arguments rather than treat them as command-options,728   * so actual command-options come before command-arguments. Turning this on for a subcommand requires729   * positional options to have been enabled on the program (parent commands).730   * The default behaviour is non-positional and options may appear before or after command-arguments.731   *732   * @param {Boolean} [passThrough=true]733   * for unknown options.734   */735  passThroughOptions(passThrough = true) {736    this._passThroughOptions = !!passThrough;737    if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {738      throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');739    }740    return this;741  }742743  /**744    * Whether to store option values as properties on command object,745    * or store separately (specify false). In both cases the option values can be accessed using .opts().746    *747    * @param {boolean} [storeAsProperties=true]748    * @return {Command} `this` command for chaining749    */750751  storeOptionsAsProperties(storeAsProperties = true) {752    this._storeOptionsAsProperties = !!storeAsProperties;753    if (this.options.length) {754      throw new Error('call .storeOptionsAsProperties() before adding options');755    }756    return this;757  }758759  /**760   * Retrieve option value.761   *762   * @param {string} key763   * @return {Object} value764   */765766  getOptionValue(key) {767    if (this._storeOptionsAsProperties) {768      return this[key];769    }770    return this._optionValues[key];771  }772773  /**774   * Store option value.775   *776   * @param {string} key777   * @param {Object} value778   * @return {Command} `this` command for chaining779   */780781  setOptionValue(key, value) {782    if (this._storeOptionsAsProperties) {783      this[key] = value;784    } else {785      this._optionValues[key] = value;786    }787    return this;788  }789790  /**791   * Store option value and where the value came from.792    *793    * @param {string} key794    * @param {Object} value795    * @param {string} source - expected values are default/config/env/cli796    * @return {Command} `this` command for chaining797    */798799  setOptionValueWithSource(key, value, source) {800    this.setOptionValue(key, value);801    this._optionValueSources[key] = source;802    return this;803  }804805  /**806    * Get source of option value.807    * Expected values are default | config | env | cli808    *809    * @param {string} key810    * @return {string}811    */812813  getOptionValueSource(key) {814    return this._optionValueSources[key];815  }816817  /**818   * Get user arguments from implied or explicit arguments.819   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.820   *821   * @api private822   */823824  _prepareUserArgs(argv, parseOptions) {825    if (argv !== undefined && !Array.isArray(argv)) {826      throw new Error('first parameter to parse must be array or undefined');827    }828    parseOptions = parseOptions || {};829830    // Default to using process.argv831    if (argv === undefined) {832      argv = process.argv;833      // @ts-ignore: unknown property834      if (process.versions && process.versions.electron) {835        parseOptions.from = 'electron';836      }837    }838    this.rawArgs = argv.slice();839840    // make it a little easier for callers by supporting various argv conventions841    let userArgs;842    switch (parseOptions.from) {843      case undefined:844      case 'node':845        this._scriptPath = argv[1];846        userArgs = argv.slice(2);847        break;848      case 'electron':849        // @ts-ignore: unknown property850        if (process.defaultApp) {851          this._scriptPath = argv[1];852          userArgs = argv.slice(2);853        } else {854          userArgs = argv.slice(1);855        }856        break;857      case 'user':858        userArgs = argv.slice(0);859        break;860      default:861        throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);862    }863864    // Find default name for program from arguments.865    if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);866    this._name = this._name || 'program';867868    return userArgs;869  }870871  /**872   * Parse `argv`, setting options and invoking commands when defined.873   *874   * The default expectation is that the arguments are from node and have the application as argv[0]875   * and the script being run in argv[1], with user parameters after that.876   *877   * @example878   * program.parse(process.argv);879   * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions880   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]881   *882   * @param {string[]} [argv] - optional, defaults to process.argv883   * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron884   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'885   * @return {Command} `this` command for chaining886   */887888  parse(argv, parseOptions) {889    const userArgs = this._prepareUserArgs(argv, parseOptions);890    this._parseCommand([], userArgs);891892    return this;893  }894895  /**896   * Parse `argv`, setting options and invoking commands when defined.897   *898   * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.899   *900   * The default expectation is that the arguments are from node and have the application as argv[0]901   * and the script being run in argv[1], with user parameters after that.902   *903   * @example904   * await program.parseAsync(process.argv);905   * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions906   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]907   *908   * @param {string[]} [argv]909   * @param {Object} [parseOptions]910   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'911   * @return {Promise}912   */913914  async parseAsync(argv, parseOptions) {915    const userArgs = this._prepareUserArgs(argv, parseOptions);916    await this._parseCommand([], userArgs);917918    return this;919  }920921  /**922   * Execute a sub-command executable.923   *924   * @api private925   */926927  _executeSubCommand(subcommand, args) {928    args = args.slice();929    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.930    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];931932    function findFile(baseDir, baseName) {933      // Look for specified file934      const localBin = path.resolve(baseDir, baseName);935      if (fs.existsSync(localBin)) return localBin;936937      // Stop looking if candidate already has an expected extension.938      if (sourceExt.includes(path.extname(baseName))) return undefined;939940      // Try all the extensions.941      const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));942      if (foundExt) return `${localBin}${foundExt}`;943944      return undefined;945    }946947    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.948    this._checkForMissingMandatoryOptions();949    this._checkForConflictingOptions();950951    // executableFile and executableDir might be full path, or just a name952    let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;953    let executableDir = this._executableDir || '';954    if (this._scriptPath) {955      let resolvedScriptPath; // resolve possible symlink for installed npm binary956      try {957        resolvedScriptPath = fs.realpathSync(this._scriptPath);958      } catch (err) {959        resolvedScriptPath = this._scriptPath;960      }961      executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);962    }963964    // Look for a local file in preference to a command in PATH.965    if (executableDir) {966      let localFile = findFile(executableDir, executableFile);967968      // Legacy search using prefix of script name instead of command name969      if (!localFile && !subcommand._executableFile && this._scriptPath) {970        const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));971        if (legacyName !== this._name) {972          localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);973        }974      }975      executableFile = localFile || executableFile;976    }977978    launchWithNode = sourceExt.includes(path.extname(executableFile));979980    let proc;981    if (process.platform !== 'win32') {982      if (launchWithNode) {983        args.unshift(executableFile);984        // add executable arguments to spawn985        args = incrementNodeInspectorPort(process.execArgv).concat(args);986987        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });988      } else {989        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });990      }991    } else {992      args.unshift(executableFile);993      // add executable arguments to spawn994      args = incrementNodeInspectorPort(process.execArgv).concat(args);995      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });996    }997998    if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn999      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1000      signals.forEach((signal) => {1001        // @ts-ignore1002        process.on(signal, () => {1003          if (proc.killed === false && proc.exitCode === null) {1004            proc.kill(signal);1005          }1006        });1007      });1008    }10091010    // By default terminate process when spawned process terminates.1011    // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1012    const exitCallback = this._exitCallback;1013    if (!exitCallback) {1014      proc.on('close', process.exit.bind(process));1015    } else {1016      proc.on('close', () => {1017        exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1018      });1019    }1020    proc.on('error', (err) => {1021      // @ts-ignore1022      if (err.code === 'ENOENT') {1023        const executableDirMessage = executableDir1024          ? `searched for local subcommand relative to directory '${executableDir}'`1025          : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1026        const executableMissing = `'${executableFile}' does not exist1027 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1028 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1029 - ${executableDirMessage}`;1030        throw new Error(executableMissing);1031      // @ts-ignore1032      } else if (err.code === 'EACCES') {1033        throw new Error(`'${executableFile}' not executable`);1034      }1035      if (!exitCallback) {1036        process.exit(1);1037      } else {1038        const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1039        wrappedError.nestedError = err;1040        exitCallback(wrappedError);1041      }1042    });10431044    // Store the reference to the child process1045    this.runningCommand = proc;1046  }10471048  /**1049   * @api private1050   */10511052  _dispatchSubcommand(commandName, operands, unknown) {1053    const subCommand = this._findCommand(commandName);1054    if (!subCommand) this.help({ error: true });10551056    if (subCommand._executableHandler) {1057      this._executeSubCommand(subCommand, operands.concat(unknown));1058    } else {1059      return subCommand._parseCommand(operands, unknown);1060    }1061  }10621063  /**1064   * Check this.args against expected this._args.1065   *1066   * @api private1067   */10681069  _checkNumberOfArguments() {1070    // too few1071    this._args.forEach((arg, i) => {1072      if (arg.required && this.args[i] == null) {1073        this.missingArgument(arg.name());1074      }1075    });1076    // too many1077    if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1078      return;1079    }1080    if (this.args.length > this._args.length) {1081      this._excessArguments(this.args);1082    }1083  }10841085  /**1086   * Process this.args using this._args and save as this.processedArgs!1087   *1088   * @api private1089   */10901091  _processArguments() {1092    const myParseArg = (argument, value, previous) => {1093      // Extra processing for nice error message on parsing failure.1094      let parsedValue = value;1095      if (value !== null && argument.parseArg) {1096        try {1097          parsedValue = argument.parseArg(value, previous);1098        } catch (err) {1099          if (err.code === 'commander.invalidArgument') {1100            const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1101            this.error(message, { exitCode: err.exitCode, code: err.code });1102          }1103          throw err;1104        }1105      }1106      return parsedValue;1107    };11081109    this._checkNumberOfArguments();11101111    const processedArgs = [];1112    this._args.forEach((declaredArg, index) => {1113      let value = declaredArg.defaultValue;1114      if (declaredArg.variadic) {1115        // Collect together remaining arguments for passing together as an array.1116        if (index < this.args.length) {1117          value = this.args.slice(index);1118          if (declaredArg.parseArg) {1119            value = value.reduce((processed, v) => {1120              return myParseArg(declaredArg, v, processed);1121            }, declaredArg.defaultValue);1122          }1123        } else if (value === undefined) {1124          value = [];1125        }1126      } else if (index < this.args.length) {1127        value = this.args[index];1128        if (declaredArg.parseArg) {1129          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1130        }1131      }1132      processedArgs[index] = value;1133    });1134    this.processedArgs = processedArgs;1135  }11361137  /**1138   * Once we have a promise we chain, but call synchronously until then.1139   *1140   * @param {Promise|undefined} promise1141   * @param {Function} fn1142   * @return {Promise|undefined}1143   * @api private1144   */11451146  _chainOrCall(promise, fn) {1147    // thenable1148    if (promise && promise.then && typeof promise.then === 'function') {1149      // already have a promise, chain callback1150      return promise.then(() => fn());1151    }1152    // callback might return a promise1153    return fn();1154  }11551156  /**1157   *1158   * @param {Promise|undefined} promise1159   * @param {string} event1160   * @return {Promise|undefined}1161   * @api private1162   */11631164  _chainOrCallHooks(promise, event) {1165    let result = promise;1166    const hooks = [];1167    getCommandAndParents(this)1168      .reverse()1169      .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1170      .forEach(hookedCommand => {1171        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1172          hooks.push({ hookedCommand, callback });1173        });1174      });1175    if (event === 'postAction') {1176      hooks.reverse();1177    }11781179    hooks.forEach((hookDetail) => {1180      result = this._chainOrCall(result, () => {1181        return hookDetail.callback(hookDetail.hookedCommand, this);1182      });1183    });1184    return result;1185  }11861187  /**1188   * Process arguments in context of this command.1189   * Returns action result, in case it is a promise.1190   *1191   * @api private1192   */11931194  _parseCommand(operands, unknown) {1195    const parsed = this.parseOptions(unknown);1196    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1197    operands = operands.concat(parsed.operands);1198    unknown = parsed.unknown;1199    this.args = operands.concat(unknown);12001201    if (operands && this._findCommand(operands[0])) {1202      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1203    }1204    if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1205      if (operands.length === 1) {1206        this.help();1207      }1208      return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1209    }1210    if (this._defaultCommandName) {1211      outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1212      return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1213    }1214    if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1215      // probably missing subcommand and no handler, user needs help (and exit)1216      this.help({ error: true });1217    }12181219    outputHelpIfRequested(this, parsed.unknown);1220    this._checkForMissingMandatoryOptions();1221    this._checkForConflictingOptions();12221223    // We do not always call this check to avoid masking a "better" error, like unknown command.1224    const checkForUnknownOptions = () => {1225      if (parsed.unknown.length > 0) {1226        this.unknownOption(parsed.unknown[0]);1227      }1228    };12291230    const commandEvent = `command:${this.name()}`;1231    if (this._actionHandler) {1232      checkForUnknownOptions();1233      this._processArguments();12341235      let actionResult;1236      actionResult = this._chainOrCallHooks(actionResult, 'preAction');1237      actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));1238      if (this.parent) {1239        actionResult = this._chainOrCall(actionResult, () => {1240          this.parent.emit(commandEvent, operands, unknown); // legacy1241        });1242      }1243      actionResult = this._chainOrCallHooks(actionResult, 'postAction');1244      return actionResult;1245    }1246    if (this.parent && this.parent.listenerCount(commandEvent)) {1247      checkForUnknownOptions();1248      this._processArguments();1249      this.parent.emit(commandEvent, operands, unknown); // legacy1250    } else if (operands.length) {1251      if (this._findCommand('*')) { // legacy default command1252        return this._dispatchSubcommand('*', operands, unknown);1253      }1254      if (this.listenerCount('command:*')) {1255        // skip option check, emit event for possible misspelling suggestion1256        this.emit('command:*', operands, unknown);1257      } else if (this.commands.length) {1258        this.unknownCommand();1259      } else {1260        checkForUnknownOptions();1261        this._processArguments();1262      }1263    } else if (this.commands.length) {1264      checkForUnknownOptions();1265      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1266      this.help({ error: true });1267    } else {1268      checkForUnknownOptions();1269      this._processArguments();1270      // fall through for caller to handle after calling .parse()1271    }1272  }12731274  /**1275   * Find matching command.1276   *1277   * @api private1278   */1279  _findCommand(name) {1280    if (!name) return undefined;1281    return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1282  }12831284  /**1285   * Return an option matching `arg` if any.1286   *1287   * @param {string} arg1288   * @return {Option}1289   * @api private1290   */12911292  _findOption(arg) {1293    return this.options.find(option => option.is(arg));1294  }12951296  /**1297   * Display an error message if a mandatory option does not have a value.1298   * Called after checking for help flags in leaf subcommand.1299   *1300   * @api private1301   */13021303  _checkForMissingMandatoryOptions() {1304    // Walk up hierarchy so can call in subcommand after checking for displaying help.1305    for (let cmd = this; cmd; cmd = cmd.parent) {1306      cmd.options.forEach((anOption) => {1307        if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1308          cmd.missingMandatoryOptionValue(anOption);1309        }1310      });1311    }1312  }13131314  /**1315   * Display an error message if conflicting options are used together in this.1316   *1317   * @api private1318   */1319  _checkForConflictingLocalOptions() {1320    const definedNonDefaultOptions = this.options.filter(1321      (option) => {1322        const optionKey = option.attributeName();1323        if (this.getOptionValue(optionKey) === undefined) {1324          return false;1325        }1326        return this.getOptionValueSource(optionKey) !== 'default';1327      }1328    );13291330    const optionsWithConflicting = definedNonDefaultOptions.filter(1331      (option) => option.conflictsWith.length > 01332    );13331334    optionsWithConflicting.forEach((option) => {1335      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1336        option.conflictsWith.includes(defined.attributeName())1337      );1338      if (conflictingAndDefined) {1339        this._conflictingOption(option, conflictingAndDefined);1340      }1341    });1342  }13431344  /**1345   * Display an error message if conflicting options are used together.1346   * Called after checking for help flags in leaf subcommand.1347   *1348   * @api private1349   */1350  _checkForConflictingOptions() {1351    // Walk up hierarchy so can call in subcommand after checking for displaying help.1352    for (let cmd = this; cmd; cmd = cmd.parent) {1353      cmd._checkForConflictingLocalOptions();1354    }1355  }13561357  /**1358   * Parse options from `argv` removing known options,1359   * and return argv split into operands and unknown arguments.1360   *1361   * Examples:1362   *1363   *     argv => operands, unknown1364   *     --known kkk op => [op], []1365   *     op --known kkk => [op], []1366   *     sub --unknown uuu op => [sub], [--unknown uuu op]1367   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1368   *1369   * @param {String[]} argv1370   * @return {{operands: String[], unknown: String[]}}1371   */13721373  parseOptions(argv) {1374    const operands = []; // operands, not options or values1375    const unknown = []; // first unknown option and remaining unknown args1376    let dest = operands;1377    const args = argv.slice();13781379    function maybeOption(arg) {1380      return arg.length > 1 && arg[0] === '-';1381    }13821383    // parse options1384    let activeVariadicOption = null;1385    while (args.length) {1386      const arg = args.shift();13871388      // literal1389      if (arg === '--') {1390        if (dest === unknown) dest.push(arg);1391        dest.push(...args);1392        break;1393      }13941395      if (activeVariadicOption && !maybeOption(arg)) {1396        this.emit(`option:${activeVariadicOption.name()}`, arg);1397        continue;1398      }1399      activeVariadicOption = null;14001401      if (maybeOption(arg)) {1402        const option = this._findOption(arg);1403        // recognised option, call listener to assign value with possible custom processing1404        if (option) {1405          if (option.required) {1406            const value = args.shift();1407            if (value === undefined) this.optionMissingArgument(option);1408            this.emit(`option:${option.name()}`, value);1409          } else if (option.optional) {1410            let value = null;1411            // historical behaviour is optional value is following arg unless an option1412            if (args.length > 0 && !maybeOption(args[0])) {1413              value = args.shift();1414            }1415            this.emit(`option:${option.name()}`, value);1416          } else { // boolean flag1417            this.emit(`option:${option.name()}`);1418          }1419          activeVariadicOption = option.variadic ? option : null;1420          continue;1421        }1422      }14231424      // Look for combo options following single dash, eat first one if known.1425      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1426        const option = this._findOption(`-${arg[1]}`);1427        if (option) {1428          if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1429            // option with value following in same argument1430            this.emit(`option:${option.name()}`, arg.slice(2));1431          } else {1432            // boolean option, emit and put back remainder of arg for further processing1433            this.emit(`option:${option.name()}`);1434            args.unshift(`-${arg.slice(2)}`);1435          }1436          continue;1437        }1438      }14391440      // Look for known long flag with value, like --foo=bar1441      if (/^--[^=]+=/.test(arg)) {1442        const index = arg.indexOf('=');1443        const option = this._findOption(arg.slice(0, index));1444        if (option && (option.required || option.optional)) {1445          this.emit(`option:${option.name()}`, arg.slice(index + 1));1446          continue;1447        }1448      }14491450      // Not a recognised option by this command.1451      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14521453      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1454      if (maybeOption(arg)) {1455        dest = unknown;1456      }14571458      // If using positionalOptions, stop processing our options at subcommand.1459      if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1460        if (this._findCommand(arg)) {1461          operands.push(arg);1462          if (args.length > 0) unknown.push(...args);1463          break;1464        } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1465          operands.push(arg);1466          if (args.length > 0) operands.push(...args);1467          break;1468        } else if (this._defaultCommandName) {1469          unknown.push(arg);1470          if (args.length > 0) unknown.push(...args);1471          break;1472        }1473      }14741475      // If using passThroughOptions, stop processing options at first command-argument.1476      if (this._passThroughOptions) {1477        dest.push(arg);1478        if (args.length > 0) dest.push(...args);1479        break;1480      }14811482      // add arg1483      dest.push(arg);1484    }14851486    return { operands, unknown };1487  }14881489  /**1490   * Return an object containing local option values as key-value pairs.1491   *1492   * @return {Object}1493   */1494  opts() {1495    if (this._storeOptionsAsProperties) {1496      // Preserve original behaviour so backwards compatible when still using properties1497      const result = {};1498      const len = this.options.length;14991500      for (let i = 0; i < len; i++) {1501        const key = this.options[i].attributeName();1502        result[key] = key === this._versionOptionName ? this._version : this[key];1503      }1504      return result;1505    }15061507    return this._optionValues;1508  }15091510  /**1511   * Return an object containing merged local and global option values as key-value pairs.1512   *1513   * @return {Object}1514   */1515  optsWithGlobals() {1516    // globals overwrite locals1517    return getCommandAndParents(this).reduce(1518      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1519      {}1520    );1521  }15221523  /**1524   * Display error message and exit (or call exitOverride).1525   *1526   * @param {string} message1527   * @param {Object} [errorOptions]1528   * @param {string} [errorOptions.code] - an id string representing the error1529   * @param {number} [errorOptions.exitCode] - used with process.exit1530   */1531  error(message, errorOptions) {1532    // output handling1533    this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1534    if (typeof this._showHelpAfterError === 'string') {1535      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1536    } else if (this._showHelpAfterError) {1537      this._outputConfiguration.writeErr('\n');1538      this.outputHelp({ error: true });1539    }15401541    // exit handling1542    const config = errorOptions || {};1543    const exitCode = config.exitCode || 1;1544    const code = config.code || 'commander.error';1545    this._exit(exitCode, code, message);1546  }15471548  /**1549   * Apply any option related environment variables, if option does1550   * not have a value from cli or client code.1551   *1552   * @api private1553   */1554  _parseOptionsEnv() {1555    this.options.forEach((option) => {1556      if (option.envVar && option.envVar in process.env) {1557        const optionKey = option.attributeName();1558        // Priority check. Do not overwrite cli or options from unknown source (client-code).1559        if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1560          if (option.required || option.optional) { // option can take a value1561            // keep very simple, optional always takes value1562            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1563          } else { // boolean1564            // keep very simple, only care that envVar defined and not the value1565            this.emit(`optionEnv:${option.name()}`);1566          }1567        }1568      }1569    });1570  }15711572  /**1573   * Argument `name` is missing.1574   *1575   * @param {string} name1576   * @api private1577   */15781579  missingArgument(name) {1580    const message = `error: missing required argument '${name}'`;1581    this.error(message, { code: 'commander.missingArgument' });1582  }15831584  /**1585   * `Option` is missing an argument.1586   *1587   * @param {Option} option1588   * @api private1589   */15901591  optionMissingArgument(option) {1592    const message = `error: option '${option.flags}' argument missing`;1593    this.error(message, { code: 'commander.optionMissingArgument' });1594  }15951596  /**1597   * `Option` does not have a value, and is a mandatory option.1598   *1599   * @param {Option} option1600   * @api private1601   */16021603  missingMandatoryOptionValue(option) {1604    const message = `error: required option '${option.flags}' not specified`;1605    this.error(message, { code: 'commander.missingMandatoryOptionValue' });1606  }16071608  /**1609   * `Option` conflicts with another option.1610   *1611   * @param {Option} option1612   * @param {Option} conflictingOption1613   * @api private1614   */1615  _conflictingOption(option, conflictingOption) {1616    // The calling code does not know whether a negated option is the source of the1617    // value, so do some work to take an educated guess.1618    const findBestOptionFromValue = (option) => {1619      const optionKey = option.attributeName();1620      const optionValue = this.getOptionValue(optionKey);1621      const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1622      const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1623      if (negativeOption && (1624        (negativeOption.presetArg === undefined && optionValue === false) ||1625        (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1626      )) {1627        return negativeOption;1628      }1629      return positiveOption || option;1630    };16311632    const getErrorMessage = (option) => {1633      const bestOption = findBestOptionFromValue(option);1634      const optionKey = bestOption.attributeName();1635      const source = this.getOptionValueSource(optionKey);1636      if (source === 'env') {1637        return `environment variable '${bestOption.envVar}'`;1638      }1639      return `option '${bestOption.flags}'`;1640    };16411642    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1643    this.error(message, { code: 'commander.conflictingOption' });1644  }16451646  /**1647   * Unknown option `flag`.1648   *1649   * @param {string} flag1650   * @api private1651   */16521653  unknownOption(flag) {1654    if (this._allowUnknownOption) return;1655    let suggestion = '';16561657    if (flag.startsWith('--') && this._showSuggestionAfterError) {1658      // Looping to pick up the global options too1659      let candidateFlags = [];1660      let command = this;1661      do {1662        const moreFlags = command.createHelp().visibleOptions(command)1663          .filter(option => option.long)1664          .map(option => option.long);1665        candidateFlags = candidateFlags.concat(moreFlags);1666        command = command.parent;1667      } while (command && !command._enablePositionalOptions);1668      suggestion = suggestSimilar(flag, candidateFlags);1669    }16701671    const message = `error: unknown option '${flag}'${suggestion}`;1672    this.error(message, { code: 'commander.unknownOption' });1673  }16741675  /**1676   * Excess arguments, more than expected.1677   *1678   * @param {string[]} receivedArgs1679   * @api private1680   */16811682  _excessArguments(receivedArgs) {1683    if (this._allowExcessArguments) return;16841685    const expected = this._args.length;1686    const s = (expected === 1) ? '' : 's';1687    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1688    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1689    this.error(message, { code: 'commander.excessArguments' });1690  }16911692  /**1693   * Unknown command.1694   *1695   * @api private1696   */16971698  unknownCommand() {1699    const unknownName = this.args[0];1700    let suggestion = '';17011702    if (this._showSuggestionAfterError) {1703      const candidateNames = [];1704      this.createHelp().visibleCommands(this).forEach((command) => {1705        candidateNames.push(command.name());1706        // just visible alias1707        if (command.alias()) candidateNames.push(command.alias());1708      });1709      suggestion = suggestSimilar(unknownName, candidateNames);1710    }17111712    const message = `error: unknown command '${unknownName}'${suggestion}`;1713    this.error(message, { code: 'commander.unknownCommand' });1714  }17151716  /**1717   * Set the program version to `str`.1718   *1719   * This method auto-registers the "-V, --version" flag1720   * which will print the version number when passed.1721   *1722   * You can optionally supply the  flags and description to override the defaults.1723   *1724   * @param {string} str1725   * @param {string} [flags]1726   * @param {string} [description]1727   * @return {this | string} `this` command for chaining, or version string if no arguments1728   */17291730  version(str, flags, description) {1731    if (str === undefined) return this._version;1732    this._version = str;1733    flags = flags || '-V, --version';1734    description = description || 'output the version number';1735    const versionOption = this.createOption(flags, description);1736    this._versionOptionName = versionOption.attributeName();1737    this.options.push(versionOption);1738    this.on('option:' + versionOption.name(), () => {1739      this._outputConfiguration.writeOut(`${str}\n`);1740      this._exit(0, 'commander.version', str);1741    });1742    return this;1743  }17441745  /**1746   * Set the description to `str`.1747   *1748   * @param {string} [str]1749   * @param {Object} [argsDescription]1750   * @return {string|Command}1751   */1752  description(str, argsDescription) {1753    if (str === undefined && argsDescription === undefined) return this._description;1754    this._description = str;1755    if (argsDescription) {1756      this._argsDescription = argsDescription;1757    }1758    return this;1759  }17601761  /**1762   * Set an alias for the command.1763   *1764   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1765   *1766   * @param {string} [alias]1767   * @return {string|Command}1768   */17691770  alias(alias) {1771    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility17721773    /** @type {Command} */1774    let command = this;1775    if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1776      // assume adding alias for last added executable subcommand, rather than this1777      command = this.commands[this.commands.length - 1];1778    }17791780    if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');17811782    command._aliases.push(alias);1783    return this;1784  }17851786  /**1787   * Set aliases for the command.1788   *1789   * Only the first alias is shown in the auto-generated help.1790   *1791   * @param {string[]} [aliases]1792   * @return {string[]|Command}1793   */17941795  aliases(aliases) {1796    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1797    if (aliases === undefined) return this._aliases;17981799    aliases.forEach((alias) => this.alias(alias));1800    return this;1801  }18021803  /**1804   * Set / get the command usage `str`.1805   *1806   * @param {string} [str]1807   * @return {String|Command}1808   */18091810  usage(str) {1811    if (str === undefined) {1812      if (this._usage) return this._usage;18131814      const args = this._args.map((arg) => {1815        return humanReadableArgName(arg);1816      });1817      return [].concat(1818        (this.options.length || this._hasHelpOption ? '[options]' : []),1819        (this.commands.length ? '[command]' : []),1820        (this._args.length ? args : [])1821      ).join(' ');1822    }18231824    this._usage = str;1825    return this;1826  }18271828  /**1829   * Get or set the name of the command.1830   *1831   * @param {string} [str]1832   * @return {string|Command}1833   */18341835  name(str) {1836    if (str === undefined) return this._name;1837    this._name = str;1838    return this;1839  }18401841  /**1842   * Set the name of the command from script filename, such as process.argv[1],1843   * or require.main.filename, or __filename.1844   *1845   * (Used internally and public although not documented in README.)1846   *1847   * @example1848   * program.nameFromFilename(require.main.filename);1849   *1850   * @param {string} filename1851   * @return {Command}1852   */18531854  nameFromFilename(filename) {1855    this._name = path.basename(filename, path.extname(filename));18561857    return this;1858  }18591860  /**1861   * Get or set the directory for searching for executable subcommands of this command.1862   *1863   * @example1864   * program.executableDir(__dirname);1865   * // or1866   * program.executableDir('subcommands');1867   *1868   * @param {string} [path]1869   * @return {string|Command}1870   */18711872  executableDir(path) {1873    if (path === undefined) return this._executableDir;1874    this._executableDir = path;1875    return this;1876  }18771878  /**1879   * Return program help documentation.1880   *1881   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1882   * @return {string}1883   */18841885  helpInformation(contextOptions) {1886    const helper = this.createHelp();1887    if (helper.helpWidth === undefined) {1888      helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1889    }1890    return helper.formatHelp(this, helper);1891  }18921893  /**1894   * @api private1895   */18961897  _getHelpContext(contextOptions) {1898    contextOptions = contextOptions || {};1899    const context = { error: !!contextOptions.error };1900    let write;1901    if (context.error) {1902      write = (arg) => this._outputConfiguration.writeErr(arg);1903    } else {1904      write = (arg) => this._outputConfiguration.writeOut(arg);1905    }1906    context.write = contextOptions.write || write;1907    context.command = this;1908    return context;1909  }19101911  /**1912   * Output help information for this command.1913   *1914   * Outputs built-in help, and custom text added using `.addHelpText()`.1915   *1916   * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1917   */19181919  outputHelp(contextOptions) {1920    let deprecatedCallback;1921    if (typeof contextOptions === 'function') {1922      deprecatedCallback = contextOptions;1923      contextOptions = undefined;1924    }1925    const context = this._getHelpContext(contextOptions);19261927    getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));1928    this.emit('beforeHelp', context);19291930    let helpInformation = this.helpInformation(context);1931    if (deprecatedCallback) {1932      helpInformation = deprecatedCallback(helpInformation);1933      if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1934        throw new Error('outputHelp callback must return a string or a Buffer');1935      }1936    }1937    context.write(helpInformation);19381939    this.emit(this._helpLongFlag); // deprecated1940    this.emit('afterHelp', context);1941    getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));1942  }19431944  /**1945   * You can pass in flags and a description to override the help1946   * flags and help description for your command. Pass in false to1947   * disable the built-in help option.1948   *1949   * @param {string | boolean} [flags]1950   * @param {string} [description]1951   * @return {Command} `this` command for chaining1952   */19531954  helpOption(flags, description) {1955    if (typeof flags === 'boolean') {1956      this._hasHelpOption = flags;1957      return this;1958    }1959    this._helpFlags = flags || this._helpFlags;1960    this._helpDescription = description || this._helpDescription;19611962    const helpFlags = splitOptionFlags(this._helpFlags);1963    this._helpShortFlag = helpFlags.shortFlag;1964    this._helpLongFlag = helpFlags.longFlag;19651966    return this;1967  }19681969  /**1970   * Output help information and exit.1971   *1972   * Outputs built-in help, and custom text added using `.addHelpText()`.1973   *1974   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1975   */19761977  help(contextOptions) {1978    this.outputHelp(contextOptions);1979    let exitCode = process.exitCode || 0;1980    if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1981      exitCode = 1;1982    }1983    // message: do not have all displayed text available so only passing placeholder.1984    this._exit(exitCode, 'commander.help', '(outputHelp)');1985  }19861987  /**1988   * Add additional text to be displayed with the built-in help.1989   *1990   * Position is 'before' or 'after' to affect just this command,1991   * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1992   *1993   * @param {string} position - before or after built-in help1994   * @param {string | Function} text - string to add, or a function returning a string1995   * @return {Command} `this` command for chaining1996   */1997  addHelpText(position, text) {1998    const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1999    if (!allowedValues.includes(position)) {2000      throw new Error(`Unexpected value for position to addHelpText.

The first 2,000 of 2,098 lines.