command.js
This file
Path
lib/command.js
2,792 lines · 85.7 KiB · JavaScript
Last changed by
Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
History of this fileTake it
The walk stopped after 200 commits: lines older than acbbe18 point at it.
Fix: Use `node`-prefixed requires for builtins (#2170)Sam Gammonbefore adoptionf7b8475
lines 1–5why, one step back1const 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');Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 6–8why, one step back67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 9why, one step back9const { Help, stripColor } = require('./help.js');Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 10why, one step back10const { Option, DualOptions } = require('./option.js');Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 11–27why, one step back11const { 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;Disallow excess arguments (#2223)John Geebefore adoption58c28eb
line 28why, one step back28 this._allowExcessArguments = false;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 29why, one step back29 /** @type {Argument[]} */Add public Arguments property (#2010)John Geebefore adoption7d23437
lines 30–31why, one step back30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old nameDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 32–38why, one step back32 /** @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 = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 39why, one step back39 this._optionValueSources = {}; // default, env, cli etcDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 40–49why, one step back40 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 = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 50why, one step back50 this._summary = '';Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 51–54why, one step back51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arraysMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 55why, one step back55 /** @type {(boolean | string)} */Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 56–57why, one step back56 this._showHelpAfterError = false;57 this._showSuggestionAfterError = true;Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 58why, one step back58 this._savedState = null; // used in save/restoreStateBeforeParseDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 59why, one step back59Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 60why, one step back60 // see configureOutput() for docsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 61–63why, one step back61 this._outputConfiguration = {62 writeOut: (str) => process.stdout.write(str),63 writeErr: (str) => process.stderr.write(str),Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 64why, one step back64 outputError: (str, write) => write(str),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 65–68why, one step back65 getOutHelpWidth: () =>66 process.stdout.isTTY ? process.stdout.columns : undefined,67 getErrHelpWidth: () =>68 process.stderr.isTTY ? process.stderr.columns : undefined,Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 69–73why, one step back69 getOutHasColors: () =>70 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),71 getErrHasColors: () =>72 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),73 stripColor: (str) => stripColor(str),Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 74–76why, one step back74 };7576 this._hidden = false;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 77–81why, one step back77 /** @type {(Option | null | undefined)} */78 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.79 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80 /** @type {Command} */81 this._helpCommand = undefined; // lazy initialised, inheritedDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 82why, one step back82 this._helpConfiguration = {};Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 83–88why, one step back83 /** @type {string | undefined} */84 this._helpGroupHeading = undefined; // soft initialised when added to parent85 /** @type {string | undefined} */86 this._defaultCommandGroup = undefined;87 /** @type {string | undefined} */88 this._defaultOptionGroup = undefined;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 89–100why, one step back89 }9091 /**92 * Copy settings that are useful to have in common across root command and subcommands.93 *94 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)95 *96 * @param {Command} sourceCommand97 * @return {Command} `this` command for chaining98 */99 copyInheritedSettings(sourceCommand) {100 this._outputConfiguration = sourceCommand._outputConfiguration;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 101–102why, one step back101 this._helpOption = sourceCommand._helpOption;102 this._helpCommand = sourceCommand._helpCommand;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 103–105why, one step back103 this._helpConfiguration = sourceCommand._helpConfiguration;104 this._exitCallback = sourceCommand._exitCallback;105 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 106–107why, one step back106 this._combineFlagAndOptionalValue =107 sourceCommand._combineFlagAndOptionalValue;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 108–116why, one step back108 this._allowExcessArguments = sourceCommand._allowExcessArguments;109 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;110 this._showHelpAfterError = sourceCommand._showHelpAfterError;111 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;112113 return this;114 }115116 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 117why, one step back117 * @returns {Command[]}Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 118why, one step back118 * @privateIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 119–122why, one step back119 */120121 _getCommandAndAncestors() {122 const result = [];ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 123why, one step back123 // eslint-disable-next-line @typescript-eslint/no-this-aliasIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 124–130why, one step back124 for (let command = this; command; command = command.parent) {125 result.push(command);126 }127 return result;128 }129130 /**Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 131–149why, one step back131 * Define a command.132 *133 * There are two styles of command: pay attention to where to put the description.134 *135 * @example136 * // Command implemented using action handler (description is supplied separately to `.command`)137 * program138 * .command('clone <source> [destination]')139 * .description('clone a repository into a newly created directory')140 * .action((source, destination) => {141 * console.log('clone command called');142 * });143 *144 * // Command implemented using separate executable file (description is second parameter to `.command`)145 * program146 * .command('start <service>', 'start named service')147 * .command('stop [service]', 'stop named service, or all if no name supplied');148 *149 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 150–151why, one step back150 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)151 * @param {object} [execOpts] - configuration options (for executable)Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 152–173why, one step back152 * @return {Command} returns new command for action handler, or `this` for executable command153 */154155 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {156 let desc = actionOptsOrExecDesc;157 let opts = execOpts;158 if (typeof desc === 'object' && desc !== null) {159 opts = desc;160 desc = null;161 }162 opts = opts || {};163 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);164165 const cmd = this.createCommand(name);166 if (desc) {167 cmd.description(desc);168 cmd._executableHandler = true;169 }170 if (opts.isDefault) this._defaultCommandName = cmd._name;171 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden172 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor173 if (args) cmd.arguments(args);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 174why, one step back174 this._registerCommand(cmd);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 175–210why, one step back175 cmd.parent = this;176 cmd.copyInheritedSettings(this);177178 if (desc) return this;179 return cmd;180 }181182 /**183 * Factory routine to create a new unattached command.184 *185 * See .command() for creating an attached subcommand, which uses this routine to186 * create the command. You can override createCommand to customise subcommands.187 *188 * @param {string} [name]189 * @return {Command} new command190 */191192 createCommand(name) {193 return new Command(name);194 }195196 /**197 * You can customise the help with a subclass of Help by overriding createHelp,198 * or by overriding Help properties using configureHelp().199 *200 * @return {Help}201 */202203 createHelp() {204 return Object.assign(new Help(), this.configureHelp());205 }206207 /**208 * You can customise the help by overriding Help properties using configureHelp(),209 * or with a subclass of Help by overriding createHelp().210 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 211–212why, one step back211 * @param {object} [configuration] - configuration options212 * @return {(Command | object)} `this` command for chaining, or stored configurationDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 213–227why, one step back213 */214215 configureHelp(configuration) {216 if (configuration === undefined) return this._helpConfiguration;217218 this._helpConfiguration = configuration;219 return this;220 }221222 /**223 * The default output goes to stdout and stderr. You can customise this for special224 * applications. You can also customise the display of errors by overriding outputError.225 *226 * The configuration properties are all functions:227 *Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 228why, one step back228 * // change how output being written, defaults to stdout and stderrDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 229–230why, one step back229 * writeOut(str)230 * writeErr(str)Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 231–233why, one step back231 * // change how output being written for errors, defaults to writeErr232 * outputError(str, write) // used for displaying errors and not used for displaying help233 * // specify width for wrapping helpDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 234–235why, one step back234 * getOutHelpWidth()235 * getErrHelpWidth()Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 236–238why, one step back236 * // color support, currently only used with Help237 * getOutHasColors()238 * getErrHasColors()Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4
line 239why, one step back239 * stripColor() // used to remove ANSI escape codes if output does not have colorsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 240why, one step back240 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 241–242why, one step back241 * @param {object} [configuration] - configuration options242 * @return {(Command | object)} `this` command for chaining, or stored configurationDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 243–247why, one step back243 */244245 configureOutput(configuration) {246 if (configuration === undefined) return this._outputConfiguration;247Make .configureOutput() create copy of settings instead of in-place change (#2350)John Geebefore adoption68199e6
lines 248–252why, one step back248 this._outputConfiguration = Object.assign(249 {},250 this._outputConfiguration,251 configuration,252 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 253–258why, one step back253 return this;254 }255256 /**257 * Display the help or a custom message after an error occurs.258 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 259why, one step back259 * @param {(boolean|string)} [displayHelp]Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 260–284why, one step back260 * @return {Command} `this` command for chaining261 */262 showHelpAfterError(displayHelp = true) {263 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;264 this._showHelpAfterError = displayHelp;265 return this;266 }267268 /**269 * Display suggestion of similar commands for unknown commands, or options for unknown options.270 *271 * @param {boolean} [displaySuggestion]272 * @return {Command} `this` command for chaining273 */274 showSuggestionAfterError(displaySuggestion = true) {275 this._showSuggestionAfterError = !!displaySuggestion;276 return this;277 }278279 /**280 * Add a prepared subcommand.281 *282 * See .command() for creating an attached subcommand which inherits settings from its parent.283 *284 * @param {Command} cmd - new subcommandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 285why, one step back285 * @param {object} [opts] - configuration optionsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 286–298why, one step back286 * @return {Command} `this` command for chaining287 */288289 addCommand(cmd, opts) {290 if (!cmd._name) {291 throw new Error(`Command passed to .addCommand() must have a name292- specify the name in Command constructor or using .name()`);293 }294295 opts = opts || {};296 if (opts.isDefault) this._defaultCommandName = cmd._name;297 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation298Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 299why, one step back299 this._registerCommand(cmd);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 300why, one step back300 cmd.parent = this;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 301–302why, one step back301 cmd._checkForBrokenPassThrough();302Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 303–332why, one step back303 return this;304 }305306 /**307 * Factory routine to create a new unattached argument.308 *309 * See .argument() for creating an attached argument, which uses this routine to310 * create the argument. You can override createArgument to return a custom argument.311 *312 * @param {string} name313 * @param {string} [description]314 * @return {Argument} new argument315 */316317 createArgument(name, description) {318 return new Argument(name, description);319 }320321 /**322 * Define argument syntax for command.323 *324 * The default is that the argument is required, and you can explicitly325 * indicate this with <> around the name. Put [] around the name for an optional argument.326 *327 * @example328 * program.argument('<input-file>');329 * program.argument('[output-file]');330 *331 * @param {string} name332 * @param {string} [description]Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 333why, one step back333 * @param {(Function|*)} [parseArg] - custom argument processing function or default valueDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 334–336why, one step back334 * @param {*} [defaultValue]335 * @return {Command} `this` command for chaining336 */Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 337why, one step back337 argument(name, description, parseArg, defaultValue) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 338why, one step back338 const argument = this.createArgument(name, description);Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
lines 339–340why, one step back339 if (typeof parseArg === 'function') {340 argument.default(defaultValue).argParser(parseArg);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 341why, one step back341 } else {Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 342why, one step back342 argument.default(parseArg);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 343–360why, one step back343 }344 this.addArgument(argument);345 return this;346 }347348 /**349 * Define argument syntax for command, adding multiple at once (without descriptions).350 *351 * See also .argument().352 *353 * @example354 * program.arguments('<cmd> [env]');355 *356 * @param {string} names357 * @return {Command} `this` command for chaining358 */359360 arguments(names) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 361–366why, one step back361 names362 .trim()363 .split(/ +/)364 .forEach((detail) => {365 this.argument(detail);366 });Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 367–376why, one step back367 return this;368 }369370 /**371 * Define argument syntax for command, adding a prepared argument.372 *373 * @param {Argument} argument374 * @return {Command} `this` command for chaining375 */376 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 377why, one step back377 const previousArgument = this.registeredArguments.slice(-1)[0];Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 378why, one step back378 if (previousArgument && previousArgument.variadic) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 379–381why, one step back379 throw new Error(380 `only the last argument can be variadic '${previousArgument.name()}'`,381 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 382why, one step back382 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 383–390why, one step back383 if (384 argument.required &&385 argument.defaultValue !== undefined &&386 argument.parseArg === undefined387 ) {388 throw new Error(389 `a default value for a required argument is never used: '${argument.name()}'`,390 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 391why, one step back391 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 392why, one step back392 this.registeredArguments.push(argument);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 393–396why, one step back393 return this;394 }395396 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 397why, one step back397 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 398why, one step back398 *ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 399why, one step back399 * @exampleMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 400–403why, one step back400 * program.helpCommand('help [cmd]');401 * program.helpCommand('help [cmd]', 'show help');402 * program.helpCommand(false); // suppress default help command403 * program.helpCommand(true); // add help command even if no subcommandsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 404why, one step back404 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 405–406why, one step back405 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added406 * @param {string} [description] - custom descriptionDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 407–409why, one step back407 * @return {Command} `this` command for chaining408 */409Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 410–412why, one step back410 helpCommand(enableOrNameAndArgs, description) {411 if (typeof enableOrNameAndArgs === 'boolean') {412 this._addImplicitHelpCommand = enableOrNameAndArgs;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 413–416why, one step back413 if (enableOrNameAndArgs && this._defaultCommandGroup) {414 // make the command to store the group415 this._initCommandGroup(this._getHelpCommand());416 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 417why, one step back417 return this;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 418why, one step back418 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 419why, one step back419Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 420–421why, one step back420 const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';421 const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 422–430why, one step back422 const helpDescription = description ?? 'display help for command';423424 const helpCommand = this.createCommand(helpName);425 helpCommand.helpOption(false);426 if (helpArgs) helpCommand.arguments(helpArgs);427 if (helpDescription) helpCommand.description(helpDescription);428429 this._addImplicitHelpCommand = true;430 this._helpCommand = helpCommand;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 431–432why, one step back431 // init group unless lazy create432 if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 433why, one step back433Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 434–437why, one step back434 return this;435 }436437 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 438–442why, one step back438 * Add prepared custom help command.439 *440 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`441 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only442 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 443why, one step back443 */Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 444–450why, one step back444 addHelpCommand(helpCommand, deprecatedDescription) {445 // If not passed an object, call through to helpCommand for backwards compatibility,446 // as addHelpCommand was originally used like helpCommand is now.447 if (typeof helpCommand !== 'object') {448 this.helpCommand(helpCommand, deprecatedDescription);449 return this;450 }Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 451why, one step back451Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 452–453why, one step back452 this._addImplicitHelpCommand = true;453 this._helpCommand = helpCommand;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 454why, one step back454 this._initCommandGroup(helpCommand);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 455–464why, one step back455 return this;456 }457458 /**459 * Lazy create help command.460 *461 * @return {(Command|null)}462 * @package463 */464 _getHelpCommand() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 465–469why, one step back465 const hasImplicitHelpCommand =466 this._addImplicitHelpCommand ??467 (this.commands.length &&468 !this._actionHandler &&469 !this._findCommand('help'));Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 470–475why, one step back470471 if (hasImplicitHelpCommand) {472 if (this._helpCommand === undefined) {473 this.helpCommand(undefined, undefined); // use default name and description474 }475 return this._helpCommand;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 476why, one step back476 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 477why, one step back477 return null;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 478–488why, one step back478 }479480 /**481 * Add hook for life cycle event.482 *483 * @param {string} event484 * @param {Function} listener485 * @return {Command} `this` command for chaining486 */487488 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 489why, one step back489 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 490–530why, one step back490 if (!allowedValues.includes(event)) {491 throw new Error(`Unexpected value for event passed to hook : '${event}'.492Expecting one of '${allowedValues.join("', '")}'`);493 }494 if (this._lifeCycleHooks[event]) {495 this._lifeCycleHooks[event].push(listener);496 } else {497 this._lifeCycleHooks[event] = [listener];498 }499 return this;500 }501502 /**503 * Register callback to use as replacement for calling process.exit.504 *505 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing506 * @return {Command} `this` command for chaining507 */508509 exitOverride(fn) {510 if (fn) {511 this._exitCallback = fn;512 } else {513 this._exitCallback = (err) => {514 if (err.code !== 'commander.executeSubCommandAsync') {515 throw err;516 } else {517 // Async callback from spawn events, not useful to throw.518 }519 };520 }521 return this;522 }523524 /**525 * Call process.exit, and _exitCallback if defined.526 *527 * @param {number} exitCode exit code for using with process.exit528 * @param {string} code an id string representing the error529 * @param {string} message human-readable description of the error530 * @return neverMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 531why, one step back531 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 532–559why, one step back532 */533534 _exit(exitCode, code, message) {535 if (this._exitCallback) {536 this._exitCallback(new CommanderError(exitCode, code, message));537 // Expecting this line is not reached.538 }539 process.exit(exitCode);540 }541542 /**543 * Register callback `fn` for the command.544 *545 * @example546 * program547 * .command('serve')548 * .description('start service')549 * .action(function() {550 * // do work here551 * });552 *553 * @param {Function} fn554 * @return {Command} `this` command for chaining555 */556557 action(fn) {558 const listener = (args) => {559 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 560why, one step back560 const expectedArgsCount = this.registeredArguments.length;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 561–590why, one step back561 const actionArgs = args.slice(0, expectedArgsCount);562 if (this._storeOptionsAsProperties) {563 actionArgs[expectedArgsCount] = this; // backwards compatible "options"564 } else {565 actionArgs[expectedArgsCount] = this.opts();566 }567 actionArgs.push(this);568569 return fn.apply(this, actionArgs);570 };571 this._actionHandler = listener;572 return this;573 }574575 /**576 * Factory routine to create a new unattached option.577 *578 * See .option() for creating an attached option, which uses this routine to579 * create the option. You can override createOption to return a custom option.580 *581 * @param {string} flags582 * @param {string} [description]583 * @return {Option} new option584 */585586 createOption(flags, description) {587 return new Option(flags, description);588 }589590 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 591–592why, one step back591 * Wrap parseArgs to catch 'commander.invalidArgument'.592 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 593why, one step back593 * @param {(Option | Argument)} targetRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 594why, one step back594 * @param {string} valueReplace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6
line 595why, one step back595 * @param {*} previousRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 596why, one step back596 * @param {string} invalidArgumentMessageMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 597why, one step back597 * @privateRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 598–612why, one step back598 */599600 _callParseArg(target, value, previous, invalidArgumentMessage) {601 try {602 return target.parseArg(value, previous);603 } catch (err) {604 if (err.code === 'commander.invalidArgument') {605 const message = `${invalidArgumentMessage} ${err.message}`;606 this.error(message, { exitCode: err.exitCode, code: err.code });607 }608 throw err;609 }610 }611612 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 613–616why, one step back613 * Check for option flag conflicts.614 * Register option if no conflicts found, or throw on conflict.615 *616 * @param {Option} optionFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 617why, one step back617 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 618–620why, one step back618 */619620 _registerOption(option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 621–622why, one step back621 const matchingOption =622 (option.short && this._findOption(option.short)) ||Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 623–624why, one step back623 (option.long && this._findOption(option.long));624 if (matchingOption) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 625–628why, one step back625 const matchingFlag =626 option.long && this._findOption(option.long)627 ? option.long628 : option.short;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 629–632why, one step back629 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'630- already used by option '${matchingOption.flags}'`);631 }632Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 633why, one step back633 this._initOptionGroup(option);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 634–641why, one step back634 this.options.push(option);635 }636637 /**638 * Check for command name and alias conflicts with existing commands.639 * Register command if no conflicts found, or throw on conflict.640 *641 * @param {Command} commandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 642why, one step back642 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 643–649why, one step back643 */644645 _registerCommand(command) {646 const knownBy = (cmd) => {647 return [cmd.name()].concat(cmd.aliases());648 };649Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 650–652why, one step back650 const alreadyUsed = knownBy(command).find((name) =>651 this._findCommand(name),652 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 653–655why, one step back653 if (alreadyUsed) {654 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');655 const newCmd = knownBy(command).join('|');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 656–658why, one step back656 throw new Error(657 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,658 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 659–660why, one step back659 }660Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 661why, one step back661 this._initCommandGroup(command);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 662–665why, one step back662 this.commands.push(command);663 }664665 /**Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 666–671why, one step back666 * Add an option.667 *668 * @param {Option} option669 * @return {Command} `this` command for chaining670 */671 addOption(option) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 672–673why, one step back672 this._registerOption(option);673Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 674–677why, one step back674 const oname = option.name();675 const name = option.attributeName();676677 // store default valueMake order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
line 678why, one step back678 if (option.defaultValue !== undefined) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 679–692why, one step back679 this.setOptionValueWithSource(name, option.defaultValue, 'default');680 }681682 // handler for cli and env supplied values683 const handleOptionValue = (val, invalidValueMessage, valueSource) => {684 // val is null for optional option used without an optional-argument.685 // val is undefined for boolean and negated option.686 if (val == null && option.presetArg !== undefined) {687 val = option.presetArg;688 }689690 // custom processing691 const oldValue = this.getOptionValue(name);692 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 693why, one step back693 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 694–728why, one step back694 } else if (val !== null && option.variadic) {695 val = option._concatValue(val, oldValue);696 }697698 // Fill-in appropriate missing values. Long winded but easy to follow.699 if (val == null) {700 if (option.negate) {701 val = false;702 } else if (option.isBoolean() || option.optional) {703 val = true;704 } else {705 val = ''; // not normal, parseArg might have failed or be a mock function for testing706 }707 }708 this.setOptionValueWithSource(name, val, valueSource);709 };710711 this.on('option:' + oname, (val) => {712 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;713 handleOptionValue(val, invalidValueMessage, 'cli');714 });715716 if (option.envVar) {717 this.on('optionEnv:' + oname, (val) => {718 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;719 handleOptionValue(val, invalidValueMessage, 'env');720 });721 }722723 return this;724 }725726 /**727 * Internal implementation shared by .option() and .requiredOption()728 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 729why, one step back729 * @return {Command} `this` command for chainingMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 730why, one step back730 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 731–733why, one step back731 */732 _optionEx(config, flags, description, fn, defaultValue) {733 if (typeof flags === 'object' && flags instanceof Option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 734–736why, one step back734 throw new Error(735 'To add an Option object use addOption() instead of option() or requiredOption()',736 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 737–757why, one step back737 }738 const option = this.createOption(flags, description);739 option.makeOptionMandatory(!!config.mandatory);740 if (typeof fn === 'function') {741 option.default(defaultValue).argParser(fn);742 } else if (fn instanceof RegExp) {743 // deprecated744 const regex = fn;745 fn = (val, def) => {746 const m = regex.exec(val);747 return m ? m[0] : def;748 };749 option.default(defaultValue).argParser(fn);750 } else {751 option.default(fn);752 }753754 return this.addOption(option);755 }756757 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 758why, one step back758 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 759why, one step back759 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 760–761why, one step back760 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required761 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 762why, one step back762 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 763why, one step back763 * See the README for more details, and see also addOption() and requiredOption().Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 764–765why, one step back764 *765 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 766–767why, one step back766 * program767 * .option('-p, --pepper', 'add pepper')Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f
line 768why, one step back768 * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argumentRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 769–770why, one step back769 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default770 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 771–773why, one step back771 *772 * @param {string} flags773 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 774why, one step back774 * @param {(Function|*)} [parseArg] - custom option processing function or default valueDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 775–778why, one step back775 * @param {*} [defaultValue]776 * @return {Command} `this` command for chaining777 */778Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 779–780why, one step back779 option(flags, description, parseArg, defaultValue) {780 return this._optionEx({}, flags, description, parseArg, defaultValue);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 781–783why, one step back781 }782783 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 784–794why, one step back784 * Add a required option which must have a value after parsing. This usually means785 * the option must be specified on the command line. (Otherwise the same as .option().)786 *787 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.788 *789 * @param {string} flags790 * @param {string} [description]791 * @param {(Function|*)} [parseArg] - custom option processing function or default value792 * @param {*} [defaultValue]793 * @return {Command} `this` command for chaining794 */Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 795why, one step back795Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 796why, one step back796 requiredOption(flags, description, parseArg, defaultValue) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 797–803why, one step back797 return this._optionEx(798 { mandatory: true },799 flags,800 description,801 parseArg,802 defaultValue,803 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 804–813why, one step back804 }805806 /**807 * Alter parsing of short flags with optional values.808 *809 * @example810 * // for `.option('-f,--flag [value]'):811 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour812 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`813 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 814–815why, one step back814 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.815 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 816–824why, one step back816 */817 combineFlagAndOptionalValue(combine = true) {818 this._combineFlagAndOptionalValue = !!combine;819 return this;820 }821822 /**823 * Allow unknown options on the command line.824 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 825–826why, one step back825 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.826 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 827–835why, one step back827 */828 allowUnknownOption(allowUnknown = true) {829 this._allowUnknownOption = !!allowUnknown;830 return this;831 }832833 /**834 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.835 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 836–837why, one step back836 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.837 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 838–848why, one step back838 */839 allowExcessArguments(allowExcess = true) {840 this._allowExcessArguments = !!allowExcess;841 return this;842 }843844 /**845 * Enable positional options. Positional means global options are specified before subcommands which lets846 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.847 * The default behaviour is non-positional and global options may appear anywhere on the command line.848 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 849–850why, one step back849 * @param {boolean} [positional]850 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 851–862why, one step back851 */852 enablePositionalOptions(positional = true) {853 this._enablePositionalOptions = !!positional;854 return this;855 }856857 /**858 * Pass through options that come after command-arguments rather than treat them as command-options,859 * so actual command-options come before command-arguments. Turning this on for a subcommand requires860 * positional options to have been enabled on the program (parent commands).861 * The default behaviour is non-positional and options may appear before or after command-arguments.862 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 863–864why, one step back863 * @param {boolean} [passThrough] for unknown options.864 * @return {Command} `this` command for chainingDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 865–867why, one step back865 */866 passThroughOptions(passThrough = true) {867 this._passThroughOptions = !!passThrough;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 868why, one step back868 this._checkForBrokenPassThrough();Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 869–872why, one step back869 return this;870 }871872 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 873–876why, one step back873 * @private874 */875876 _checkForBrokenPassThrough() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 877–884why, one step back877 if (878 this.parent &&879 this._passThroughOptions &&880 !this.parent._enablePositionalOptions881 ) {882 throw new Error(883 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,884 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 885–888why, one step back885 }886 }887888 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 889–894why, one step back889 * Whether to store option values as properties on command object,890 * or store separately (specify false). In both cases the option values can be accessed using .opts().891 *892 * @param {boolean} [storeAsProperties=true]893 * @return {Command} `this` command for chaining894 */Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 895–899why, one step back895896 storeOptionsAsProperties(storeAsProperties = true) {897 if (this.options.length) {898 throw new Error('call .storeOptionsAsProperties() before adding options');899 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 900why, one step back900 if (Object.keys(this._optionValues).length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 901–903why, one step back901 throw new Error(902 'call .storeOptionsAsProperties() before setting option values',903 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 904why, one step back904 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
line 905why, one step back905 this._storeOptionsAsProperties = !!storeAsProperties;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 906–912why, one step back906 return this;907 }908909 /**910 * Retrieve option value.911 *912 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 913why, one step back913 * @return {object} valueDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 914–926why, one step back914 */915916 getOptionValue(key) {917 if (this._storeOptionsAsProperties) {918 return this[key];919 }920 return this._optionValues[key];921 }922923 /**924 * Store option value.925 *926 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 927why, one step back927 * @param {object} valueDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 928–931why, one step back928 * @return {Command} `this` command for chaining929 */930931 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 932why, one step back932 return this.setOptionValueWithSource(key, value, undefined);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 933–935why, one step back933 }934935 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 936–938why, one step back936 * Store option value and where the value came from.937 *938 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 939why, one step back939 * @param {object} valueReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 940–942why, one step back940 * @param {string} source - expected values are default/config/env/cli/implied941 * @return {Command} `this` command for chaining942 */Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 943–944why, one step back943944 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 945–949why, one step back945 if (this._storeOptionsAsProperties) {946 this[key] = value;947 } else {948 this._optionValues[key] = value;949 }Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 950–954why, one step back950 this._optionValueSources[key] = source;951 return this;952 }953954 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 955–960why, one step back955 * Get source of option value.956 * Expected values are default | config | env | cli | implied957 *958 * @param {string} key959 * @return {string}960 */Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 961–966why, one step back961962 getOptionValueSource(key) {963 return this._optionValueSources[key];964 }965966 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 967–972why, one step back967 * Get source of option value. See also .optsWithGlobals().968 * Expected values are default | config | env | cli | implied969 *970 * @param {string} key971 * @return {string}972 */Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 973–976why, one step back973974 getOptionValueSourceWithGlobals(key) {975 // global overwrites local, like optsWithGlobals976 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 977why, one step back977 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 978–985why, one step back978 if (cmd.getOptionValueSource(key) !== undefined) {979 source = cmd.getOptionValueSource(key);980 }981 });982 return source;983 }984985 /**Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 986–988why, one step back986 * Get user arguments from implied or explicit arguments.987 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.988 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 989why, one step back989 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 990–997why, one step back990 */991992 _prepareUserArgs(argv, parseOptions) {993 if (argv !== undefined && !Array.isArray(argv)) {994 throw new Error('first parameter to parse must be array or undefined');995 }996 parseOptions = parseOptions || {};997Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 998–1000why, one step back998 // auto-detect argument conventions if nothing supplied999 if (argv === undefined && parseOptions.from === undefined) {1000 if (process.versions?.electron) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1001–1002why, one step back1001 parseOptions.from = 'electron';1002 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1003–1012why, one step back1003 // check node specific options for scenarios where user CLI args follow executable without scriptname1004 const execArgv = process.execArgv ?? [];1005 if (1006 execArgv.includes('-e') ||1007 execArgv.includes('--eval') ||1008 execArgv.includes('-p') ||1009 execArgv.includes('--print')1010 ) {1011 parseOptions.from = 'eval'; // internal usage, not documented1012 }Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1013why, one step back1013 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1014–1018why, one step back10141015 // default to using process.argv1016 if (argv === undefined) {1017 argv = process.argv;1018 }Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1019–1020why, one step back1019 this.rawArgs = argv.slice();1020Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1021why, one step back1021 // extract the user args and scriptPathDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1022–1029why, one step back1022 let userArgs;1023 switch (parseOptions.from) {1024 case undefined:1025 case 'node':1026 this._scriptPath = argv[1];1027 userArgs = argv.slice(2);1028 break;1029 case 'electron':ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1030why, one step back1030 // @ts-ignore: because defaultApp is an unknown propertyDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1031–1040why, one step back1031 if (process.defaultApp) {1032 this._scriptPath = argv[1];1033 userArgs = argv.slice(2);1034 } else {1035 userArgs = argv.slice(1);1036 }1037 break;1038 case 'user':1039 userArgs = argv.slice(0);1040 break;Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1041–1043why, one step back1041 case 'eval':1042 userArgs = argv.slice(1);1043 break;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1044why, one step back1044 default:Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1045–1047why, one step back1045 throw new Error(1046 `unexpected parse option { from: '${parseOptions.from}' }`,1047 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1048–1050why, one step back1048 }10491050 // Find default name for program from arguments.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1051–1052why, one step back1051 if (!this._name && this._scriptPath)1052 this.nameFromFilename(this._scriptPath);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1053–1060why, one step back1053 this._name = this._name || 'program';10541055 return userArgs;1056 }10571058 /**1059 * Parse `argv`, setting options and invoking commands when defined.1060 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1061why, one step back1061 * Use parseAsync instead of parse if any of your action handlers are async.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1062why, one step back1062 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1063–1069why, one step back1063 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1064 *1065 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1066 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1067 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1068 * - `'user'`: just user arguments1069 *Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1070why, one step back1070 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1071–1072why, one step back1071 * program.parse(); // parse process.argv and auto-detect electron and special node flags1072 * program.parse(process.argv); // assume argv[0] is app and argv[1] is scriptDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1073–1074why, one step back1073 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1074 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 1075–1077why, one step back1075 * @param {string[]} [argv] - optional, defaults to process.argv1076 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1077 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1078–1081why, one step back1078 * @return {Command} `this` command for chaining1079 */10801081 parse(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1082why, one step back1082 this._prepareForParse();Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1083–1091why, one step back1083 const userArgs = this._prepareUserArgs(argv, parseOptions);1084 this._parseCommand([], userArgs);10851086 return this;1087 }10881089 /**1090 * Parse `argv`, setting options and invoking commands when defined.1091 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1092why, one step back1092 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1093why, one step back1093 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1094–1097why, one step back1094 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1095 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1096 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1097 * - `'user'`: just user argumentsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1098–1099why, one step back1098 *1099 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1100–1101why, one step back1100 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1101 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is scriptDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1102–1104why, one step back1102 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1103 *1104 * @param {string[]} [argv]Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1105why, one step back1105 * @param {object} [parseOptions]Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1106why, one step back1106 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1107–1110why, one step back1107 * @return {Promise}1108 */11091110 async parseAsync(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1111why, one step back1111 this._prepareForParse();Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1112–1117why, one step back1112 const userArgs = this._prepareUserArgs(argv, parseOptions);1113 await this._parseCommand([], userArgs);11141115 return this;1116 }1117Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1118why, one step back1118 _prepareForParse() {Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
line 1119why, one step back1119 // Save the state the first time, then restore the state before each subsequent parse.Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1120why, one step back1120 if (this._savedState === null) {Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
lines 1121–1141why, one step back1121 // Do the special default of lone negated option to true, now that we have all the options.1122 // Filter for negated options that have not been processed already.1123 this.options1124 .filter(1125 (option) =>1126 option.negate &&1127 option.defaultValue === undefined &&1128 this.getOptionValue(option.attributeName()) === undefined,1129 )1130 .forEach((option) => {1131 // check for lone negated option: --no-foo without a --foo option1132 const positiveLongFlag = option.long.replace(/^--no-/, '--');1133 if (!this._findOption(positiveLongFlag)) {1134 this.setOptionValueWithSource(1135 option.attributeName(),1136 true,1137 'default',1138 );1139 }1140 });1141Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1142–1147why, one step back1142 this.saveStateBeforeParse();1143 } else {1144 this.restoreStateBeforeParse();1145 }1146 }1147Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1148why, one step back1148 /**Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1149–1189why, one step back1149 * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.1150 * Not usually called directly, but available for subclasses to save their custom state.1151 *1152 * This is called in a lazy way. Only commands used in parsing chain will have state saved.1153 */1154 saveStateBeforeParse() {1155 this._savedState = {1156 // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1157 _name: this._name,1158 // option values before parse have default values (including false for negated options)1159 // shallow clones1160 _optionValues: { ...this._optionValues },1161 _optionValueSources: { ...this._optionValueSources },1162 };1163 }11641165 /**1166 * Restore state before parse for calls after the first.1167 * Not usually called directly, but available for subclasses to save their custom state.1168 *1169 * This is called in a lazy way. Only commands used in parsing chain will have state restored.1170 */1171 restoreStateBeforeParse() {1172 if (this._storeOptionsAsProperties)1173 throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1174- either make a new Command for each call to parse, or stop storing options as properties`);11751176 // clear state from _prepareUserArgs1177 this._name = this._savedState._name;1178 this._scriptPath = null;1179 this.rawArgs = [];1180 // clear state from setOptionValueWithSource1181 this._optionValues = { ...this._savedState._optionValues };1182 this._optionValueSources = { ...this._savedState._optionValueSources };1183 // clear state from _parseCommand1184 this.args = [];1185 // clear state from _processArguments1186 this.processedArgs = [];1187 }11881189 /**Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1190–1209why, one step back1190 * Throw if expected executable is missing. Add lots of help for author.1191 *1192 * @param {string} executableFile1193 * @param {string} executableDir1194 * @param {string} subcommandName1195 */1196 _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1197 if (fs.existsSync(executableFile)) return;11981199 const executableDirMessage = executableDir1200 ? `searched for local subcommand relative to directory '${executableDir}'`1201 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1202 const executableMissing = `'${executableFile}' does not exist1203 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1204 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1205 - ${executableDirMessage}`;1206 throw new Error(executableMissing);1207 }12081209 /**Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1210–1211why, one step back1210 * Execute a sub-command executable.1211 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1212why, one step back1212 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1213–1228why, one step back1213 */12141215 _executeSubCommand(subcommand, args) {1216 args = args.slice();1217 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1218 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12191220 function findFile(baseDir, baseName) {1221 // Look for specified file1222 const localBin = path.resolve(baseDir, baseName);1223 if (fs.existsSync(localBin)) return localBin;12241225 // Stop looking if candidate already has an expected extension.1226 if (sourceExt.includes(path.extname(baseName))) return undefined;12271228 // Try all the extensions.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1229–1231why, one step back1229 const foundExt = sourceExt.find((ext) =>1230 fs.existsSync(`${localBin}${ext}`),1231 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1232–1241why, one step back1232 if (foundExt) return `${localBin}${foundExt}`;12331234 return undefined;1235 }12361237 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1238 this._checkForMissingMandatoryOptions();1239 this._checkForConflictingOptions();12401241 // executableFile and executableDir might be full path, or just a nameReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1242–1243why, one step back1242 let executableFile =1243 subcommand._executableFile || `${this._name}-${subcommand._name}`;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1244–1248why, one step back1244 let executableDir = this._executableDir || '';1245 if (this._scriptPath) {1246 let resolvedScriptPath; // resolve possible symlink for installed npm binary1247 try {1248 resolvedScriptPath = fs.realpathSync(this._scriptPath);Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585
line 1249why, one step back1249 } catch {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1250–1251why, one step back1250 resolvedScriptPath = this._scriptPath;1251 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1252–1255why, one step back1252 executableDir = path.resolve(1253 path.dirname(resolvedScriptPath),1254 executableDir,1255 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1256–1263why, one step back1256 }12571258 // Look for a local file in preference to a command in PATH.1259 if (executableDir) {1260 let localFile = findFile(executableDir, executableFile);12611262 // Legacy search using prefix of script name instead of command name1263 if (!localFile && !subcommand._executableFile && this._scriptPath) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1264–1267why, one step back1264 const legacyName = path.basename(1265 this._scriptPath,1266 path.extname(this._scriptPath),1267 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1268why, one step back1268 if (legacyName !== this._name) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1269–1272why, one step back1269 localFile = findFile(1270 executableDir,1271 `${legacyName}-${subcommand._name}`,1272 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1273–1291why, one step back1273 }1274 }1275 executableFile = localFile || executableFile;1276 }12771278 launchWithNode = sourceExt.includes(path.extname(executableFile));12791280 let proc;1281 if (process.platform !== 'win32') {1282 if (launchWithNode) {1283 args.unshift(executableFile);1284 // add executable arguments to spawn1285 args = incrementNodeInspectorPort(process.execArgv).concat(args);12861287 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1288 } else {1289 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1290 }1291 } else {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1292–1296why, one step back1292 this._checkForMissingExecutable(1293 executableFile,1294 executableDir,1295 subcommand._name,1296 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1297–1302why, one step back1297 args.unshift(executableFile);1298 // add executable arguments to spawn1299 args = incrementNodeInspectorPort(process.execArgv).concat(args);1300 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1301 }1302Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1303–1304why, one step back1303 if (!proc.killed) {1304 // testing mainly to avoid leak warnings during unit tests with mocked spawnDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1305–1308why, one step back1305 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1306 signals.forEach((signal) => {1307 process.on(signal, () => {1308 if (proc.killed === false && proc.exitCode === null) {Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1309why, one step back1309 // @ts-ignore because signals not typed to known stringsDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1310–1317why, one step back1310 proc.kill(signal);1311 }1312 });1313 });1314 }13151316 // By default terminate process when spawned process terminates.1317 const exitCallback = this._exitCallback;ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1318why, one step back1318 proc.on('close', (code) => {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1319–1322why, one step back1319 code = code ?? 1; // code is null if spawned process terminated due to a signal1320 if (!exitCallback) {1321 process.exit(code);1322 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1323–1329why, one step back1323 exitCallback(1324 new CommanderError(1325 code,1326 'commander.executeSubCommandAsync',1327 '(close)',1328 ),1329 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1330–1331why, one step back1330 }1331 });Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1332why, one step back1332 proc.on('error', (err) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1333why, one step back1333 // @ts-ignore: because err.code is an unknown propertyDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1334why, one step back1334 if (err.code === 'ENOENT') {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1335–1339why, one step back1335 this._checkForMissingExecutable(1336 executableFile,1337 executableDir,1338 subcommand._name,1339 );Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1340why, one step back1340 // @ts-ignore: because err.code is an unknown propertyDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1341–1346why, one step back1341 } else if (err.code === 'EACCES') {1342 throw new Error(`'${executableFile}' not executable`);1343 }1344 if (!exitCallback) {1345 process.exit(1);1346 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1347–1351why, one step back1347 const wrappedError = new CommanderError(1348 1,1349 'commander.executeSubCommandAsync',1350 '(error)',1351 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1352–1361why, one step back1352 wrappedError.nestedError = err;1353 exitCallback(wrappedError);1354 }1355 });13561357 // Store the reference to the child process1358 this.runningCommand = proc;1359 }13601361 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1362why, one step back1362 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1363–1368why, one step back1363 */13641365 _dispatchSubcommand(commandName, operands, unknown) {1366 const subCommand = this._findCommand(commandName);1367 if (!subCommand) this.help({ error: true });1368Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1369why, one step back1369 subCommand._prepareForParse();Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1370why, one step back1370 let promiseChain;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1371–1375why, one step back1371 promiseChain = this._chainOrCallSubCommandHook(1372 promiseChain,1373 subCommand,1374 'preSubcommand',1375 );Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1376why, one step back1376 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1377–1382why, one step back1377 if (subCommand._executableHandler) {1378 this._executeSubCommand(subCommand, operands.concat(unknown));1379 } else {1380 return subCommand._parseCommand(operands, unknown);1381 }1382 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1383why, one step back1383 return promiseChain;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1384–1386why, one step back1384 }13851386 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1387–1389why, one step back1387 * Invoke help directly if possible, or dispatch if necessary.1388 * e.g. help foo1389 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1390why, one step back1390 * @privateHave help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1391–1402why, one step back1391 */13921393 _dispatchHelpCommand(subcommandName) {1394 if (!subcommandName) {1395 this.help();1396 }1397 const subCommand = this._findCommand(subcommandName);1398 if (subCommand && !subCommand._executableHandler) {1399 subCommand.help();1400 }14011402 // Fallback to parsing the help flag to invoke the help.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1403–1407why, one step back1403 return this._dispatchSubcommand(1404 subcommandName,1405 [],1406 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1407 );Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1408–1410why, one step back1408 }14091410 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1411why, one step back1411 * Check this.args against expected this.registeredArguments.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1412why, one step back1412 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1413why, one step back1413 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1414–1417why, one step back1414 */14151416 _checkNumberOfArguments() {1417 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1418why, one step back1418 this.registeredArguments.forEach((arg, i) => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1419–1423why, one step back1419 if (arg.required && this.args[i] == null) {1420 this.missingArgument(arg.name());1421 }1422 });1423 // too manyReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1424–1427why, one step back1424 if (1425 this.registeredArguments.length > 0 &&1426 this.registeredArguments[this.registeredArguments.length - 1].variadic1427 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1428–1429why, one step back1428 return;1429 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1430why, one step back1430 if (this.args.length > this.registeredArguments.length) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1431–1435why, one step back1431 this._excessArguments(this.args);1432 }1433 }14341435 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1436why, one step back1436 * Process this.args using this.registeredArguments and save as this.processedArgs!Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1437why, one step back1437 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1438why, one step back1438 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1439–1445why, one step back1439 */14401441 _processArguments() {1442 const myParseArg = (argument, value, previous) => {1443 // Extra processing for nice error message on parsing failure.1444 let parsedValue = value;1445 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 1446why, one step back1446 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1447–1452why, one step back1447 parsedValue = this._callParseArg(1448 argument,1449 value,1450 previous,1451 invalidValueMessage,1452 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1453–1459why, one step back1453 }1454 return parsedValue;1455 };14561457 this._checkNumberOfArguments();14581459 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1460why, one step back1460 this.registeredArguments.forEach((declaredArg, index) => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1461–1487why, one step back1461 let value = declaredArg.defaultValue;1462 if (declaredArg.variadic) {1463 // Collect together remaining arguments for passing together as an array.1464 if (index < this.args.length) {1465 value = this.args.slice(index);1466 if (declaredArg.parseArg) {1467 value = value.reduce((processed, v) => {1468 return myParseArg(declaredArg, v, processed);1469 }, declaredArg.defaultValue);1470 }1471 } else if (value === undefined) {1472 value = [];1473 }1474 } else if (index < this.args.length) {1475 value = this.args[index];1476 if (declaredArg.parseArg) {1477 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1478 }1479 }1480 processedArgs[index] = value;1481 });1482 this.processedArgs = processedArgs;1483 }14841485 /**1486 * Once we have a promise we chain, but call synchronously until then.1487 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1488why, one step back1488 * @param {(Promise|undefined)} promiseDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1489why, one step back1489 * @param {Function} fnMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1490–1491why, one step back1490 * @return {(Promise|undefined)}1491 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1492–1505why, one step back1492 */14931494 _chainOrCall(promise, fn) {1495 // thenable1496 if (promise && promise.then && typeof promise.then === 'function') {1497 // already have a promise, chain callback1498 return promise.then(() => fn());1499 }1500 // callback might return a promise1501 return fn();1502 }15031504 /**1505 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1506why, one step back1506 * @param {(Promise|undefined)} promiseDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1507why, one step back1507 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1508–1509why, one step back1508 * @return {(Promise|undefined)}1509 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1510–1514why, one step back1510 */15111512 _chainOrCallHooks(promise, event) {1513 let result = promise;1514 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1515why, one step back1515 this._getCommandAndAncestors()Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1516why, one step back1516 .reverse()Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1517–1518why, one step back1517 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1518 .forEach((hookedCommand) => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1519–1531why, one step back1519 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1520 hooks.push({ hookedCommand, callback });1521 });1522 });1523 if (event === 'postAction') {1524 hooks.reverse();1525 }15261527 hooks.forEach((hookDetail) => {1528 result = this._chainOrCall(result, () => {1529 return hookDetail.callback(hookDetail.hookedCommand, this);1530 });1531 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1532–1536why, one step back1532 return result;1533 }15341535 /**1536 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1537why, one step back1537 * @param {(Promise|undefined)} promisefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1538–1539why, one step back1538 * @param {Command} subCommand1539 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1540–1541why, one step back1540 * @return {(Promise|undefined)}1541 * @privatefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1542–1552why, one step back1542 */15431544 _chainOrCallSubCommandHook(promise, subCommand, event) {1545 let result = promise;1546 if (this._lifeCycleHooks[event] !== undefined) {1547 this._lifeCycleHooks[event].forEach((hook) => {1548 result = this._chainOrCall(result, () => {1549 return hook(this, subCommand);1550 });1551 });1552 }Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1553–1559why, one step back1553 return result;1554 }15551556 /**1557 * Process arguments in context of this command.1558 * Returns action result, in case it is a promise.1559 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1560why, one step back1560 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1561–1565why, one step back1561 */15621563 _parseCommand(operands, unknown) {1564 const parsed = this.parseOptions(unknown);1565 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1566why, one step back1566 this._parseOptionsImplied();Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1567–1573why, one step back1567 operands = operands.concat(parsed.operands);1568 unknown = parsed.unknown;1569 this.args = operands.concat(unknown);15701571 if (operands && this._findCommand(operands[0])) {1572 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1573 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1574–1577why, one step back1574 if (1575 this._getHelpCommand() &&1576 operands[0] === this._getHelpCommand().name()1577 ) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1578why, one step back1578 return this._dispatchHelpCommand(operands[1]);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1579–1580why, one step back1579 }1580 if (this._defaultCommandName) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1581why, one step back1581 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default commandReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1582–1586why, one step back1582 return this._dispatchSubcommand(1583 this._defaultCommandName,1584 operands,1585 unknown,1586 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1587why, one step back1587 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1588–1593why, one step back1588 if (1589 this.commands.length &&1590 this.args.length === 0 &&1591 !this._actionHandler &&1592 !this._defaultCommandName1593 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1594–1597why, one step back1594 // probably missing subcommand and no handler, user needs help (and exit)1595 this.help({ error: true });1596 }1597Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1598why, one step back1598 this._outputHelpIfRequested(parsed.unknown);Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1599–1613why, one step back1599 this._checkForMissingMandatoryOptions();1600 this._checkForConflictingOptions();16011602 // We do not always call this check to avoid masking a "better" error, like unknown command.1603 const checkForUnknownOptions = () => {1604 if (parsed.unknown.length > 0) {1605 this.unknownOption(parsed.unknown[0]);1606 }1607 };16081609 const commandEvent = `command:${this.name()}`;1610 if (this._actionHandler) {1611 checkForUnknownOptions();1612 this._processArguments();1613Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1614–1615why, one step back1614 let promiseChain;1615 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1616–1618why, one step back1616 promiseChain = this._chainOrCall(promiseChain, () =>1617 this._actionHandler(this.processedArgs),1618 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1619why, one step back1619 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1620why, one step back1620 promiseChain = this._chainOrCall(promiseChain, () => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1621–1623why, one step back1621 this.parent.emit(commandEvent, operands, unknown); // legacy1622 });1623 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1624–1625why, one step back1624 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1625 return promiseChain;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1626–1631why, one step back1626 }1627 if (this.parent && this.parent.listenerCount(commandEvent)) {1628 checkForUnknownOptions();1629 this._processArguments();1630 this.parent.emit(commandEvent, operands, unknown); // legacy1631 } else if (operands.length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1632–1633why, one step back1632 if (this._findCommand('*')) {1633 // legacy default commandDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1634–1658why, one step back1634 return this._dispatchSubcommand('*', operands, unknown);1635 }1636 if (this.listenerCount('command:*')) {1637 // skip option check, emit event for possible misspelling suggestion1638 this.emit('command:*', operands, unknown);1639 } else if (this.commands.length) {1640 this.unknownCommand();1641 } else {1642 checkForUnknownOptions();1643 this._processArguments();1644 }1645 } else if (this.commands.length) {1646 checkForUnknownOptions();1647 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1648 this.help({ error: true });1649 } else {1650 checkForUnknownOptions();1651 this._processArguments();1652 // fall through for caller to handle after calling .parse()1653 }1654 }16551656 /**1657 * Find matching command.1658 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1659why, one step back1659 * @privateFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1660why, one step back1660 * @return {Command | undefined}Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1661–1663why, one step back1661 */1662 _findCommand(name) {1663 if (!name) return undefined;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1664–1666why, one step back1664 return this.commands.find(1665 (cmd) => cmd._name === name || cmd._aliases.includes(name),1666 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1667–1673why, one step back1667 }16681669 /**1670 * Return an option matching `arg` if any.1671 *1672 * @param {string} arg1673 * @return {Option}Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1674why, one step back1674 * @packageDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1675–1677why, one step back1675 */16761677 _findOption(arg) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1678why, one step back1678 return this.options.find((option) => option.is(arg));Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1679–1684why, one step back1679 }16801681 /**1682 * Display an error message if a mandatory option does not have a value.1683 * Called after checking for help flags in leaf subcommand.1684 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1685why, one step back1685 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1686–1689why, one step back1686 */16871688 _checkForMissingMandatoryOptions() {1689 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1690why, one step back1690 this._getCommandAndAncestors().forEach((cmd) => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1691why, one step back1691 cmd.options.forEach((anOption) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1692–1695why, one step back1692 if (1693 anOption.mandatory &&1694 cmd.getOptionValue(anOption.attributeName()) === undefined1695 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1696–1698why, one step back1696 cmd.missingMandatoryOptionValue(anOption);1697 }1698 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1699why, one step back1699 });Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1700–1704why, one step back1700 }17011702 /**1703 * Display an error message if conflicting options are used together in this.1704 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1705why, one step back1705 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1706–1707why, one step back1706 */1707 _checkForConflictingLocalOptions() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1708–1711why, one step back1708 const definedNonDefaultOptions = this.options.filter((option) => {1709 const optionKey = option.attributeName();1710 if (this.getOptionValue(optionKey) === undefined) {1711 return false;Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1712why, one step back1712 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1713–1714why, one step back1713 return this.getOptionValueSource(optionKey) !== 'default';1714 });Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1715–1716why, one step back17151716 const optionsWithConflicting = definedNonDefaultOptions.filter(Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1717why, one step back1717 (option) => option.conflictsWith.length > 0,Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1718–1721why, one step back1718 );17191720 optionsWithConflicting.forEach((option) => {1721 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1722why, one step back1722 option.conflictsWith.includes(defined.attributeName()),Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1723–1733why, one step back1723 );1724 if (conflictingAndDefined) {1725 this._conflictingOption(option, conflictingAndDefined);1726 }1727 });1728 }17291730 /**1731 * Display an error message if conflicting options are used together.1732 * Called after checking for help flags in leaf subcommand.1733 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1734why, one step back1734 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1735–1737why, one step back1735 */1736 _checkForConflictingOptions() {1737 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1738why, one step back1738 this._getCommandAndAncestors().forEach((cmd) => {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1739why, one step back1739 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1740why, one step back1740 });Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1741–1745why, one step back1741 }17421743 /**1744 * Parse options from `argv` removing known options,1745 * and return argv split into operands and unknown arguments.Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1746–1747why, one step back1746 *1747 * Side effects: modifies command by storing options. Does not reset state if called again.Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1748–1756why, one step back1748 *1749 * Examples:1750 *1751 * argv => operands, unknown1752 * --known kkk op => [op], []1753 * op --known kkk => [op], []1754 * sub --unknown uuu op => [sub], [--unknown uuu op]1755 * sub -- --unknown uuu op => [sub --unknown uuu op], []1756 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1757–1758why, one step back1757 * @param {string[]} argv1758 * @return {{operands: string[], unknown: string[]}}Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1759–1770why, one step back1759 */17601761 parseOptions(argv) {1762 const operands = []; // operands, not options or values1763 const unknown = []; // first unknown option and remaining unknown args1764 let dest = operands;1765 const args = argv.slice();17661767 function maybeOption(arg) {1768 return arg.length > 1 && arg[0] === '-';1769 }1770Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1771–1781why, one step back1771 const negativeNumberArg = (arg) => {1772 // return false if not a negative number1773 if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;1774 // negative number is ok unless digit used as an option in command hierarchy1775 return !this._getCommandAndAncestors().some((cmd) =>1776 cmd.options1777 .map((opt) => opt.short)1778 .some((short) => /^-\d$/.test(short)),1779 );1780 };1781Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1782–1793why, one step back1782 // parse options1783 let activeVariadicOption = null;1784 while (args.length) {1785 const arg = args.shift();17861787 // literal1788 if (arg === '--') {1789 if (dest === unknown) dest.push(arg);1790 dest.push(...args);1791 break;1792 }1793Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1794–1797why, one step back1794 if (1795 activeVariadicOption &&1796 (!maybeOption(arg) || negativeNumberArg(arg))1797 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1798–1813why, one step back1798 this.emit(`option:${activeVariadicOption.name()}`, arg);1799 continue;1800 }1801 activeVariadicOption = null;18021803 if (maybeOption(arg)) {1804 const option = this._findOption(arg);1805 // recognised option, call listener to assign value with possible custom processing1806 if (option) {1807 if (option.required) {1808 const value = args.shift();1809 if (value === undefined) this.optionMissingArgument(option);1810 this.emit(`option:${option.name()}`, value);1811 } else if (option.optional) {1812 let value = null;1813 // historical behaviour is optional value is following arg unless an optionAllow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1814–1817why, one step back1814 if (1815 args.length > 0 &&1816 (!maybeOption(args[0]) || negativeNumberArg(args[0]))1817 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1818–1820why, one step back1818 value = args.shift();1819 }1820 this.emit(`option:${option.name()}`, value);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1821–1822why, one step back1821 } else {1822 // boolean flagDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1823–1833why, one step back1823 this.emit(`option:${option.name()}`);1824 }1825 activeVariadicOption = option.variadic ? option : null;1826 continue;1827 }1828 }18291830 // Look for combo options following single dash, eat first one if known.1831 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1832 const option = this._findOption(`-${arg[1]}`);1833 if (option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1834–1837why, one step back1834 if (1835 option.required ||1836 (option.optional && this._combineFlagAndOptionalValue)1837 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1838–1862why, one step back1838 // option with value following in same argument1839 this.emit(`option:${option.name()}`, arg.slice(2));1840 } else {1841 // boolean option, emit and put back remainder of arg for further processing1842 this.emit(`option:${option.name()}`);1843 args.unshift(`-${arg.slice(2)}`);1844 }1845 continue;1846 }1847 }18481849 // Look for known long flag with value, like --foo=bar1850 if (/^--[^=]+=/.test(arg)) {1851 const index = arg.indexOf('=');1852 const option = this._findOption(arg.slice(0, index));1853 if (option && (option.required || option.optional)) {1854 this.emit(`option:${option.name()}`, arg.slice(index + 1));1855 continue;1856 }1857 }18581859 // Not a recognised option by this command.1860 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18611862 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1863–1868why, one step back1863 // A negative number in a leaf command is not an unknown option.1864 if (1865 dest === operands &&1866 maybeOption(arg) &&1867 !(this.commands.length === 0 && negativeNumberArg(arg))1868 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1869–1872why, one step back1869 dest = unknown;1870 }18711872 // If using positionalOptions, stop processing our options at subcommand.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1873–1877why, one step back1873 if (1874 (this._enablePositionalOptions || this._passThroughOptions) &&1875 operands.length === 0 &&1876 unknown.length === 01877 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1878–1881why, one step back1878 if (this._findCommand(arg)) {1879 operands.push(arg);1880 if (args.length > 0) unknown.push(...args);1881 break;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1882–1885why, one step back1882 } else if (1883 this._getHelpCommand() &&1884 arg === this._getHelpCommand().name()1885 ) {Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1886–1912why, one step back1886 operands.push(arg);1887 if (args.length > 0) operands.push(...args);1888 break;1889 } else if (this._defaultCommandName) {1890 unknown.push(arg);1891 if (args.length > 0) unknown.push(...args);1892 break;1893 }1894 }18951896 // If using passThroughOptions, stop processing options at first command-argument.1897 if (this._passThroughOptions) {1898 dest.push(arg);1899 if (args.length > 0) dest.push(...args);1900 break;1901 }19021903 // add arg1904 dest.push(arg);1905 }19061907 return { operands, unknown };1908 }19091910 /**1911 * Return an object containing local option values as key-value pairs.1912 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1913why, one step back1913 * @return {object}Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1914–1922why, one step back1914 */1915 opts() {1916 if (this._storeOptionsAsProperties) {1917 // Preserve original behaviour so backwards compatible when still using properties1918 const result = {};1919 const len = this.options.length;19201921 for (let i = 0; i < len; i++) {1922 const key = this.options[i].attributeName();Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1923–1924why, one step back1923 result[key] =1924 key === this._versionOptionName ? this._version : this[key];Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1925–1934why, one step back1925 }1926 return result;1927 }19281929 return this._optionValues;1930 }19311932 /**1933 * Return an object containing merged local and global option values as key-value pairs.1934 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1935why, one step back1935 * @return {object}Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1936–1938why, one step back1936 */1937 optsWithGlobals() {1938 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1939why, one step back1939 return this._getCommandAndAncestors().reduce(Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
line 1940why, one step back1940 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1941why, one step back1941 {},Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1942–1948why, one step back1942 );1943 }19441945 /**1946 * Display error message and exit (or call exitOverride).1947 *1948 * @param {string} messageFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1949why, one step back1949 * @param {object} [errorOptions]Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1950–1954why, one step back1950 * @param {string} [errorOptions.code] - an id string representing the error1951 * @param {number} [errorOptions.exitCode] - used with process.exit1952 */1953 error(message, errorOptions) {1954 // output handlingReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1955–1958why, one step back1955 this._outputConfiguration.outputError(1956 `${message}\n`,1957 this._outputConfiguration.writeErr,1958 );Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1959–1976why, one step back1959 if (typeof this._showHelpAfterError === 'string') {1960 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1961 } else if (this._showHelpAfterError) {1962 this._outputConfiguration.writeErr('\n');1963 this.outputHelp({ error: true });1964 }19651966 // exit handling1967 const config = errorOptions || {};1968 const exitCode = config.exitCode || 1;1969 const code = config.code || 'commander.error';1970 this._exit(exitCode, code, message);1971 }19721973 /**1974 * Apply any option related environment variables, if option does1975 * not have a value from cli or client code.1976 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1977why, one step back1977 * @privateDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1978–1983why, one step back1978 */1979 _parseOptionsEnv() {1980 this.options.forEach((option) => {1981 if (option.envVar && option.envVar in process.env) {1982 const optionKey = option.attributeName();1983 // Priority check. Do not overwrite cli or options from unknown source (client-code).Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1984–1991why, one step back1984 if (1985 this.getOptionValue(optionKey) === undefined ||1986 ['default', 'config', 'env'].includes(1987 this.getOptionValueSource(optionKey),1988 )1989 ) {1990 if (option.required || option.optional) {1991 // option can take a valueDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1992–1993why, one step back1992 // keep very simple, optional always takes value1993 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1994–1995why, one step back1994 } else {1995 // booleanDeprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18
lines 1996–2001why, one step back1996 // keep very simple, only care that envVar defined and not the value1997 this.emit(`optionEnv:${option.name()}`);1998 }1999 }2000 }The first 2,000 of 2,792 lines.