Skip to content
Myr

command.js

This file

Path

lib/command.js

2,780 lines · 85.3 KiB · JavaScript

Last changed by

List excess arguments in error message (#2384)stiffbefore adoption2e96cd3

History of this file

Take 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 back
1const EventEmitter = require('node:events').EventEmitter;
2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 6–8why, one step back
6
7const { 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 back
9const { Help, stripColor } = require('./help.js');

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 10why, one step back
10const { Option, DualOptions } = require('./option.js');

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 11–27why, one step back
11const { suggestSimilar } = require('./suggestSimilar');
1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 /** @type {Command[]} */23 this.commands = [];24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;

Disallow excess arguments (#2223)John Geebefore adoption58c28eb

line 28why, one step back
28 this._allowExcessArguments = false;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 29why, one step back
29 /** @type {Argument[]} */

Add public Arguments property (#2010)John Geebefore adoption7d23437

lines 30–31why, one step back
30 this.registeredArguments = [];
31 this._args = this.registeredArguments; // deprecated old name

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 32–38why, one step back
32 /** @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 back
39 this._optionValueSources = {}; // default, env, cli etc

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 40–49why, one step back
40 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 back
50 this._summary = '';

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 51–54why, one step back
51 this._argsDescription = undefined; // legacy
52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arrays

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 55why, one step back
55 /** @type {(boolean | string)} */

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 56–57why, one step back
56 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 back
58 this._savedState = null; // used in save/restoreStateBeforeParse

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 59why, one step back
59

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 60why, one step back
60 // see configureOutput() for docs

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 61–63why, one step back
61 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 back
64 outputError: (str, write) => write(str),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 65–68why, one step back
65 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 back
69 getOutHasColors: () =>
70 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),71 getErrHasColors: () =>72 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),73 stripColor: (str) => stripColor(str),

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 74–76why, one step back
74 };
7576 this._hidden = false;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 77–81why, one step back
77 /** @type {(Option | null | undefined)} */
78 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.79 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80 /** @type {Command} */81 this._helpCommand = undefined; // lazy initialised, inherited

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 82why, one step back
82 this._helpConfiguration = {};

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

lines 83–88why, one step back
83 /** @type {string | undefined} */
84 this._helpGroupHeading = undefined; // soft initialised when added to parent85 /** @type {string | undefined} */86 this._defaultCommandGroup = undefined;87 /** @type {string | undefined} */88 this._defaultOptionGroup = undefined;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 89–100why, one step back
89 }
9091 /**92 * Copy settings that are useful to have in common across root command and subcommands.93 *94 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)95 *96 * @param {Command} sourceCommand97 * @return {Command} `this` command for chaining98 */99 copyInheritedSettings(sourceCommand) {100 this._outputConfiguration = sourceCommand._outputConfiguration;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 101–102why, one step back
101 this._helpOption = sourceCommand._helpOption;
102 this._helpCommand = sourceCommand._helpCommand;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 103–105why, one step back
103 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 back
106 this._combineFlagAndOptionalValue =
107 sourceCommand._combineFlagAndOptionalValue;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 108–116why, one step back
108 this._allowExcessArguments = sourceCommand._allowExcessArguments;
109 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;110 this._showHelpAfterError = sourceCommand._showHelpAfterError;111 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;112113 return this;114 }115116 /**

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 117why, one step back
117 * @returns {Command[]}

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 118why, one step back
118 * @private

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 119–122why, one step back
119 */
120121 _getCommandAndAncestors() {122 const result = [];

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 123why, one step back
123 // eslint-disable-next-line @typescript-eslint/no-this-alias

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 124–130why, one step back
124 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 back
131 * Define a command.
132 *133 * There are two styles of command: pay attention to where to put the description.134 *135 * @example136 * // Command implemented using action handler (description is supplied separately to `.command`)137 * program138 * .command('clone <source> [destination]')139 * .description('clone a repository into a newly created directory')140 * .action((source, destination) => {141 * console.log('clone command called');142 * });143 *144 * // Command implemented using separate executable file (description is second parameter to `.command`)145 * program146 * .command('start <service>', 'start named service')147 * .command('stop [service]', 'stop named service, or all if no name supplied');148 *149 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 150–151why, one step back
150 * @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 back
152 * @return {Command} returns new command for action handler, or `this` for executable command
153 */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 back
174 this._registerCommand(cmd);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 175–210why, one step back
175 cmd.parent = this;
176 cmd.copyInheritedSettings(this);177178 if (desc) return this;179 return cmd;180 }181182 /**183 * Factory routine to create a new unattached command.184 *185 * See .command() for creating an attached subcommand, which uses this routine to186 * create the command. You can override createCommand to customise subcommands.187 *188 * @param {string} [name]189 * @return {Command} new command190 */191192 createCommand(name) {193 return new Command(name);194 }195196 /**197 * You can customise the help with a subclass of Help by overriding createHelp,198 * or by overriding Help properties using configureHelp().199 *200 * @return {Help}201 */202203 createHelp() {204 return Object.assign(new Help(), this.configureHelp());205 }206207 /**208 * You can customise the help by overriding Help properties using configureHelp(),209 * or with a subclass of Help by overriding createHelp().210 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 211–212why, one step back
211 * @param {object} [configuration] - configuration options
212 * @return {(Command | object)} `this` command for chaining, or stored configuration

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 213–227why, one step back
213 */
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 back
228 * // change how output being written, defaults to stdout and stderr

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 229–230why, one step back
229 * writeOut(str)
230 * writeErr(str)

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 231–233why, one step back
231 * // change how output being written for errors, defaults to writeErr
232 * outputError(str, write) // used for displaying errors and not used for displaying help233 * // specify width for wrapping help

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 234–235why, one step back
234 * getOutHelpWidth()
235 * getErrHelpWidth()

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 236–238why, one step back
236 * // color support, currently only used with Help
237 * getOutHasColors()238 * getErrHasColors()

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

line 239why, one step back
239 * stripColor() // used to remove ANSI escape codes if output does not have colors

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 240why, one step back
240 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 241–242why, one step back
241 * @param {object} [configuration] - configuration options
242 * @return {(Command | object)} `this` command for chaining, or stored configuration

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 243–247why, one step back
243 */
244245 configureOutput(configuration) {246 if (configuration === undefined) return this._outputConfiguration;247

Make .configureOutput() create copy of settings instead of in-place change (#2350)John Geebefore adoption68199e6

lines 248–252why, one step back
248 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 back
253 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 back
259 * @param {(boolean|string)} [displayHelp]

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 260–284why, one step back
260 * @return {Command} `this` command for chaining
261 */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 subcommand

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 285why, one step back
285 * @param {object} [opts] - configuration options

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 286–298why, one step back
286 * @return {Command} `this` command for chaining
287 */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 implementation298

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 299why, one step back
299 this._registerCommand(cmd);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 300why, one step back
300 cmd.parent = this;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 301–302why, one step back
301 cmd._checkForBrokenPassThrough();
302

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 303–332why, one step back
303 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 back
333 * @param {(Function|*)} [parseArg] - custom argument processing function or default value

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 334–336why, one step back
334 * @param {*} [defaultValue]
335 * @return {Command} `this` command for chaining336 */

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

line 337why, one step back
337 argument(name, description, parseArg, defaultValue) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 338why, one step back
338 const argument = this.createArgument(name, description);

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

lines 339–340why, one step back
339 if (typeof parseArg === 'function') {
340 argument.default(defaultValue).argParser(parseArg);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 341why, one step back
341 } else {

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

line 342why, one step back
342 argument.default(parseArg);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 343–360why, one step back
343 }
344 this.addArgument(argument);345 return this;346 }347348 /**349 * Define argument syntax for command, adding multiple at once (without descriptions).350 *351 * See also .argument().352 *353 * @example354 * program.arguments('<cmd> [env]');355 *356 * @param {string} names357 * @return {Command} `this` command for chaining358 */359360 arguments(names) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 361–366why, one step back
361 names
362 .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 back
367 return this;
368 }369370 /**371 * Define argument syntax for command, adding a prepared argument.372 *373 * @param {Argument} argument374 * @return {Command} `this` command for chaining375 */376 addArgument(argument) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 377why, one step back
377 const previousArgument = this.registeredArguments.slice(-1)[0];

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 378why, one step back
378 if (previousArgument && previousArgument.variadic) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 379–381why, one step back
379 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 back
382 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 383–390why, one step back
383 if (
384 argument.required &&385 argument.defaultValue !== undefined &&386 argument.parseArg === undefined387 ) {388 throw new Error(389 `a default value for a required argument is never used: '${argument.name()}'`,390 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 391why, one step back
391 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 392why, one step back
392 this.registeredArguments.push(argument);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 393–396why, one step back
393 return this;
394 }395396 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 397why, one step back
397 * 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 back
398 *

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 399why, one step back
399 * @example

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 400–403why, one step back
400 * 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 subcommands

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 404why, one step back
404 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 405–406why, one step back
405 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
406 * @param {string} [description] - custom description

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 407–409why, one step back
407 * @return {Command} `this` command for chaining
408 */409

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 410–412why, one step back
410 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 back
413 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 back
417 return this;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 418why, one step back
418 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 419why, one step back
419

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

lines 420–421why, one step back
420 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 back
422 const helpDescription = description ?? 'display help for command';
423424 const helpCommand = this.createCommand(helpName);425 helpCommand.helpOption(false);426 if (helpArgs) helpCommand.arguments(helpArgs);427 if (helpDescription) helpCommand.description(helpDescription);428429 this._addImplicitHelpCommand = true;430 this._helpCommand = helpCommand;

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

lines 431–432why, one step back
431 // init group unless lazy create
432 if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 433why, one step back
433

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 434–437why, one step back
434 return this;
435 }436437 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 438–442why, one step back
438 * Add prepared custom help command.
439 *440 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`441 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only442 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 443why, one step back
443 */

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 444–450why, one step back
444 addHelpCommand(helpCommand, deprecatedDescription) {
445 // If not passed an object, call through to helpCommand for backwards compatibility,446 // as addHelpCommand was originally used like helpCommand is now.447 if (typeof helpCommand !== 'object') {448 this.helpCommand(helpCommand, deprecatedDescription);449 return this;450 }

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 451why, one step back
451

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 452–453why, one step back
452 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 back
454 this._initCommandGroup(helpCommand);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 455–464why, one step back
455 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 back
465 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 back
470
471 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 back
476 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 477why, one step back
477 return null;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 478–488why, one step back
478 }
479480 /**481 * Add hook for life cycle event.482 *483 * @param {string} event484 * @param {Function} listener485 * @return {Command} `this` command for chaining486 */487488 hook(event, listener) {

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

line 489why, one step back
489 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 490–530why, one step back
490 if (!allowedValues.includes(event)) {
491 throw new Error(`Unexpected value for event passed to hook : '${event}'.492Expecting one of '${allowedValues.join("', '")}'`);493 }494 if (this._lifeCycleHooks[event]) {495 this._lifeCycleHooks[event].push(listener);496 } else {497 this._lifeCycleHooks[event] = [listener];498 }499 return this;500 }501502 /**503 * Register callback to use as replacement for calling process.exit.504 *505 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing506 * @return {Command} `this` command for chaining507 */508509 exitOverride(fn) {510 if (fn) {511 this._exitCallback = fn;512 } else {513 this._exitCallback = (err) => {514 if (err.code !== 'commander.executeSubCommandAsync') {515 throw err;516 } else {517 // Async callback from spawn events, not useful to throw.518 }519 };520 }521 return this;522 }523524 /**525 * Call process.exit, and _exitCallback if defined.526 *527 * @param {number} exitCode exit code for using with process.exit528 * @param {string} code an id string representing the error529 * @param {string} message human-readable description of the error530 * @return never

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 531why, one step back
531 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 532–559why, one step back
532 */
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 back
560 const expectedArgsCount = this.registeredArguments.length;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 561–590why, one step back
561 const actionArgs = args.slice(0, expectedArgsCount);
562 if (this._storeOptionsAsProperties) {563 actionArgs[expectedArgsCount] = this; // backwards compatible "options"564 } else {565 actionArgs[expectedArgsCount] = this.opts();566 }567 actionArgs.push(this);568569 return fn.apply(this, actionArgs);570 };571 this._actionHandler = listener;572 return this;573 }574575 /**576 * Factory routine to create a new unattached option.577 *578 * See .option() for creating an attached option, which uses this routine to579 * create the option. You can override createOption to return a custom option.580 *581 * @param {string} flags582 * @param {string} [description]583 * @return {Option} new option584 */585586 createOption(flags, description) {587 return new Option(flags, description);588 }589590 /**

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

lines 591–592why, one step back
591 * Wrap parseArgs to catch 'commander.invalidArgument'.
592 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 593why, one step back
593 * @param {(Option | Argument)} target

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 594why, one step back
594 * @param {string} value

Replace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6

line 595why, one step back
595 * @param {*} previous

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 596why, one step back
596 * @param {string} invalidArgumentMessage

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 597why, one step back
597 * @private

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

lines 598–612why, one step back
598 */
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 back
613 * Check for option flag conflicts.
614 * Register option if no conflicts found, or throw on conflict.615 *616 * @param {Option} option

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 617why, one step back
617 * @private

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 618–620why, one step back
618 */
619620 _registerOption(option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 621–622why, one step back
621 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 back
623 (option.long && this._findOption(option.long));
624 if (matchingOption) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 625–628why, one step back
625 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 back
629 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
630- already used by option '${matchingOption.flags}'`);631 }632

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

line 633why, one step back
633 this._initOptionGroup(option);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 634–641why, one step back
634 this.options.push(option);
635 }636637 /**638 * Check for command name and alias conflicts with existing commands.639 * Register command if no conflicts found, or throw on conflict.640 *641 * @param {Command} command

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 642why, one step back
642 * @private

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 643–649why, one step back
643 */
644645 _registerCommand(command) {646 const knownBy = (cmd) => {647 return [cmd.name()].concat(cmd.aliases());648 };649

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 650–652why, one step back
650 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 back
653 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 back
656 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 back
659 }
660

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

line 661why, one step back
661 this._initCommandGroup(command);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 662–665why, one step back
662 this.commands.push(command);
663 }664665 /**

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 666–671why, one step back
666 * 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 back
672 this._registerOption(option);
673

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 674–681why, one step back
674 const oname = option.name();
675 const name = option.attributeName();676677 // store default value678 if (option.negate) {679 // --no-foo is special and defaults foo to true, unless a --foo option is already defined680 const positiveLongFlag = option.long.replace(/^--no-/, '--');681 if (!this._findOption(positiveLongFlag)) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 682–686why, one step back
682 this.setOptionValueWithSource(
683 name,684 option.defaultValue === undefined ? true : option.defaultValue,685 'default',686 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 687–702why, one step back
687 }
688 } else if (option.defaultValue !== undefined) {689 this.setOptionValueWithSource(name, option.defaultValue, 'default');690 }691692 // handler for cli and env supplied values693 const handleOptionValue = (val, invalidValueMessage, valueSource) => {694 // val is null for optional option used without an optional-argument.695 // val is undefined for boolean and negated option.696 if (val == null && option.presetArg !== undefined) {697 val = option.presetArg;698 }699700 // custom processing701 const oldValue = this.getOptionValue(name);702 if (val !== null && option.parseArg) {

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 703why, one step back
703 val = this._callParseArg(option, val, oldValue, invalidValueMessage);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 704–738why, one step back
704 } else if (val !== null && option.variadic) {
705 val = option._concatValue(val, oldValue);706 }707708 // Fill-in appropriate missing values. Long winded but easy to follow.709 if (val == null) {710 if (option.negate) {711 val = false;712 } else if (option.isBoolean() || option.optional) {713 val = true;714 } else {715 val = ''; // not normal, parseArg might have failed or be a mock function for testing716 }717 }718 this.setOptionValueWithSource(name, val, valueSource);719 };720721 this.on('option:' + oname, (val) => {722 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;723 handleOptionValue(val, invalidValueMessage, 'cli');724 });725726 if (option.envVar) {727 this.on('optionEnv:' + oname, (val) => {728 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;729 handleOptionValue(val, invalidValueMessage, 'env');730 });731 }732733 return this;734 }735736 /**737 * Internal implementation shared by .option() and .requiredOption()738 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 739why, one step back
739 * @return {Command} `this` command for chaining

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 740why, one step back
740 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 741–743why, one step back
741 */
742 _optionEx(config, flags, description, fn, defaultValue) {743 if (typeof flags === 'object' && flags instanceof Option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 744–746why, one step back
744 throw new Error(
745 'To add an Option object use addOption() instead of option() or requiredOption()',746 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 747–767why, one step back
747 }
748 const option = this.createOption(flags, description);749 option.makeOptionMandatory(!!config.mandatory);750 if (typeof fn === 'function') {751 option.default(defaultValue).argParser(fn);752 } else if (fn instanceof RegExp) {753 // deprecated754 const regex = fn;755 fn = (val, def) => {756 const m = regex.exec(val);757 return m ? m[0] : def;758 };759 option.default(defaultValue).argParser(fn);760 } else {761 option.default(fn);762 }763764 return this.addOption(option);765 }766767 /**

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 768why, one step back
768 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 769why, one step back
769 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 770–771why, one step back
770 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
771 * option-argument is indicated by `<>` and an optional option-argument by `[]`.

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 772why, one step back
772 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 773why, one step back
773 * See the README for more details, and see also addOption() and requiredOption().

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 774–775why, one step back
774 *
775 * @example

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 776–777why, one step back
776 * program
777 * .option('-p, --pepper', 'add pepper')

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

line 778why, one step back
778 * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 779–780why, one step back
779 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
780 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 781–783why, one step back
781 *
782 * @param {string} flags783 * @param {string} [description]

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 784why, one step back
784 * @param {(Function|*)} [parseArg] - custom option processing function or default value

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 785–788why, one step back
785 * @param {*} [defaultValue]
786 * @return {Command} `this` command for chaining787 */788

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 789–790why, one step back
789 option(flags, description, parseArg, defaultValue) {
790 return this._optionEx({}, flags, description, parseArg, defaultValue);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 791–793why, one step back
791 }
792793 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 794–804why, one step back
794 * Add a required option which must have a value after parsing. This usually means
795 * the option must be specified on the command line. (Otherwise the same as .option().)796 *797 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.798 *799 * @param {string} flags800 * @param {string} [description]801 * @param {(Function|*)} [parseArg] - custom option processing function or default value802 * @param {*} [defaultValue]803 * @return {Command} `this` command for chaining804 */

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 805why, one step back
805

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 806why, one step back
806 requiredOption(flags, description, parseArg, defaultValue) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 807–813why, one step back
807 return this._optionEx(
808 { mandatory: true },809 flags,810 description,811 parseArg,812 defaultValue,813 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 814–823why, one step back
814 }
815816 /**817 * Alter parsing of short flags with optional values.818 *819 * @example820 * // for `.option('-f,--flag [value]'):821 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour822 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`823 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 824–825why, one step back
824 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
825 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 826–834why, one step back
826 */
827 combineFlagAndOptionalValue(combine = true) {828 this._combineFlagAndOptionalValue = !!combine;829 return this;830 }831832 /**833 * Allow unknown options on the command line.834 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 835–836why, one step back
835 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
836 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 837–845why, one step back
837 */
838 allowUnknownOption(allowUnknown = true) {839 this._allowUnknownOption = !!allowUnknown;840 return this;841 }842843 /**844 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.845 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 846–847why, one step back
846 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
847 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 848–858why, one step back
848 */
849 allowExcessArguments(allowExcess = true) {850 this._allowExcessArguments = !!allowExcess;851 return this;852 }853854 /**855 * Enable positional options. Positional means global options are specified before subcommands which lets856 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.857 * The default behaviour is non-positional and global options may appear anywhere on the command line.858 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 859–860why, one step back
859 * @param {boolean} [positional]
860 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 861–872why, one step back
861 */
862 enablePositionalOptions(positional = true) {863 this._enablePositionalOptions = !!positional;864 return this;865 }866867 /**868 * Pass through options that come after command-arguments rather than treat them as command-options,869 * so actual command-options come before command-arguments. Turning this on for a subcommand requires870 * positional options to have been enabled on the program (parent commands).871 * The default behaviour is non-positional and options may appear before or after command-arguments.872 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 873–874why, one step back
873 * @param {boolean} [passThrough] for unknown options.
874 * @return {Command} `this` command for chaining

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 875–877why, one step back
875 */
876 passThroughOptions(passThrough = true) {877 this._passThroughOptions = !!passThrough;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 878why, one step back
878 this._checkForBrokenPassThrough();

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 879–882why, one step back
879 return this;
880 }881882 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 883–886why, one step back
883 * @private
884 */885886 _checkForBrokenPassThrough() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 887–894why, one step back
887 if (
888 this.parent &&889 this._passThroughOptions &&890 !this.parent._enablePositionalOptions891 ) {892 throw new Error(893 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,894 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 895–898why, one step back
895 }
896 }897898 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 899–904why, one step back
899 * Whether to store option values as properties on command object,
900 * or store separately (specify false). In both cases the option values can be accessed using .opts().901 *902 * @param {boolean} [storeAsProperties=true]903 * @return {Command} `this` command for chaining904 */

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 905–909why, one step back
905
906 storeOptionsAsProperties(storeAsProperties = true) {907 if (this.options.length) {908 throw new Error('call .storeOptionsAsProperties() before adding options');909 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 910why, one step back
910 if (Object.keys(this._optionValues).length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 911–913why, one step back
911 throw new Error(
912 'call .storeOptionsAsProperties() before setting option values',913 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 914why, one step back
914 }

Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e

line 915why, one step back
915 this._storeOptionsAsProperties = !!storeAsProperties;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 916–922why, one step back
916 return this;
917 }918919 /**920 * Retrieve option value.921 *922 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 923why, one step back
923 * @return {object} value

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 924–936why, one step back
924 */
925926 getOptionValue(key) {927 if (this._storeOptionsAsProperties) {928 return this[key];929 }930 return this._optionValues[key];931 }932933 /**934 * Store option value.935 *936 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 937why, one step back
937 * @param {object} value

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 938–941why, one step back
938 * @return {Command} `this` command for chaining
939 */940941 setOptionValue(key, value) {

setOptionValue should clear option source (#1795)John Geebefore adoption84d9201

line 942why, one step back
942 return this.setOptionValueWithSource(key, value, undefined);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 943–945why, one step back
943 }
944945 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 946–948why, one step back
946 * Store option value and where the value came from.
947 *948 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 949why, one step back
949 * @param {object} value

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 950–952why, one step back
950 * @param {string} source - expected values are default/config/env/cli/implied
951 * @return {Command} `this` command for chaining952 */

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 953–954why, one step back
953
954 setOptionValueWithSource(key, value, source) {

setOptionValue should clear option source (#1795)John Geebefore adoption84d9201

lines 955–959why, one step back
955 if (this._storeOptionsAsProperties) {
956 this[key] = value;957 } else {958 this._optionValues[key] = value;959 }

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 960–964why, one step back
960 this._optionValueSources[key] = source;
961 return this;962 }963964 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 965–970why, one step back
965 * Get source of option value.
966 * Expected values are default | config | env | cli | implied967 *968 * @param {string} key969 * @return {string}970 */

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 971–976why, one step back
971
972 getOptionValueSource(key) {973 return this._optionValueSources[key];974 }975976 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 977–982why, one step back
977 * Get source of option value. See also .optsWithGlobals().
978 * Expected values are default | config | env | cli | implied979 *980 * @param {string} key981 * @return {string}982 */

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 983–986why, one step back
983
984 getOptionValueSourceWithGlobals(key) {985 // global overwrites local, like optsWithGlobals986 let source;

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 987why, one step back
987 this._getCommandAndAncestors().forEach((cmd) => {

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 988–995why, one step back
988 if (cmd.getOptionValueSource(key) !== undefined) {
989 source = cmd.getOptionValueSource(key);990 }991 });992 return source;993 }994995 /**

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 996–998why, one step back
996 * Get user arguments from implied or explicit arguments.
997 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.998 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 999why, one step back
999 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1000–1007why, one step back
1000 */
10011002 _prepareUserArgs(argv, parseOptions) {1003 if (argv !== undefined && !Array.isArray(argv)) {1004 throw new Error('first parameter to parse must be array or undefined');1005 }1006 parseOptions = parseOptions || {};1007

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1008–1010why, one step back
1008 // auto-detect argument conventions if nothing supplied
1009 if (argv === undefined && parseOptions.from === undefined) {1010 if (process.versions?.electron) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1011–1012why, one step back
1011 parseOptions.from = 'electron';
1012 }

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1013–1022why, one step back
1013 // check node specific options for scenarios where user CLI args follow executable without scriptname
1014 const execArgv = process.execArgv ?? [];1015 if (1016 execArgv.includes('-e') ||1017 execArgv.includes('--eval') ||1018 execArgv.includes('-p') ||1019 execArgv.includes('--print')1020 ) {1021 parseOptions.from = 'eval'; // internal usage, not documented1022 }

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1023why, one step back
1023 }

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1024–1028why, one step back
1024
1025 // default to using process.argv1026 if (argv === undefined) {1027 argv = process.argv;1028 }

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1029–1030why, one step back
1029 this.rawArgs = argv.slice();
1030

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1031why, one step back
1031 // extract the user args and scriptPath

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1032–1039why, one step back
1032 let userArgs;
1033 switch (parseOptions.from) {1034 case undefined:1035 case 'node':1036 this._scriptPath = argv[1];1037 userArgs = argv.slice(2);1038 break;1039 case 'electron':

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 1040why, one step back
1040 // @ts-ignore: because defaultApp is an unknown property

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1041–1050why, one step back
1041 if (process.defaultApp) {
1042 this._scriptPath = argv[1];1043 userArgs = argv.slice(2);1044 } else {1045 userArgs = argv.slice(1);1046 }1047 break;1048 case 'user':1049 userArgs = argv.slice(0);1050 break;

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1051–1053why, one step back
1051 case 'eval':
1052 userArgs = argv.slice(1);1053 break;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1054why, one step back
1054 default:

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1055–1057why, one step back
1055 throw new Error(
1056 `unexpected parse option { from: '${parseOptions.from}' }`,1057 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1058–1060why, one step back
1058 }
10591060 // Find default name for program from arguments.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1061–1062why, one step back
1061 if (!this._name && this._scriptPath)
1062 this.nameFromFilename(this._scriptPath);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1063–1070why, one step back
1063 this._name = this._name || 'program';
10641065 return userArgs;1066 }10671068 /**1069 * Parse `argv`, setting options and invoking commands when defined.1070 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1071why, one step back
1071 * Use parseAsync instead of parse if any of your action handlers are async.

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1072why, one step back
1072 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1073–1079why, one step back
1073 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1074 *1075 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1076 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1077 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1078 * - `'user'`: just user arguments1079 *

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1080why, one step back
1080 * @example

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1081–1082why, one step back
1081 * program.parse(); // parse process.argv and auto-detect electron and special node flags
1082 * program.parse(process.argv); // assume argv[0] is app and argv[1] is script

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1083–1084why, one step back
1083 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1084 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 1085–1087why, one step back
1085 * @param {string[]} [argv] - optional, defaults to process.argv
1086 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1087 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1088–1091why, one step back
1088 * @return {Command} `this` command for chaining
1089 */10901091 parse(argv, parseOptions) {

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1092why, one step back
1092 this._prepareForParse();

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1093–1101why, one step back
1093 const userArgs = this._prepareUserArgs(argv, parseOptions);
1094 this._parseCommand([], userArgs);10951096 return this;1097 }10981099 /**1100 * Parse `argv`, setting options and invoking commands when defined.1101 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1102why, one step back
1102 * 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 1103why, one step back
1103 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1104–1107why, one step back
1104 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1105 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1106 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1107 * - `'user'`: just user arguments

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1108–1109why, one step back
1108 *
1109 * @example

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1110–1111why, one step back
1110 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1111 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1112–1114why, one step back
1112 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1113 *1114 * @param {string[]} [argv]

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1115why, one step back
1115 * @param {object} [parseOptions]

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1116why, one step back
1116 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1117–1120why, one step back
1117 * @return {Promise}
1118 */11191120 async parseAsync(argv, parseOptions) {

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1121why, one step back
1121 this._prepareForParse();

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1122–1127why, one step back
1122 const userArgs = this._prepareUserArgs(argv, parseOptions);
1123 await this._parseCommand([], userArgs);11241125 return this;1126 }1127

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1128–1135why, one step back
1128 _prepareForParse() {
1129 if (this._savedState === null) {1130 this.saveStateBeforeParse();1131 } else {1132 this.restoreStateBeforeParse();1133 }1134 }1135

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1136why, one step back
1136 /**

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1137–1177why, one step back
1137 * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1138 * Not usually called directly, but available for subclasses to save their custom state.1139 *1140 * This is called in a lazy way. Only commands used in parsing chain will have state saved.1141 */1142 saveStateBeforeParse() {1143 this._savedState = {1144 // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1145 _name: this._name,1146 // option values before parse have default values (including false for negated options)1147 // shallow clones1148 _optionValues: { ...this._optionValues },1149 _optionValueSources: { ...this._optionValueSources },1150 };1151 }11521153 /**1154 * Restore state before parse for calls after the first.1155 * Not usually called directly, but available for subclasses to save their custom state.1156 *1157 * This is called in a lazy way. Only commands used in parsing chain will have state restored.1158 */1159 restoreStateBeforeParse() {1160 if (this._storeOptionsAsProperties)1161 throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1162- either make a new Command for each call to parse, or stop storing options as properties`);11631164 // clear state from _prepareUserArgs1165 this._name = this._savedState._name;1166 this._scriptPath = null;1167 this.rawArgs = [];1168 // clear state from setOptionValueWithSource1169 this._optionValues = { ...this._savedState._optionValues };1170 this._optionValueSources = { ...this._savedState._optionValueSources };1171 // clear state from _parseCommand1172 this.args = [];1173 // clear state from _processArguments1174 this.processedArgs = [];1175 }11761177 /**

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1178–1197why, one step back
1178 * Throw if expected executable is missing. Add lots of help for author.
1179 *1180 * @param {string} executableFile1181 * @param {string} executableDir1182 * @param {string} subcommandName1183 */1184 _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1185 if (fs.existsSync(executableFile)) return;11861187 const executableDirMessage = executableDir1188 ? `searched for local subcommand relative to directory '${executableDir}'`1189 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1190 const executableMissing = `'${executableFile}' does not exist1191 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1192 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1193 - ${executableDirMessage}`;1194 throw new Error(executableMissing);1195 }11961197 /**

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1198–1199why, one step back
1198 * Execute a sub-command executable.
1199 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1200why, one step back
1200 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1201–1216why, one step back
1201 */
12021203 _executeSubCommand(subcommand, args) {1204 args = args.slice();1205 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1206 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12071208 function findFile(baseDir, baseName) {1209 // Look for specified file1210 const localBin = path.resolve(baseDir, baseName);1211 if (fs.existsSync(localBin)) return localBin;12121213 // Stop looking if candidate already has an expected extension.1214 if (sourceExt.includes(path.extname(baseName))) return undefined;12151216 // Try all the extensions.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1217–1219why, one step back
1217 const foundExt = sourceExt.find((ext) =>
1218 fs.existsSync(`${localBin}${ext}`),1219 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1220–1229why, one step back
1220 if (foundExt) return `${localBin}${foundExt}`;
12211222 return undefined;1223 }12241225 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1226 this._checkForMissingMandatoryOptions();1227 this._checkForConflictingOptions();12281229 // executableFile and executableDir might be full path, or just a name

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1230–1231why, one step back
1230 let executableFile =
1231 subcommand._executableFile || `${this._name}-${subcommand._name}`;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1232–1236why, one step back
1232 let executableDir = this._executableDir || '';
1233 if (this._scriptPath) {1234 let resolvedScriptPath; // resolve possible symlink for installed npm binary1235 try {1236 resolvedScriptPath = fs.realpathSync(this._scriptPath);

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 1237why, one step back
1237 } catch {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1238–1239why, one step back
1238 resolvedScriptPath = this._scriptPath;
1239 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1240–1243why, one step back
1240 executableDir = path.resolve(
1241 path.dirname(resolvedScriptPath),1242 executableDir,1243 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1244–1251why, one step back
1244 }
12451246 // Look for a local file in preference to a command in PATH.1247 if (executableDir) {1248 let localFile = findFile(executableDir, executableFile);12491250 // Legacy search using prefix of script name instead of command name1251 if (!localFile && !subcommand._executableFile && this._scriptPath) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1252–1255why, one step back
1252 const legacyName = path.basename(
1253 this._scriptPath,1254 path.extname(this._scriptPath),1255 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1256why, one step back
1256 if (legacyName !== this._name) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1257–1260why, one step back
1257 localFile = findFile(
1258 executableDir,1259 `${legacyName}-${subcommand._name}`,1260 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1261–1279why, one step back
1261 }
1262 }1263 executableFile = localFile || executableFile;1264 }12651266 launchWithNode = sourceExt.includes(path.extname(executableFile));12671268 let proc;1269 if (process.platform !== 'win32') {1270 if (launchWithNode) {1271 args.unshift(executableFile);1272 // add executable arguments to spawn1273 args = incrementNodeInspectorPort(process.execArgv).concat(args);12741275 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1276 } else {1277 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1278 }1279 } else {

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1280–1284why, one step back
1280 this._checkForMissingExecutable(
1281 executableFile,1282 executableDir,1283 subcommand._name,1284 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1285–1290why, one step back
1285 args.unshift(executableFile);
1286 // add executable arguments to spawn1287 args = incrementNodeInspectorPort(process.execArgv).concat(args);1288 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1289 }1290

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1291–1292why, one step back
1291 if (!proc.killed) {
1292 // testing mainly to avoid leak warnings during unit tests with mocked spawn

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1293–1296why, one step back
1293 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1294 signals.forEach((signal) => {1295 process.on(signal, () => {1296 if (proc.killed === false && proc.exitCode === null) {

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1297why, one step back
1297 // @ts-ignore because signals not typed to known strings

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1298–1305why, one step back
1298 proc.kill(signal);
1299 }1300 });1301 });1302 }13031304 // By default terminate process when spawned process terminates.1305 const exitCallback = this._exitCallback;

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 1306why, one step back
1306 proc.on('close', (code) => {

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1307–1310why, one step back
1307 code = code ?? 1; // code is null if spawned process terminated due to a signal
1308 if (!exitCallback) {1309 process.exit(code);1310 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1311–1317why, one step back
1311 exitCallback(
1312 new CommanderError(1313 code,1314 'commander.executeSubCommandAsync',1315 '(close)',1316 ),1317 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1318–1319why, one step back
1318 }
1319 });

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1320why, one step back
1320 proc.on('error', (err) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1321why, one step back
1321 // @ts-ignore: because err.code is an unknown property

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1322why, one step back
1322 if (err.code === 'ENOENT') {

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1323–1327why, one step back
1323 this._checkForMissingExecutable(
1324 executableFile,1325 executableDir,1326 subcommand._name,1327 );

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1328why, one step back
1328 // @ts-ignore: because err.code is an unknown property

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1329–1334why, one step back
1329 } else if (err.code === 'EACCES') {
1330 throw new Error(`'${executableFile}' not executable`);1331 }1332 if (!exitCallback) {1333 process.exit(1);1334 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1335–1339why, one step back
1335 const wrappedError = new CommanderError(
1336 1,1337 'commander.executeSubCommandAsync',1338 '(error)',1339 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1340–1349why, one step back
1340 wrappedError.nestedError = err;
1341 exitCallback(wrappedError);1342 }1343 });13441345 // Store the reference to the child process1346 this.runningCommand = proc;1347 }13481349 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1350why, one step back
1350 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1351–1356why, one step back
1351 */
13521353 _dispatchSubcommand(commandName, operands, unknown) {1354 const subCommand = this._findCommand(commandName);1355 if (!subCommand) this.help({ error: true });1356

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1357why, one step back
1357 subCommand._prepareForParse();

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1358why, one step back
1358 let promiseChain;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1359–1363why, one step back
1359 promiseChain = this._chainOrCallSubCommandHook(
1360 promiseChain,1361 subCommand,1362 'preSubcommand',1363 );

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1364why, one step back
1364 promiseChain = this._chainOrCall(promiseChain, () => {

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1365–1370why, one step back
1365 if (subCommand._executableHandler) {
1366 this._executeSubCommand(subCommand, operands.concat(unknown));1367 } else {1368 return subCommand._parseCommand(operands, unknown);1369 }1370 });

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1371why, one step back
1371 return promiseChain;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1372–1374why, one step back
1372 }
13731374 /**

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1375–1377why, one step back
1375 * Invoke help directly if possible, or dispatch if necessary.
1376 * e.g. help foo1377 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1378why, one step back
1378 * @private

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1379–1390why, one step back
1379 */
13801381 _dispatchHelpCommand(subcommandName) {1382 if (!subcommandName) {1383 this.help();1384 }1385 const subCommand = this._findCommand(subcommandName);1386 if (subCommand && !subCommand._executableHandler) {1387 subCommand.help();1388 }13891390 // Fallback to parsing the help flag to invoke the help.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1391–1395why, one step back
1391 return this._dispatchSubcommand(
1392 subcommandName,1393 [],1394 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1395 );

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1396–1398why, one step back
1396 }
13971398 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1399why, one step back
1399 * Check this.args against expected this.registeredArguments.

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1400why, one step back
1400 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1401why, one step back
1401 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1402–1405why, one step back
1402 */
14031404 _checkNumberOfArguments() {1405 // too few

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1406why, one step back
1406 this.registeredArguments.forEach((arg, i) => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1407–1411why, one step back
1407 if (arg.required && this.args[i] == null) {
1408 this.missingArgument(arg.name());1409 }1410 });1411 // too many

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1412–1415why, one step back
1412 if (
1413 this.registeredArguments.length > 0 &&1414 this.registeredArguments[this.registeredArguments.length - 1].variadic1415 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1416–1417why, one step back
1416 return;
1417 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1418why, one step back
1418 if (this.args.length > this.registeredArguments.length) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1419–1423why, one step back
1419 this._excessArguments(this.args);
1420 }1421 }14221423 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1424why, one step back
1424 * Process this.args using this.registeredArguments and save as this.processedArgs!

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1425why, one step back
1425 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1426why, one step back
1426 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1427–1433why, one step back
1427 */
14281429 _processArguments() {1430 const myParseArg = (argument, value, previous) => {1431 // Extra processing for nice error message on parsing failure.1432 let parsedValue = value;1433 if (value !== null && argument.parseArg) {

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 1434why, one step back
1434 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1435–1440why, one step back
1435 parsedValue = this._callParseArg(
1436 argument,1437 value,1438 previous,1439 invalidValueMessage,1440 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1441–1447why, one step back
1441 }
1442 return parsedValue;1443 };14441445 this._checkNumberOfArguments();14461447 const processedArgs = [];

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1448why, one step back
1448 this.registeredArguments.forEach((declaredArg, index) => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1449–1475why, one step back
1449 let value = declaredArg.defaultValue;
1450 if (declaredArg.variadic) {1451 // Collect together remaining arguments for passing together as an array.1452 if (index < this.args.length) {1453 value = this.args.slice(index);1454 if (declaredArg.parseArg) {1455 value = value.reduce((processed, v) => {1456 return myParseArg(declaredArg, v, processed);1457 }, declaredArg.defaultValue);1458 }1459 } else if (value === undefined) {1460 value = [];1461 }1462 } else if (index < this.args.length) {1463 value = this.args[index];1464 if (declaredArg.parseArg) {1465 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1466 }1467 }1468 processedArgs[index] = value;1469 });1470 this.processedArgs = processedArgs;1471 }14721473 /**1474 * Once we have a promise we chain, but call synchronously until then.1475 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1476why, one step back
1476 * @param {(Promise|undefined)} promise

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1477why, one step back
1477 * @param {Function} fn

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1478–1479why, one step back
1478 * @return {(Promise|undefined)}
1479 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1480–1493why, one step back
1480 */
14811482 _chainOrCall(promise, fn) {1483 // thenable1484 if (promise && promise.then && typeof promise.then === 'function') {1485 // already have a promise, chain callback1486 return promise.then(() => fn());1487 }1488 // callback might return a promise1489 return fn();1490 }14911492 /**1493 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1494why, one step back
1494 * @param {(Promise|undefined)} promise

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1495why, one step back
1495 * @param {string} event

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1496–1497why, one step back
1496 * @return {(Promise|undefined)}
1497 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1498–1502why, one step back
1498 */
14991500 _chainOrCallHooks(promise, event) {1501 let result = promise;1502 const hooks = [];

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 1503why, one step back
1503 this._getCommandAndAncestors()

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1504why, one step back
1504 .reverse()

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1505–1506why, one step back
1505 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1506 .forEach((hookedCommand) => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1507–1519why, one step back
1507 hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1508 hooks.push({ hookedCommand, callback });1509 });1510 });1511 if (event === 'postAction') {1512 hooks.reverse();1513 }15141515 hooks.forEach((hookDetail) => {1516 result = this._chainOrCall(result, () => {1517 return hookDetail.callback(hookDetail.hookedCommand, this);1518 });1519 });

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1520–1524why, one step back
1520 return result;
1521 }15221523 /**1524 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1525why, one step back
1525 * @param {(Promise|undefined)} promise

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1526–1527why, one step back
1526 * @param {Command} subCommand
1527 * @param {string} event

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1528–1529why, one step back
1528 * @return {(Promise|undefined)}
1529 * @private

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1530–1540why, one step back
1530 */
15311532 _chainOrCallSubCommandHook(promise, subCommand, event) {1533 let result = promise;1534 if (this._lifeCycleHooks[event] !== undefined) {1535 this._lifeCycleHooks[event].forEach((hook) => {1536 result = this._chainOrCall(result, () => {1537 return hook(this, subCommand);1538 });1539 });1540 }

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1541–1547why, one step back
1541 return result;
1542 }15431544 /**1545 * Process arguments in context of this command.1546 * Returns action result, in case it is a promise.1547 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1548why, one step back
1548 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1549–1553why, one step back
1549 */
15501551 _parseCommand(operands, unknown) {1552 const parsed = this.parseOptions(unknown);1553 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env

Add Option.implies() (#1724)John Geebefore adoptiond660967

line 1554why, one step back
1554 this._parseOptionsImplied();

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1555–1561why, one step back
1555 operands = operands.concat(parsed.operands);
1556 unknown = parsed.unknown;1557 this.args = operands.concat(unknown);15581559 if (operands && this._findCommand(operands[0])) {1560 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1561 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1562–1565why, one step back
1562 if (
1563 this._getHelpCommand() &&1564 operands[0] === this._getHelpCommand().name()1565 ) {

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

line 1566why, one step back
1566 return this._dispatchHelpCommand(operands[1]);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1567–1568why, one step back
1567 }
1568 if (this._defaultCommandName) {

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1569why, one step back
1569 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1570–1574why, one step back
1570 return this._dispatchSubcommand(
1571 this._defaultCommandName,1572 operands,1573 unknown,1574 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1575why, one step back
1575 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1576–1581why, one step back
1576 if (
1577 this.commands.length &&1578 this.args.length === 0 &&1579 !this._actionHandler &&1580 !this._defaultCommandName1581 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1582–1585why, one step back
1582 // probably missing subcommand and no handler, user needs help (and exit)
1583 this.help({ error: true });1584 }1585

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1586why, one step back
1586 this._outputHelpIfRequested(parsed.unknown);

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1587–1601why, one step back
1587 this._checkForMissingMandatoryOptions();
1588 this._checkForConflictingOptions();15891590 // We do not always call this check to avoid masking a "better" error, like unknown command.1591 const checkForUnknownOptions = () => {1592 if (parsed.unknown.length > 0) {1593 this.unknownOption(parsed.unknown[0]);1594 }1595 };15961597 const commandEvent = `command:${this.name()}`;1598 if (this._actionHandler) {1599 checkForUnknownOptions();1600 this._processArguments();1601

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1602–1603why, one step back
1602 let promiseChain;
1603 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1604–1606why, one step back
1604 promiseChain = this._chainOrCall(promiseChain, () =>
1605 this._actionHandler(this.processedArgs),1606 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1607why, one step back
1607 if (this.parent) {

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1608why, one step back
1608 promiseChain = this._chainOrCall(promiseChain, () => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1609–1611why, one step back
1609 this.parent.emit(commandEvent, operands, unknown); // legacy
1610 });1611 }

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1612–1613why, one step back
1612 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1613 return promiseChain;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1614–1619why, one step back
1614 }
1615 if (this.parent && this.parent.listenerCount(commandEvent)) {1616 checkForUnknownOptions();1617 this._processArguments();1618 this.parent.emit(commandEvent, operands, unknown); // legacy1619 } else if (operands.length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1620–1621why, one step back
1620 if (this._findCommand('*')) {
1621 // legacy default command

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1622–1646why, one step back
1622 return this._dispatchSubcommand('*', operands, unknown);
1623 }1624 if (this.listenerCount('command:*')) {1625 // skip option check, emit event for possible misspelling suggestion1626 this.emit('command:*', operands, unknown);1627 } else if (this.commands.length) {1628 this.unknownCommand();1629 } else {1630 checkForUnknownOptions();1631 this._processArguments();1632 }1633 } else if (this.commands.length) {1634 checkForUnknownOptions();1635 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1636 this.help({ error: true });1637 } else {1638 checkForUnknownOptions();1639 this._processArguments();1640 // fall through for caller to handle after calling .parse()1641 }1642 }16431644 /**1645 * Find matching command.1646 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1647why, one step back
1647 * @private

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1648why, one step back
1648 * @return {Command | undefined}

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1649–1651why, one step back
1649 */
1650 _findCommand(name) {1651 if (!name) return undefined;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1652–1654why, one step back
1652 return this.commands.find(
1653 (cmd) => cmd._name === name || cmd._aliases.includes(name),1654 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1655–1661why, one step back
1655 }
16561657 /**1658 * Return an option matching `arg` if any.1659 *1660 * @param {string} arg1661 * @return {Option}

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1662why, one step back
1662 * @package

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1663–1665why, one step back
1663 */
16641665 _findOption(arg) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1666why, one step back
1666 return this.options.find((option) => option.is(arg));

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1667–1672why, one step back
1667 }
16681669 /**1670 * Display an error message if a mandatory option does not have a value.1671 * Called after checking for help flags in leaf subcommand.1672 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1673why, one step back
1673 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1674–1677why, one step back
1674 */
16751676 _checkForMissingMandatoryOptions() {1677 // Walk up hierarchy so can call in subcommand after checking for displaying help.

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1678why, one step back
1678 this._getCommandAndAncestors().forEach((cmd) => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1679why, one step back
1679 cmd.options.forEach((anOption) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1680–1683why, one step back
1680 if (
1681 anOption.mandatory &&1682 cmd.getOptionValue(anOption.attributeName()) === undefined1683 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1684–1686why, one step back
1684 cmd.missingMandatoryOptionValue(anOption);
1685 }1686 });

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1687why, one step back
1687 });

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1688–1692why, one step back
1688 }
16891690 /**1691 * Display an error message if conflicting options are used together in this.1692 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1693why, one step back
1693 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1694–1695why, one step back
1694 */
1695 _checkForConflictingLocalOptions() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1696–1699why, one step back
1696 const definedNonDefaultOptions = this.options.filter((option) => {
1697 const optionKey = option.attributeName();1698 if (this.getOptionValue(optionKey) === undefined) {1699 return false;

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1700why, one step back
1700 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1701–1702why, one step back
1701 return this.getOptionValueSource(optionKey) !== 'default';
1702 });

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1703–1704why, one step back
1703
1704 const optionsWithConflicting = definedNonDefaultOptions.filter(

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1705why, one step back
1705 (option) => option.conflictsWith.length > 0,

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1706–1709why, one step back
1706 );
17071708 optionsWithConflicting.forEach((option) => {1709 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1710why, one step back
1710 option.conflictsWith.includes(defined.attributeName()),

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1711–1721why, one step back
1711 );
1712 if (conflictingAndDefined) {1713 this._conflictingOption(option, conflictingAndDefined);1714 }1715 });1716 }17171718 /**1719 * Display an error message if conflicting options are used together.1720 * Called after checking for help flags in leaf subcommand.1721 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1722why, one step back
1722 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1723–1725why, one step back
1723 */
1724 _checkForConflictingOptions() {1725 // Walk up hierarchy so can call in subcommand after checking for displaying help.

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1726why, one step back
1726 this._getCommandAndAncestors().forEach((cmd) => {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1727why, one step back
1727 cmd._checkForConflictingLocalOptions();

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1728why, one step back
1728 });

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1729–1733why, one step back
1729 }
17301731 /**1732 * Parse options from `argv` removing known options,1733 * and return argv split into operands and unknown arguments.

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1734–1735why, one step back
1734 *
1735 * Side effects: modifies command by storing options. Does not reset state if called again.

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1736–1744why, one step back
1736 *
1737 * Examples:1738 *1739 * argv => operands, unknown1740 * --known kkk op => [op], []1741 * op --known kkk => [op], []1742 * sub --unknown uuu op => [sub], [--unknown uuu op]1743 * sub -- --unknown uuu op => [sub --unknown uuu op], []1744 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1745–1746why, one step back
1745 * @param {string[]} argv
1746 * @return {{operands: string[], unknown: string[]}}

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1747–1758why, one step back
1747 */
17481749 parseOptions(argv) {1750 const operands = []; // operands, not options or values1751 const unknown = []; // first unknown option and remaining unknown args1752 let dest = operands;1753 const args = argv.slice();17541755 function maybeOption(arg) {1756 return arg.length > 1 && arg[0] === '-';1757 }1758

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1759–1769why, one step back
1759 const negativeNumberArg = (arg) => {
1760 // return false if not a negative number1761 if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;1762 // negative number is ok unless digit used as an option in command hierarchy1763 return !this._getCommandAndAncestors().some((cmd) =>1764 cmd.options1765 .map((opt) => opt.short)1766 .some((short) => /^-\d$/.test(short)),1767 );1768 };1769

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1770–1781why, one step back
1770 // parse options
1771 let activeVariadicOption = null;1772 while (args.length) {1773 const arg = args.shift();17741775 // literal1776 if (arg === '--') {1777 if (dest === unknown) dest.push(arg);1778 dest.push(...args);1779 break;1780 }1781

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1782–1785why, one step back
1782 if (
1783 activeVariadicOption &&1784 (!maybeOption(arg) || negativeNumberArg(arg))1785 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1786–1801why, one step back
1786 this.emit(`option:${activeVariadicOption.name()}`, arg);
1787 continue;1788 }1789 activeVariadicOption = null;17901791 if (maybeOption(arg)) {1792 const option = this._findOption(arg);1793 // recognised option, call listener to assign value with possible custom processing1794 if (option) {1795 if (option.required) {1796 const value = args.shift();1797 if (value === undefined) this.optionMissingArgument(option);1798 this.emit(`option:${option.name()}`, value);1799 } else if (option.optional) {1800 let value = null;1801 // historical behaviour is optional value is following arg unless an option

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1802–1805why, one step back
1802 if (
1803 args.length > 0 &&1804 (!maybeOption(args[0]) || negativeNumberArg(args[0]))1805 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1806–1808why, one step back
1806 value = args.shift();
1807 }1808 this.emit(`option:${option.name()}`, value);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1809–1810why, one step back
1809 } else {
1810 // boolean flag

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1811–1821why, one step back
1811 this.emit(`option:${option.name()}`);
1812 }1813 activeVariadicOption = option.variadic ? option : null;1814 continue;1815 }1816 }18171818 // Look for combo options following single dash, eat first one if known.1819 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1820 const option = this._findOption(`-${arg[1]}`);1821 if (option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1822–1825why, one step back
1822 if (
1823 option.required ||1824 (option.optional && this._combineFlagAndOptionalValue)1825 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1826–1850why, one step back
1826 // option with value following in same argument
1827 this.emit(`option:${option.name()}`, arg.slice(2));1828 } else {1829 // boolean option, emit and put back remainder of arg for further processing1830 this.emit(`option:${option.name()}`);1831 args.unshift(`-${arg.slice(2)}`);1832 }1833 continue;1834 }1835 }18361837 // Look for known long flag with value, like --foo=bar1838 if (/^--[^=]+=/.test(arg)) {1839 const index = arg.indexOf('=');1840 const option = this._findOption(arg.slice(0, index));1841 if (option && (option.required || option.optional)) {1842 this.emit(`option:${option.name()}`, arg.slice(index + 1));1843 continue;1844 }1845 }18461847 // Not a recognised option by this command.1848 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18491850 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1851–1856why, one step back
1851 // A negative number in a leaf command is not an unknown option.
1852 if (1853 dest === operands &&1854 maybeOption(arg) &&1855 !(this.commands.length === 0 && negativeNumberArg(arg))1856 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1857–1860why, one step back
1857 dest = unknown;
1858 }18591860 // If using positionalOptions, stop processing our options at subcommand.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1861–1865why, one step back
1861 if (
1862 (this._enablePositionalOptions || this._passThroughOptions) &&1863 operands.length === 0 &&1864 unknown.length === 01865 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1866–1869why, one step back
1866 if (this._findCommand(arg)) {
1867 operands.push(arg);1868 if (args.length > 0) unknown.push(...args);1869 break;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1870–1873why, one step back
1870 } else if (
1871 this._getHelpCommand() &&1872 arg === this._getHelpCommand().name()1873 ) {

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1874–1900why, one step back
1874 operands.push(arg);
1875 if (args.length > 0) operands.push(...args);1876 break;1877 } else if (this._defaultCommandName) {1878 unknown.push(arg);1879 if (args.length > 0) unknown.push(...args);1880 break;1881 }1882 }18831884 // If using passThroughOptions, stop processing options at first command-argument.1885 if (this._passThroughOptions) {1886 dest.push(arg);1887 if (args.length > 0) dest.push(...args);1888 break;1889 }18901891 // add arg1892 dest.push(arg);1893 }18941895 return { operands, unknown };1896 }18971898 /**1899 * Return an object containing local option values as key-value pairs.1900 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1901why, one step back
1901 * @return {object}

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1902–1910why, one step back
1902 */
1903 opts() {1904 if (this._storeOptionsAsProperties) {1905 // Preserve original behaviour so backwards compatible when still using properties1906 const result = {};1907 const len = this.options.length;19081909 for (let i = 0; i < len; i++) {1910 const key = this.options[i].attributeName();

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1911–1912why, one step back
1911 result[key] =
1912 key === this._versionOptionName ? this._version : this[key];

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1913–1922why, one step back
1913 }
1914 return result;1915 }19161917 return this._optionValues;1918 }19191920 /**1921 * Return an object containing merged local and global option values as key-value pairs.1922 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1923why, one step back
1923 * @return {object}

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1924–1926why, one step back
1924 */
1925 optsWithGlobals() {1926 // globals overwrite locals

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 1927why, one step back
1927 return this._getCommandAndAncestors().reduce(

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

line 1928why, one step back
1928 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1929why, one step back
1929 {},

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1930–1936why, one step back
1930 );
1931 }19321933 /**1934 * Display error message and exit (or call exitOverride).1935 *1936 * @param {string} message

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1937why, one step back
1937 * @param {object} [errorOptions]

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1938–1942why, one step back
1938 * @param {string} [errorOptions.code] - an id string representing the error
1939 * @param {number} [errorOptions.exitCode] - used with process.exit1940 */1941 error(message, errorOptions) {1942 // output handling

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1943–1946why, one step back
1943 this._outputConfiguration.outputError(
1944 `${message}\n`,1945 this._outputConfiguration.writeErr,1946 );

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1947–1964why, one step back
1947 if (typeof this._showHelpAfterError === 'string') {
1948 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1949 } else if (this._showHelpAfterError) {1950 this._outputConfiguration.writeErr('\n');1951 this.outputHelp({ error: true });1952 }19531954 // exit handling1955 const config = errorOptions || {};1956 const exitCode = config.exitCode || 1;1957 const code = config.code || 'commander.error';1958 this._exit(exitCode, code, message);1959 }19601961 /**1962 * Apply any option related environment variables, if option does1963 * not have a value from cli or client code.1964 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1965why, one step back
1965 * @private

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1966–1971why, one step back
1966 */
1967 _parseOptionsEnv() {1968 this.options.forEach((option) => {1969 if (option.envVar && option.envVar in process.env) {1970 const optionKey = option.attributeName();1971 // Priority check. Do not overwrite cli or options from unknown source (client-code).

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1972–1979why, one step back
1972 if (
1973 this.getOptionValue(optionKey) === undefined ||1974 ['default', 'config', 'env'].includes(1975 this.getOptionValueSource(optionKey),1976 )1977 ) {1978 if (option.required || option.optional) {1979 // option can take a value

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1980–1981why, one step back
1980 // keep very simple, optional always takes value
1981 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1982–1983why, one step back
1982 } else {
1983 // boolean

Deprecate multi-character short flags (#1718)John Geebefore adoptionacbbe18

lines 1984–1989why, one step back
1984 // keep very simple, only care that envVar defined and not the value
1985 this.emit(`optionEnv:${option.name()}`);1986 }1987 }1988 }1989 });

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 1990–1994why, one step back
1990 }
19911992 /**1993 * Apply any implied option values, if option is undefined or default value.1994 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1995why, one step back
1995 * @private

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 1996–1999why, one step back
1996 */
1997 _parseOptionsImplied() {1998 const dualHelper = new DualOptions(this.options);1999 const hasCustomOptionValue = (optionKey) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 2000–2003why, one step back
2000 return (

The first 2,000 of 2,780 lines.