Skip to content
Myr

command.js

This file

Path

lib/command.js

2,504 lines · 75.9 KiB · JavaScript

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than d282f20 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');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 11why, one step back
11const { suggestSimilar } = require('./suggestSimilar');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 12–21why, one step back
12
13class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 22why, one step back
22 /** @type {Command[]} */

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 23why, one step back
23 this.commands = [];

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 24why, one step back
24 /** @type {Option[]} */

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 25–28why, one step back
25 this.options = [];
26 this.parent = null;27 this._allowUnknownOption = false;28 this._allowExcessArguments = true;

Support argument processing without action handler (#1529)John Geebefore adoption4663597

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 32–35why, 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 variadic

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 36–38why, one step back
36 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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 40–43why, one step back
40 this._storeOptionsAsProperties = false;
41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 44why, one step back
44 this._executableDir = null; // custom search directory for subcommands

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 45–49why, one step back
45 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 = '';

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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)} */

Add showHelpAfterError (#1534)John Geebefore adoption082717f

line 56why, one step back
56 this._showHelpAfterError = false;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 57why, one step back
57 this._showSuggestionAfterError = true;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 58–62why, one step back
58
59 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 63–67why, one step back
63 getOutHelpWidth: () =>
64 process.stdout.isTTY ? process.stdout.columns : undefined,65 getErrHelpWidth: () =>66 process.stderr.isTTY ? process.stderr.columns : undefined,67 outputError: (str, write) => write(str),

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 68–70why, one step back
68 };
6970 this._hidden = false;

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 76–79why, one step back
76 this._helpConfiguration = {};
77 }7879 /**

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 80–84why, one step back
80 * Copy settings that are useful to have in common across root command and subcommands.
81 *82 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)83 *84 * @param {Command} sourceCommand

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 86–88why, one step back
86 */
87 copyInheritedSettings(sourceCommand) {88 this._outputConfiguration = sourceCommand._outputConfiguration;

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

lines 89–90why, one step back
89 this._helpOption = sourceCommand._helpOption;
90 this._helpCommand = sourceCommand._helpCommand;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 91–93why, one step back
91 this._helpConfiguration = sourceCommand._helpConfiguration;
92 this._exitCallback = sourceCommand._exitCallback;93 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 94–95why, one step back
94 this._combineFlagAndOptionalValue =
95 sourceCommand._combineFlagAndOptionalValue;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 96–98why, one step back
96 this._allowExcessArguments = sourceCommand._allowExcessArguments;
97 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;98 this._showHelpAfterError = sourceCommand._showHelpAfterError;

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 99why, one step back
99 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 100–104why, one step back
100
101 return this;102 }103104 /**

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

line 106why, one step back
106 * @private

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 107–110why, one step back
107 */
108109 _getCommandAndAncestors() {110 const result = [];

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

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

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 112–118why, one step back
112 for (let command = this; command; command = command.parent) {
113 result.push(command);114 }115 return result;116 }117118 /**

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 119–122why, one step back
119 * Define a command.
120 *121 * There are two styles of command: pay attention to where to put the description.122 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 123–130why, one step back
123 * @example
124 * // Command implemented using action handler (description is supplied separately to `.command`)125 * program126 * .command('clone <source> [destination]')127 * .description('clone a repository into a newly created directory')128 * .action((source, destination) => {129 * console.log('clone command called');130 * });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 131why, one step back
131 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 132–135why, one step back
132 * // Command implemented using separate executable file (description is second parameter to `.command`)
133 * program134 * .command('start <service>', 'start named service')135 * .command('stop [service]', 'stop named service, or all if no name supplied');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 136–137why, one step back
136 *
137 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`

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

line 138why, one step back
138 * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 139–152why, one step back
139 * @param {Object} [execOpts] - configuration options (for executable)
140 * @return {Command} returns new command for action handler, or `this` for executable command141 */142143 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {144 let desc = actionOptsOrExecDesc;145 let opts = execOpts;146 if (typeof desc === 'object' && desc !== null) {147 opts = desc;148 desc = null;149 }150 opts = opts || {};151 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);152

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

line 153why, one step back
153 const cmd = this.createCommand(name);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 154–161why, one step back
154 if (desc) {
155 cmd.description(desc);156 cmd._executableHandler = true;157 }158 if (opts.isDefault) this._defaultCommandName = cmd._name;159 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden160 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor161 if (args) cmd.arguments(args);

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

line 164why, one step back
164 cmd.copyInheritedSettings(this);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 165–167why, one step back
165
166 if (desc) return this;167 return cmd;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 168why, one step back
168 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 169–181why, one step back
169
170 /**171 * Factory routine to create a new unattached command.172 *173 * See .command() for creating an attached subcommand, which uses this routine to174 * create the command. You can override createCommand to customise subcommands.175 *176 * @param {string} [name]177 * @return {Command} new command178 */179180 createCommand(name) {181 return new Command(name);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 182why, one step back
182 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 183–192why, one step back
183
184 /**185 * You can customise the help with a subclass of Help by overriding createHelp,186 * or by overriding Help properties using configureHelp().187 *188 * @return {Help}189 */190191 createHelp() {192 return Object.assign(new Help(), this.configureHelp());

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 193why, one step back
193 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 194–199why, one step back
194
195 /**196 * You can customise the help by overriding Help properties using configureHelp(),197 * or with a subclass of Help by overriding createHelp().198 *199 * @param {Object} [configuration] - configuration options

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

line 200why, one step back
200 * @return {(Command|Object)} `this` command for chaining, or stored configuration

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 201–215why, one step back
201 */
202203 configureHelp(configuration) {204 if (configuration === undefined) return this._helpConfiguration;205206 this._helpConfiguration = configuration;207 return this;208 }209210 /**211 * The default output goes to stdout and stderr. You can customise this for special212 * applications. You can also customise the display of errors by overriding outputError.213 *214 * The configuration properties are all functions:215 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 216–223why, one step back
216 * // functions to change where being written, stdout and stderr
217 * writeOut(str)218 * writeErr(str)219 * // matching functions to specify width for wrapping help220 * getOutHelpWidth()221 * getErrHelpWidth()222 * // functions based on what is being written out223 * outputError(str, write) // used for displaying errors, and not used for displaying help

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 224–225why, one step back
224 *
225 * @param {Object} [configuration] - configuration options

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

line 226why, one step back
226 * @return {(Command|Object)} `this` command for chaining, or stored configuration

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 227–236why, one step back
227 */
228229 configureOutput(configuration) {230 if (configuration === undefined) return this._outputConfiguration;231232 Object.assign(this._outputConfiguration, configuration);233 return this;234 }235236 /**

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 237–238why, one step back
237 * Display the help or a custom message after an error occurs.
238 *

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

line 239why, one step back
239 * @param {(boolean|string)} [displayHelp]

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 240–248why, one step back
240 * @return {Command} `this` command for chaining
241 */242 showHelpAfterError(displayHelp = true) {243 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;244 this._showHelpAfterError = displayHelp;245 return this;246 }247248 /**

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 249–259why, one step back
249 * Display suggestion of similar commands for unknown commands, or options for unknown options.
250 *251 * @param {boolean} [displaySuggestion]252 * @return {Command} `this` command for chaining253 */254 showSuggestionAfterError(displaySuggestion = true) {255 this._showSuggestionAfterError = !!displaySuggestion;256 return this;257 }258259 /**

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 260–269why, one step back
260 * Add a prepared subcommand.
261 *262 * See .command() for creating an attached subcommand which inherits settings from its parent.263 *264 * @param {Command} cmd - new subcommand265 * @param {Object} [opts] - configuration options266 * @return {Command} `this` command for chaining267 */268269 addCommand(cmd, opts) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 270–272why, one step back
270 if (!cmd._name) {
271 throw new Error(`Command passed to .addCommand() must have a name272- specify the name in Command constructor or using .name()`);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 273–278why, one step back
273 }
274275 opts = opts || {};276 if (opts.isDefault) this._defaultCommandName = cmd._name;277 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation278

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

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

lines 281–282why, one step back
281 cmd._checkForBrokenPassThrough();
282

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 283why, one step back
283 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 284why, one step back
284 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 285–298why, one step back
285
286 /**287 * Factory routine to create a new unattached argument.288 *289 * See .argument() for creating an attached argument, which uses this routine to290 * create the argument. You can override createArgument to return a custom argument.291 *292 * @param {string} name293 * @param {string} [description]294 * @return {Argument} new argument295 */296297 createArgument(name, description) {298 return new Argument(name, description);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 299why, one step back
299 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 300–307why, one step back
300
301 /**302 * Define argument syntax for command.303 *304 * The default is that the argument is required, and you can explicitly305 * indicate this with <> around the name. Put [] around the name for an optional argument.306 *307 * @example

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 308–309why, one step back
308 * program.argument('<input-file>');
309 * program.argument('[output-file]');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 310–312why, one step back
310 *
311 * @param {string} name312 * @param {string} [description]

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

line 313why, one step back
313 * @param {(Function|*)} [fn] - custom argument processing function

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 314–333why, one step back
314 * @param {*} [defaultValue]
315 * @return {Command} `this` command for chaining316 */317 argument(name, description, fn, defaultValue) {318 const argument = this.createArgument(name, description);319 if (typeof fn === 'function') {320 argument.default(defaultValue).argParser(fn);321 } else {322 argument.default(fn);323 }324 this.addArgument(argument);325 return this;326 }327328 /**329 * Define argument syntax for command, adding multiple at once (without descriptions).330 *331 * See also .argument().332 *333 * @example

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 334why, one step back
334 * program.arguments('<cmd> [env]');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 335–340why, one step back
335 *
336 * @param {string} names337 * @return {Command} `this` command for chaining338 */339340 arguments(names) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 341–346why, one step back
341 names
342 .trim()343 .split(/ +/)344 .forEach((detail) => {345 this.argument(detail);346 });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 347why, one step back
347 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 348why, one step back
348 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 349–356why, one step back
349
350 /**351 * Define argument syntax for command, adding a prepared argument.352 *353 * @param {Argument} argument354 * @return {Command} `this` command for chaining355 */356 addArgument(argument) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 359–361why, one step back
359 throw new Error(
360 `only the last argument can be variadic '${previousArgument.name()}'`,361 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 362why, one step back
362 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 363–370why, one step back
363 if (
364 argument.required &&365 argument.defaultValue !== undefined &&366 argument.parseArg === undefined367 ) {368 throw new Error(369 `a default value for a required argument is never used: '${argument.name()}'`,370 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 371why, one step back
371 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 373–376why, one step back
373 return this;
374 }375376 /**

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

line 377why, one step back
377 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 378why, one step back
378 *

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

line 379why, one step back
379 * @example

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

lines 380–383why, one step back
380 * program.helpCommand('help [cmd]');
381 * program.helpCommand('help [cmd]', 'show help');382 * program.helpCommand(false); // suppress default help command383 * program.helpCommand(true); // add help command even if no subcommands

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 384why, one step back
384 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 387–389why, one step back
387 * @return {Command} `this` command for chaining
388 */389

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

lines 390–393why, one step back
390 helpCommand(enableOrNameAndArgs, description) {
391 if (typeof enableOrNameAndArgs === 'boolean') {392 this._addImplicitHelpCommand = enableOrNameAndArgs;393 return this;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 394why, one step back
394 }

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

lines 395–407why, one step back
395
396 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';397 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);398 const helpDescription = description ?? 'display help for command';399400 const helpCommand = this.createCommand(helpName);401 helpCommand.helpOption(false);402 if (helpArgs) helpCommand.arguments(helpArgs);403 if (helpDescription) helpCommand.description(helpDescription);404405 this._addImplicitHelpCommand = true;406 this._helpCommand = helpCommand;407

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 408why, one step back
408 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 409why, one step back
409 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 410–411why, one step back
410
411 /**

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

lines 412–416why, one step back
412 * Add prepared custom help command.
413 *414 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`415 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only416 * @return {Command} `this` command for chaining

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 417why, one step back
417 */

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

lines 418–424why, one step back
418 addHelpCommand(helpCommand, deprecatedDescription) {
419 // If not passed an object, call through to helpCommand for backwards compatibility,420 // as addHelpCommand was originally used like helpCommand is now.421 if (typeof helpCommand !== 'object') {422 this.helpCommand(helpCommand, deprecatedDescription);423 return this;424 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 425why, one step back
425

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

lines 426–437why, one step back
426 this._addImplicitHelpCommand = true;
427 this._helpCommand = helpCommand;428 return this;429 }430431 /**432 * Lazy create help command.433 *434 * @return {(Command|null)}435 * @package436 */437 _getHelpCommand() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 438–442why, one step back
438 const hasImplicitHelpCommand =
439 this._addImplicitHelpCommand ??440 (this.commands.length &&441 !this._actionHandler &&442 !this._findCommand('help'));

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

lines 443–448why, one step back
443
444 if (hasImplicitHelpCommand) {445 if (this._helpCommand === undefined) {446 this.helpCommand(undefined, undefined); // use default name and description447 }448 return this._helpCommand;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 449why, one step back
449 }

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

line 450why, one step back
450 return null;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 451why, one step back
451 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 452–461why, one step back
452
453 /**454 * Add hook for life cycle event.455 *456 * @param {string} event457 * @param {Function} listener458 * @return {Command} `this` command for chaining459 */460461 hook(event, listener) {

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 463–494why, one step back
463 if (!allowedValues.includes(event)) {
464 throw new Error(`Unexpected value for event passed to hook : '${event}'.465Expecting one of '${allowedValues.join("', '")}'`);466 }467 if (this._lifeCycleHooks[event]) {468 this._lifeCycleHooks[event].push(listener);469 } else {470 this._lifeCycleHooks[event] = [listener];471 }472 return this;473 }474475 /**476 * Register callback to use as replacement for calling process.exit.477 *478 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing479 * @return {Command} `this` command for chaining480 */481482 exitOverride(fn) {483 if (fn) {484 this._exitCallback = fn;485 } else {486 this._exitCallback = (err) => {487 if (err.code !== 'commander.executeSubCommandAsync') {488 throw err;489 } else {490 // Async callback from spawn events, not useful to throw.491 }492 };493 }494 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 495why, one step back
495 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 496–503why, one step back
496
497 /**498 * Call process.exit, and _exitCallback if defined.499 *500 * @param {number} exitCode exit code for using with process.exit501 * @param {string} code an id string representing the error502 * @param {string} message human-readable description of the error503 * @return never

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

line 504why, one step back
504 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 505–512why, one step back
505 */
506507 _exit(exitCode, code, message) {508 if (this._exitCallback) {509 this._exitCallback(new CommanderError(exitCode, code, message));510 // Expecting this line is not reached.511 }512 process.exit(exitCode);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 513why, one step back
513 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 514–517why, one step back
514
515 /**516 * Register callback `fn` for the command.517 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 518–519why, one step back
518 * @example
519 * program

Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68

lines 520–521why, one step back
520 * .command('serve')
521 * .description('start service')

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 522why, one step back
522 * .action(function() {

Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68

line 523why, one step back
523 * // do work here

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 524why, one step back
524 * });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 525–532why, one step back
525 *
526 * @param {Function} fn527 * @return {Command} `this` command for chaining528 */529530 action(fn) {531 const listener = (args) => {532 // The .action callback takes an extra parameter which is the command or options.

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 533why, one step back
533 const expectedArgsCount = this.registeredArguments.length;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 534–545why, one step back
534 const actionArgs = args.slice(0, expectedArgsCount);
535 if (this._storeOptionsAsProperties) {536 actionArgs[expectedArgsCount] = this; // backwards compatible "options"537 } else {538 actionArgs[expectedArgsCount] = this.opts();539 }540 actionArgs.push(this);541542 return fn.apply(this, actionArgs);543 };544 this._actionHandler = listener;545 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 546why, one step back
546 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 547–560why, one step back
547
548 /**549 * Factory routine to create a new unattached option.550 *551 * See .option() for creating an attached option, which uses this routine to552 * create the option. You can override createOption to return a custom option.553 *554 * @param {string} flags555 * @param {string} [description]556 * @return {Option} new option557 */558559 createOption(flags, description) {560 return new Option(flags, description);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 561why, one step back
561 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 562–563why, one step back
562
563 /**

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

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

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

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

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

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

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

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

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

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

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

line 570why, one step back
570 * @private

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

lines 571–585why, one step back
571 */
572573 _callParseArg(target, value, previous, invalidArgumentMessage) {574 try {575 return target.parseArg(value, previous);576 } catch (err) {577 if (err.code === 'commander.invalidArgument') {578 const message = `${invalidArgumentMessage} ${err.message}`;579 this.error(message, { exitCode: err.exitCode, code: err.code });580 }581 throw err;582 }583 }584585 /**

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

lines 586–593why, one step back
586 * Check for option flag conflicts.
587 * Register option if no conflicts found, or throw on conflict.588 *589 * @param {Option} option590 * @api private591 */592593 _registerOption(option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 594–595why, one step back
594 const matchingOption =
595 (option.short && this._findOption(option.short)) ||

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

lines 596–597why, one step back
596 (option.long && this._findOption(option.long));
597 if (matchingOption) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 598–601why, one step back
598 const matchingFlag =
599 option.long && this._findOption(option.long)600 ? option.long601 : option.short;

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

lines 602–621why, one step back
602 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
603- already used by option '${matchingOption.flags}'`);604 }605606 this.options.push(option);607 }608609 /**610 * Check for command name and alias conflicts with existing commands.611 * Register command if no conflicts found, or throw on conflict.612 *613 * @param {Command} command614 * @api private615 */616617 _registerCommand(command) {618 const knownBy = (cmd) => {619 return [cmd.name()].concat(cmd.aliases());620 };621

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 622–624why, one step back
622 const alreadyUsed = knownBy(command).find((name) =>
623 this._findCommand(name),624 );

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

lines 625–627why, one step back
625 if (alreadyUsed) {
626 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');627 const newCmd = knownBy(command).join('|');

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 628–630why, one step back
628 throw new Error(
629 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,630 );

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

lines 631–636why, one step back
631 }
632633 this.commands.push(command);634 }635636 /**

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 637–642why, one step back
637 * Add an option.
638 *639 * @param {Option} option640 * @return {Command} `this` command for chaining641 */642 addOption(option) {

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

lines 643–644why, one step back
643 this._registerOption(option);
644

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 645–647why, one step back
645 const oname = option.name();
646 const name = option.attributeName();647

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 648–652why, one step back
648 // store default value
649 if (option.negate) {650 // --no-foo is special and defaults foo to true, unless a --foo option is already defined651 const positiveLongFlag = option.long.replace(/^--no-/, '--');652 if (!this._findOption(positiveLongFlag)) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 653–657why, one step back
653 this.setOptionValueWithSource(
654 name,655 option.defaultValue === undefined ? true : option.defaultValue,656 'default',657 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 658why, one step back
658 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 659–660why, one step back
659 } else if (option.defaultValue !== undefined) {
660 this.setOptionValueWithSource(name, option.defaultValue, 'default');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 661–662why, one step back
661 }
662

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 663–664why, one step back
663 // handler for cli and env supplied values
664 const handleOptionValue = (val, invalidValueMessage, valueSource) => {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 665–669why, one step back
665 // val is null for optional option used without an optional-argument.
666 // val is undefined for boolean and negated option.667 if (val == null && option.presetArg !== undefined) {668 val = option.presetArg;669 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 670–671why, one step back
670
671 // custom processing

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 672why, one step back
672 const oldValue = this.getOptionValue(name);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 673why, one step back
673 if (val !== null && option.parseArg) {

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 675–678why, one step back
675 } else if (val !== null && option.variadic) {
676 val = option._concatValue(val, oldValue);677 }678

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 679–684why, one step back
679 // Fill-in appropriate missing values. Long winded but easy to follow.
680 if (val == null) {681 if (option.negate) {682 val = false;683 } else if (option.isBoolean() || option.optional) {684 val = true;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 685why, one step back
685 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 686why, one step back
686 val = ''; // not normal, parseArg might have failed or be a mock function for testing

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 687–688why, one step back
687 }
688 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 689why, one step back
689 this.setOptionValueWithSource(name, val, valueSource);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 690–694why, one step back
690 };
691692 this.on('option:' + oname, (val) => {693 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;694 handleOptionValue(val, invalidValueMessage, 'cli');

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 695–696why, one step back
695 });
696

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 697–703why, one step back
697 if (option.envVar) {
698 this.on('optionEnv:' + oname, (val) => {699 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;700 handleOptionValue(val, invalidValueMessage, 'env');701 });702 }703

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 704–709why, one step back
704 return this;
705 }706707 /**708 * Internal implementation shared by .option() and .requiredOption()709 *

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

line 710why, one step back
710 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 711–712why, one step back
711 */
712 _optionEx(config, flags, description, fn, defaultValue) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 713why, one step back
713 if (typeof flags === 'object' && flags instanceof Option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 717why, one step back
717 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 718–737why, one step back
718 const option = this.createOption(flags, description);
719 option.makeOptionMandatory(!!config.mandatory);720 if (typeof fn === 'function') {721 option.default(defaultValue).argParser(fn);722 } else if (fn instanceof RegExp) {723 // deprecated724 const regex = fn;725 fn = (val, def) => {726 const m = regex.exec(val);727 return m ? m[0] : def;728 };729 option.default(defaultValue).argParser(fn);730 } else {731 option.default(fn);732 }733734 return this.addOption(option);735 }736737 /**

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 739why, one step back
739 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 742why, one step back
742 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 744why, one step back
744 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 745why, one step back
745 * @example

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 746–750why, one step back
746 * program
747 * .option('-p, --pepper', 'add pepper')748 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument749 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default750 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 751–753why, one step back
751 *
752 * @param {string} flags753 * @param {string} [description]

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 755–758why, one step back
755 * @param {*} [defaultValue]
756 * @return {Command} `this` command for chaining757 */758

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 761why, one step back
761 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 762–763why, one step back
762
763 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 764–774why, one step back
764 * Add a required option which must have a value after parsing. This usually means
765 * the option must be specified on the command line. (Otherwise the same as .option().)766 *767 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.768 *769 * @param {string} flags770 * @param {string} [description]771 * @param {(Function|*)} [parseArg] - custom option processing function or default value772 * @param {*} [defaultValue]773 * @return {Command} `this` command for chaining774 */

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 775why, one step back
775

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 777–783why, one step back
777 return this._optionEx(
778 { mandatory: true },779 flags,780 description,781 parseArg,782 defaultValue,783 );

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 784why, one step back
784 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 785–788why, one step back
785
786 /**787 * Alter parsing of short flags with optional values.788 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 789–792why, one step back
789 * @example
790 * // for `.option('-f,--flag [value]'):791 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour792 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 793why, one step back
793 *

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

line 794why, one step back
794 * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 795–798why, one step back
795 */
796 combineFlagAndOptionalValue(combine = true) {797 this._combineFlagAndOptionalValue = !!combine;798 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 799why, one step back
799 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 800–803why, one step back
800
801 /**802 * Allow unknown options on the command line.803 *

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

line 804why, one step back
804 * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 805–809why, one step back
805 * for unknown options.
806 */807 allowUnknownOption(allowUnknown = true) {808 this._allowUnknownOption = !!allowUnknown;809 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 810why, one step back
810 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 811–814why, one step back
811
812 /**813 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.814 *

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

line 815why, one step back
815 * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 816–820why, one step back
816 * for excess arguments.
817 */818 allowExcessArguments(allowExcess = true) {819 this._allowExcessArguments = !!allowExcess;820 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 821why, one step back
821 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 822–827why, one step back
822
823 /**824 * Enable positional options. Positional means global options are specified before subcommands which lets825 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.826 * The default behaviour is non-positional and global options may appear anywhere on the command line.827 *

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

line 828why, one step back
828 * @param {boolean} [positional=true]

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 829–832why, one step back
829 */
830 enablePositionalOptions(positional = true) {831 this._enablePositionalOptions = !!positional;832 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 833why, one step back
833 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 834–840why, one step back
834
835 /**836 * Pass through options that come after command-arguments rather than treat them as command-options,837 * so actual command-options come before command-arguments. Turning this on for a subcommand requires838 * positional options to have been enabled on the program (parent commands).839 * The default behaviour is non-positional and options may appear before or after command-arguments.840 *

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

line 841why, one step back
841 * @param {boolean} [passThrough=true]

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 842–845why, one step back
842 * for unknown options.
843 */844 passThroughOptions(passThrough = true) {845 this._passThroughOptions = !!passThrough;

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 847why, one step back
847 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 848why, one step back
848 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 849–850why, one step back
849
850 /**

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

lines 851–854why, one step back
851 * @private
852 */853854 _checkForBrokenPassThrough() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 855–862why, one step back
855 if (
856 this.parent &&857 this._passThroughOptions &&858 !this.parent._enablePositionalOptions859 ) {860 throw new Error(861 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,862 );

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

lines 863–866why, one step back
863 }
864 }865866 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 867–872why, one step back
867 * Whether to store option values as properties on command object,
868 * or store separately (specify false). In both cases the option values can be accessed using .opts().869 *870 * @param {boolean} [storeAsProperties=true]871 * @return {Command} `this` command for chaining872 */

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 873–877why, one step back
873
874 storeOptionsAsProperties(storeAsProperties = true) {875 if (this.options.length) {876 throw new Error('call .storeOptionsAsProperties() before adding options');877 }

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 879–881why, one step back
879 throw new Error(
880 'call .storeOptionsAsProperties() before setting option values',881 );

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

line 882why, one step back
882 }

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 884why, one step back
884 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 885why, one step back
885 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 886–898why, one step back
886
887 /**888 * Retrieve option value.889 *890 * @param {string} key891 * @return {Object} value892 */893894 getOptionValue(key) {895 if (this._storeOptionsAsProperties) {896 return this[key];897 }898 return this._optionValues[key];

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 899why, one step back
899 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 900–909why, one step back
900
901 /**902 * Store option value.903 *904 * @param {string} key905 * @param {Object} value906 * @return {Command} `this` command for chaining907 */908909 setOptionValue(key, value) {

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

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 911why, one step back
911 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 912–913why, one step back
912
913 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 914–920why, one step back
914 * Store option value and where the value came from.
915 *916 * @param {string} key917 * @param {Object} value918 * @param {string} source - expected values are default/config/env/cli/implied919 * @return {Command} `this` command for chaining920 */

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 921–922why, one step back
921
922 setOptionValueWithSource(key, value, source) {

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

lines 923–927why, one step back
923 if (this._storeOptionsAsProperties) {
924 this[key] = value;925 } else {926 this._optionValues[key] = value;927 }

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 928why, one step back
928 this._optionValueSources[key] = source;

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 929why, one step back
929 return this;

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 930–932why, one step back
930 }
931932 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 933–938why, one step back
933 * Get source of option value.
934 * Expected values are default | config | env | cli | implied935 *936 * @param {string} key937 * @return {string}938 */

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 939–941why, one step back
939
940 getOptionValueSource(key) {941 return this._optionValueSources[key];

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 942why, one step back
942 }

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 943–944why, one step back
943
944 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 945–950why, one step back
945 * Get source of option value. See also .optsWithGlobals().
946 * Expected values are default | config | env | cli | implied947 *948 * @param {string} key949 * @return {string}950 */

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

lines 951–954why, one step back
951
952 getOptionValueSourceWithGlobals(key) {953 // global overwrites local, like optsWithGlobals954 let source;

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

lines 956–963why, one step back
956 if (cmd.getOptionValueSource(key) !== undefined) {
957 source = cmd.getOptionValueSource(key);958 }959 });960 return source;961 }962963 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 966why, one step back
966 *

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

line 967why, one step back
967 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 968–975why, one step back
968 */
969970 _prepareUserArgs(argv, parseOptions) {971 if (argv !== undefined && !Array.isArray(argv)) {972 throw new Error('first parameter to parse must be array or undefined');973 }974 parseOptions = parseOptions || {};975

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 979–980why, one step back
979 parseOptions.from = 'electron';
980 }

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

lines 981–990why, one step back
981 // check node specific options for scenarios where user CLI args follow executable without scriptname
982 const execArgv = process.execArgv ?? [];983 if (984 execArgv.includes('-e') ||985 execArgv.includes('--eval') ||986 execArgv.includes('-p') ||987 execArgv.includes('--print')988 ) {989 parseOptions.from = 'eval'; // internal usage, not documented990 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 991why, one step back
991 }

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

lines 992–996why, one step back
992
993 // default to using process.argv994 if (argv === undefined) {995 argv = process.argv;996 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1000–1007why, one step back
1000 let userArgs;
1001 switch (parseOptions.from) {1002 case undefined:1003 case 'node':1004 this._scriptPath = argv[1];1005 userArgs = argv.slice(2);1006 break;1007 case 'electron':

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1009–1018why, one step back
1009 if (process.defaultApp) {
1010 this._scriptPath = argv[1];1011 userArgs = argv.slice(2);1012 } else {1013 userArgs = argv.slice(1);1014 }1015 break;1016 case 'user':1017 userArgs = argv.slice(0);1018 break;

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

lines 1019–1021why, one step back
1019 case 'eval':
1020 userArgs = argv.slice(1);1021 break;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1022why, one step back
1022 default:

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1026–1027why, one step back
1026 }
1027

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1028why, one step back
1028 // Find default name for program from arguments.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1031why, one step back
1031 this._name = this._name || 'program';

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1032–1038why, one step back
1032
1033 return userArgs;1034 }10351036 /**1037 * Parse `argv`, setting options and invoking commands when defined.1038 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1040why, one step back
1040 *

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

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

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 1048why, one step back
1048 * @example

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

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

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1052why, one step back
1052 *

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

lines 1053–1055why, one step back
1053 * @param {string[]} [argv]
1054 * @param {object} [parseOptions]1055 * @param {string} parseOptions.from - one of 'node', 'user', 'electron'

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1056–1063why, one step back
1056 * @return {Command} `this` command for chaining
1057 */10581059 parse(argv, parseOptions) {1060 const userArgs = this._prepareUserArgs(argv, parseOptions);1061 this._parseCommand([], userArgs);10621063 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1064why, one step back
1064 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1065–1068why, one step back
1065
1066 /**1067 * Parse `argv`, setting options and invoking commands when defined.1068 *

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

line 1069why, one step back
1069 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1070why, one step back
1070 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1075why, one step back
1075 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 1076why, one step back
1076 * @example

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

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

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 1079why, one step back
1079 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1080–1081why, one step back
1080 *
1081 * @param {string[]} [argv]

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

lines 1082–1083why, one step back
1082 * @param {object} [parseOptions]
1083 * @param {string} parseOptions.from - one of 'node', 'user', 'electron'

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1084–1091why, one step back
1084 * @return {Promise}
1085 */10861087 async parseAsync(argv, parseOptions) {1088 const userArgs = this._prepareUserArgs(argv, parseOptions);1089 await this._parseCommand([], userArgs);10901091 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1092why, one step back
1092 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1093–1096why, one step back
1093
1094 /**1095 * Execute a sub-command executable.1096 *

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

line 1097why, one step back
1097 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1098–1104why, one step back
1098 */
10991100 _executeSubCommand(subcommand, args) {1101 args = args.slice();1102 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1103 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];1104

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1105–1108why, one step back
1105 function findFile(baseDir, baseName) {
1106 // Look for specified file1107 const localBin = path.resolve(baseDir, baseName);1108 if (fs.existsSync(localBin)) return localBin;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1109why, one step back
1109

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1110–1111why, one step back
1110 // Stop looking if candidate already has an expected extension.
1111 if (sourceExt.includes(path.extname(baseName))) return undefined;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1112why, one step back
1112

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1113why, one step back
1113 // Try all the extensions.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1117–1119why, one step back
1117 if (foundExt) return `${localBin}${foundExt}`;
11181119 return undefined;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1120–1121why, one step back
1120 }
1121

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1122–1123why, one step back
1122 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1123 this._checkForMissingMandatoryOptions();

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

line 1124why, one step back
1124 this._checkForConflictingOptions();

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1125–1126why, one step back
1125
1126 // executableFile and executableDir might be full path, or just a name

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1129–1136why, one step back
1129 let executableDir = this._executableDir || '';
1130 if (this._scriptPath) {1131 let resolvedScriptPath; // resolve possible symlink for installed npm binary1132 try {1133 resolvedScriptPath = fs.realpathSync(this._scriptPath);1134 } catch (err) {1135 resolvedScriptPath = this._scriptPath;1136 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1137–1140why, one step back
1137 executableDir = path.resolve(
1138 path.dirname(resolvedScriptPath),1139 executableDir,1140 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1141–1142why, one step back
1141 }
1142

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1143–1148why, one step back
1143 // Look for a local file in preference to a command in PATH.
1144 if (executableDir) {1145 let localFile = findFile(executableDir, executableFile);11461147 // Legacy search using prefix of script name instead of command name1148 if (!localFile && !subcommand._executableFile && this._scriptPath) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1149–1152why, one step back
1149 const legacyName = path.basename(
1150 this._scriptPath,1151 path.extname(this._scriptPath),1152 );

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1154–1157why, one step back
1154 localFile = findFile(
1155 executableDir,1156 `${legacyName}-${subcommand._name}`,1157 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1158why, one step back
1158 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1159–1160why, one step back
1159 }
1160 executableFile = localFile || executableFile;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1161–1162why, one step back
1161 }
1162

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1163–1164why, one step back
1163 launchWithNode = sourceExt.includes(path.extname(executableFile));
1164

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1165–1167why, one step back
1165 let proc;
1166 if (process.platform !== 'win32') {1167 if (launchWithNode) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1168why, one step back
1168 args.unshift(executableFile);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1169–1173why, one step back
1169 // add executable arguments to spawn
1170 args = incrementNodeInspectorPort(process.execArgv).concat(args);11711172 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1173 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1174why, one step back
1174 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1175–1176why, one step back
1175 }
1176 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1177why, one step back
1177 args.unshift(executableFile);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1178–1182why, one step back
1178 // add executable arguments to spawn
1179 args = incrementNodeInspectorPort(process.execArgv).concat(args);1180 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1181 }1182

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1185–1191why, one step back
1185 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1186 signals.forEach((signal) => {1187 process.on(signal, () => {1188 if (proc.killed === false && proc.exitCode === null) {1189 proc.kill(signal);1190 }1191 });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1192why, one step back
1192 });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1193why, one step back
1193 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1194–1196why, one step back
1194
1195 // By default terminate process when spawned process terminates.1196 const exitCallback = this._exitCallback;

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

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1202–1208why, one step back
1202 exitCallback(
1203 new CommanderError(1204 code,1205 'commander.executeSubCommandAsync',1206 '(close)',1207 ),1208 );

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

lines 1209–1210why, one step back
1209 }
1210 });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1214–1217why, one step back
1214 const executableDirMessage = executableDir
1215 ? `searched for local subcommand relative to directory '${executableDir}'`1216 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1217 const executableMissing = `'${executableFile}' does not exist

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1218why, one step back
1218 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1219–1220why, one step back
1219 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1220 - ${executableDirMessage}`;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1221why, one step back
1221 throw new Error(executableMissing);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1223why, one step back
1223 } else if (err.code === 'EACCES') {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1224why, one step back
1224 throw new Error(`'${executableFile}' not executable`);

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1225–1228why, one step back
1225 }
1226 if (!exitCallback) {1227 process.exit(1);1228 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1229–1233why, one step back
1229 const wrappedError = new CommanderError(
1230 1,1231 'commander.executeSubCommandAsync',1232 '(error)',1233 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1234–1240why, one step back
1234 wrappedError.nestedError = err;
1235 exitCallback(wrappedError);1236 }1237 });12381239 // Store the reference to the child process1240 this.runningCommand = proc;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1241why, one step back
1241 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1242–1243why, one step back
1242
1243 /**

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

line 1244why, one step back
1244 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1245–1250why, one step back
1245 */
12461247 _dispatchSubcommand(commandName, operands, unknown) {1248 const subCommand = this._findCommand(commandName);1249 if (!subCommand) this.help({ error: true });1250

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1251why, one step back
1251 let promiseChain;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1252–1256why, one step back
1252 promiseChain = this._chainOrCallSubCommandHook(
1253 promiseChain,1254 subCommand,1255 'preSubcommand',1256 );

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

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

lines 1258–1263why, one step back
1258 if (subCommand._executableHandler) {
1259 this._executeSubCommand(subCommand, operands.concat(unknown));1260 } else {1261 return subCommand._parseCommand(operands, unknown);1262 }1263 });

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1264why, one step back
1264 return promiseChain;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1265why, one step back
1265 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1266–1267why, one step back
1266
1267 /**

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

lines 1268–1270why, one step back
1268 * Invoke help directly if possible, or dispatch if necessary.
1269 * e.g. help foo1270 *

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

line 1271why, one step back
1271 * @private

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

lines 1272–1283why, one step back
1272 */
12731274 _dispatchHelpCommand(subcommandName) {1275 if (!subcommandName) {1276 this.help();1277 }1278 const subCommand = this._findCommand(subcommandName);1279 if (subCommand && !subCommand._executableHandler) {1280 subCommand.help();1281 }12821283 // Fallback to parsing the help flag to invoke the help.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1284–1288why, one step back
1284 return this._dispatchSubcommand(
1285 subcommandName,1286 [],1287 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1288 );

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

lines 1289–1291why, one step back
1289 }
12901291 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1293why, one step back
1293 *

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

line 1294why, one step back
1294 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1295–1296why, one step back
1295 */
1296

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1297–1298why, one step back
1297 _checkNumberOfArguments() {
1298 // too few

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1300–1304why, one step back
1300 if (arg.required && this.args[i] == null) {
1301 this.missingArgument(arg.name());1302 }1303 });1304 // too many

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1305–1308why, one step back
1305 if (
1306 this.registeredArguments.length > 0 &&1307 this.registeredArguments[this.registeredArguments.length - 1].variadic1308 ) {

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1309–1310why, one step back
1309 return;
1310 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1312–1313why, one step back
1312 this._excessArguments(this.args);
1313 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1314why, one step back
1314 }

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1315–1316why, one step back
1315
1316 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1318why, one step back
1318 *

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

line 1319why, one step back
1319 * @private

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1320–1322why, one step back
1320 */
13211322 _processArguments() {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1323–1326why, one step back
1323 const myParseArg = (argument, value, previous) => {
1324 // Extra processing for nice error message on parsing failure.1325 let parsedValue = value;1326 if (value !== null && argument.parseArg) {

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1328–1333why, one step back
1328 parsedValue = this._callParseArg(
1329 argument,1330 value,1331 previous,1332 invalidValueMessage,1333 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1334–1337why, one step back
1334 }
1335 return parsedValue;1336 };1337

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1338–1340why, one step back
1338 this._checkNumberOfArguments();
13391340 const processedArgs = [];

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1342–1360why, one step back
1342 let value = declaredArg.defaultValue;
1343 if (declaredArg.variadic) {1344 // Collect together remaining arguments for passing together as an array.1345 if (index < this.args.length) {1346 value = this.args.slice(index);1347 if (declaredArg.parseArg) {1348 value = value.reduce((processed, v) => {1349 return myParseArg(declaredArg, v, processed);1350 }, declaredArg.defaultValue);1351 }1352 } else if (value === undefined) {1353 value = [];1354 }1355 } else if (index < this.args.length) {1356 value = this.args[index];1357 if (declaredArg.parseArg) {1358 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1359 }1360 }

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1361why, one step back
1361 processedArgs[index] = value;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1362why, one step back
1362 });

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1363why, one step back
1363 this.processedArgs = processedArgs;

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1364–1368why, one step back
1364 }
13651366 /**1367 * Once we have a promise we chain, but call synchronously until then.1368 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1373–1386why, one step back
1373 */
13741375 _chainOrCall(promise, fn) {1376 // thenable1377 if (promise && promise.then && typeof promise.then === 'function') {1378 // already have a promise, chain callback1379 return promise.then(() => fn());1380 }1381 // callback might return a promise1382 return fn();1383 }13841385 /**1386 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1391–1395why, one step back
1391 */
13921393 _chainOrCallHooks(promise, event) {1394 let result = promise;1395 const hooks = [];

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1400–1412why, one step back
1400 hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1401 hooks.push({ hookedCommand, callback });1402 });1403 });1404 if (event === 'postAction') {1405 hooks.reverse();1406 }14071408 hooks.forEach((hookDetail) => {1409 result = this._chainOrCall(result, () => {1410 return hookDetail.callback(hookDetail.hookedCommand, this);1411 });1412 });

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

lines 1413–1417why, one step back
1413 return result;
1414 }14151416 /**1417 *

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

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

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

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

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

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

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

lines 1423–1433why, one step back
1423 */
14241425 _chainOrCallSubCommandHook(promise, subCommand, event) {1426 let result = promise;1427 if (this._lifeCycleHooks[event] !== undefined) {1428 this._lifeCycleHooks[event].forEach((hook) => {1429 result = this._chainOrCall(result, () => {1430 return hook(this, subCommand);1431 });1432 });1433 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1434–1440why, one step back
1434 return result;
1435 }14361437 /**1438 * Process arguments in context of this command.1439 * Returns action result, in case it is a promise.1440 *

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

line 1441why, one step back
1441 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1442–1445why, one step back
1442 */
14431444 _parseCommand(operands, unknown) {1445 const parsed = this.parseOptions(unknown);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 1446why, one step back
1446 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1448–1454why, one step back
1448 operands = operands.concat(parsed.operands);
1449 unknown = parsed.unknown;1450 this.args = operands.concat(unknown);14511452 if (operands && this._findCommand(operands[0])) {1453 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1454 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1455–1458why, one step back
1455 if (
1456 this._getHelpCommand() &&1457 operands[0] === this._getHelpCommand().name()1458 ) {

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1460–1461why, one step back
1460 }
1461 if (this._defaultCommandName) {

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

line 1462why, one step back
1462 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 1463–1467why, one step back
1463 return this._dispatchSubcommand(
1464 this._defaultCommandName,1465 operands,1466 unknown,1467 );

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1468why, one step back
1468 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1469–1474why, one step back
1469 if (
1470 this.commands.length &&1471 this.args.length === 0 &&1472 !this._actionHandler &&1473 !this._defaultCommandName1474 ) {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1475–1478why, one step back
1475 // probably missing subcommand and no handler, user needs help (and exit)
1476 this.help({ error: true });1477 }1478

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1480why, one step back
1480 this._checkForMissingMandatoryOptions();

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1481why, one step back
1481 this._checkForConflictingOptions();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1482–1492why, one step back
1482
1483 // We do not always call this check to avoid masking a "better" error, like unknown command.1484 const checkForUnknownOptions = () => {1485 if (parsed.unknown.length > 0) {1486 this.unknownOption(parsed.unknown[0]);1487 }1488 };14891490 const commandEvent = `command:${this.name()}`;1491 if (this._actionHandler) {1492 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1493why, one step back
1493 this._processArguments();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1494why, one step back
1494

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1497–1499why, one step back
1497 promiseChain = this._chainOrCall(promiseChain, () =>
1498 this._actionHandler(this.processedArgs),1499 );

Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b

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

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b

lines 1502–1504why, one step back
1502 this.parent.emit(commandEvent, operands, unknown); // legacy
1503 });1504 }

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1507–1509why, one step back
1507 }
1508 if (this.parent && this.parent.listenerCount(commandEvent)) {1509 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1510why, one step back
1510 this._processArguments();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1511–1512why, one step back
1511 this.parent.emit(commandEvent, operands, unknown); // legacy
1512 } else if (operands.length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1515–1523why, one step back
1515 return this._dispatchSubcommand('*', operands, unknown);
1516 }1517 if (this.listenerCount('command:*')) {1518 // skip option check, emit event for possible misspelling suggestion1519 this.emit('command:*', operands, unknown);1520 } else if (this.commands.length) {1521 this.unknownCommand();1522 } else {1523 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1524why, one step back
1524 this._processArguments();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1525–1526why, one step back
1525 }
1526 } else if (this.commands.length) {

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 1527why, one step back
1527 checkForUnknownOptions();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1528–1531why, one step back
1528 // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1529 this.help({ error: true });1530 } else {1531 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1532why, one step back
1532 this._processArguments();

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1533–1534why, one step back
1533 // fall through for caller to handle after calling .parse()
1534 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1535why, one step back
1535 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1536–1539why, one step back
1536
1537 /**1538 * Find matching command.1539 *

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

line 1540why, one step back
1540 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1541–1543why, one step back
1541 */
1542 _findCommand(name) {1543 if (!name) return undefined;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1544–1546why, one step back
1544 return this.commands.find(
1545 (cmd) => cmd._name === name || cmd._aliases.includes(name),1546 );

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1547why, one step back
1547 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1548–1553why, one step back
1548
1549 /**1550 * Return an option matching `arg` if any.1551 *1552 * @param {string} arg1553 * @return {Option}

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

line 1554why, one step back
1554 * @package internal use only

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1555–1557why, one step back
1555 */
15561557 _findOption(arg) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1559why, one step back
1559 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1560–1562why, one step back
1560
1561 /**1562 * Display an error message if a mandatory option does not have a value.

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

line 1563why, one step back
1563 * Called after checking for help flags in leaf subcommand.

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1564why, one step back
1564 *

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

line 1565why, one step back
1565 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1572–1575why, one step back
1572 if (
1573 anOption.mandatory &&1574 cmd.getOptionValue(anOption.attributeName()) === undefined1575 ) {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1576–1578why, one step back
1576 cmd.missingMandatoryOptionValue(anOption);
1577 }1578 });

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1579why, one step back
1579 });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1580why, one step back
1580 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1581–1582why, one step back
1581
1582 /**

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

line 1583why, one step back
1583 * Display an error message if conflicting options are used together in this.

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1584why, one step back
1584 *

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

line 1585why, one step back
1585 * @private

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1586why, one step back
1586 */

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

line 1587why, one step back
1587 _checkForConflictingLocalOptions() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1588–1591why, one step back
1588 const definedNonDefaultOptions = this.options.filter((option) => {
1589 const optionKey = option.attributeName();1590 if (this.getOptionValue(optionKey) === undefined) {1591 return false;

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1592why, one step back
1592 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1595–1596why, one step back
1595
1596 const optionsWithConflicting = definedNonDefaultOptions.filter(

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1598–1601why, one step back
1598 );
15991600 optionsWithConflicting.forEach((option) => {1601 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1603–1607why, one step back
1603 );
1604 if (conflictingAndDefined) {1605 this._conflictingOption(option, conflictingAndDefined);1606 }1607 });

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

lines 1608–1613why, one step back
1608 }
16091610 /**1611 * Display an error message if conflicting options are used together.1612 * Called after checking for help flags in leaf subcommand.1613 *

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

line 1614why, one step back
1614 * @private

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

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

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

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1620why, one step back
1620 });

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1621–1623why, one step back
1621 }
16221623 /**

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1624–1628why, one step back
1624 * Parse options from `argv` removing known options,
1625 * and return argv split into operands and unknown arguments.1626 *1627 * Examples:1628 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 1629–1633why, one step back
1629 * argv => operands, unknown
1630 * --known kkk op => [op], []1631 * op --known kkk => [op], []1632 * sub --unknown uuu op => [sub], [--unknown uuu op]1633 * sub -- --unknown uuu op => [sub --unknown uuu op], []

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1634why, one step back
1634 *

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

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1637–1681why, one step back
1637 */
16381639 parseOptions(argv) {1640 const operands = []; // operands, not options or values1641 const unknown = []; // first unknown option and remaining unknown args1642 let dest = operands;1643 const args = argv.slice();16441645 function maybeOption(arg) {1646 return arg.length > 1 && arg[0] === '-';1647 }16481649 // parse options1650 let activeVariadicOption = null;1651 while (args.length) {1652 const arg = args.shift();16531654 // literal1655 if (arg === '--') {1656 if (dest === unknown) dest.push(arg);1657 dest.push(...args);1658 break;1659 }16601661 if (activeVariadicOption && !maybeOption(arg)) {1662 this.emit(`option:${activeVariadicOption.name()}`, arg);1663 continue;1664 }1665 activeVariadicOption = null;16661667 if (maybeOption(arg)) {1668 const option = this._findOption(arg);1669 // recognised option, call listener to assign value with possible custom processing1670 if (option) {1671 if (option.required) {1672 const value = args.shift();1673 if (value === undefined) this.optionMissingArgument(option);1674 this.emit(`option:${option.name()}`, value);1675 } else if (option.optional) {1676 let value = null;1677 // historical behaviour is optional value is following arg unless an option1678 if (args.length > 0 && !maybeOption(args[0])) {1679 value = args.shift();1680 }1681 this.emit(`option:${option.name()}`, value);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1682–1683why, one step back
1682 } else {
1683 // boolean flag

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1684–1694why, one step back
1684 this.emit(`option:${option.name()}`);
1685 }1686 activeVariadicOption = option.variadic ? option : null;1687 continue;1688 }1689 }16901691 // Look for combo options following single dash, eat first one if known.1692 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1693 const option = this._findOption(`-${arg[1]}`);1694 if (option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1695–1698why, one step back
1695 if (
1696 option.required ||1697 (option.optional && this._combineFlagAndOptionalValue)1698 ) {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1699–1728why, one step back
1699 // option with value following in same argument
1700 this.emit(`option:${option.name()}`, arg.slice(2));1701 } else {1702 // boolean option, emit and put back remainder of arg for further processing1703 this.emit(`option:${option.name()}`);1704 args.unshift(`-${arg.slice(2)}`);1705 }1706 continue;1707 }1708 }17091710 // Look for known long flag with value, like --foo=bar1711 if (/^--[^=]+=/.test(arg)) {1712 const index = arg.indexOf('=');1713 const option = this._findOption(arg.slice(0, index));1714 if (option && (option.required || option.optional)) {1715 this.emit(`option:${option.name()}`, arg.slice(index + 1));1716 continue;1717 }1718 }17191720 // Not a recognised option by this command.1721 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.17221723 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1724 if (maybeOption(arg)) {1725 dest = unknown;1726 }17271728 // If using positionalOptions, stop processing our options at subcommand.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1729–1733why, one step back
1729 if (
1730 (this._enablePositionalOptions || this._passThroughOptions) &&1731 operands.length === 0 &&1732 unknown.length === 01733 ) {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1734–1737why, one step back
1734 if (this._findCommand(arg)) {
1735 operands.push(arg);1736 if (args.length > 0) unknown.push(...args);1737 break;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1738–1741why, one step back
1738 } else if (
1739 this._getHelpCommand() &&1740 arg === this._getHelpCommand().name()1741 ) {

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1742–1763why, one step back
1742 operands.push(arg);
1743 if (args.length > 0) operands.push(...args);1744 break;1745 } else if (this._defaultCommandName) {1746 unknown.push(arg);1747 if (args.length > 0) unknown.push(...args);1748 break;1749 }1750 }17511752 // If using passThroughOptions, stop processing options at first command-argument.1753 if (this._passThroughOptions) {1754 dest.push(arg);1755 if (args.length > 0) dest.push(...args);1756 break;1757 }17581759 // add arg1760 dest.push(arg);1761 }17621763 return { operands, unknown };

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1764why, one step back
1764 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1765–1766why, one step back
1765
1766 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1767why, one step back
1767 * Return an object containing local option values as key-value pairs.

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1768–1778why, one step back
1768 *
1769 * @return {Object}1770 */1771 opts() {1772 if (this._storeOptionsAsProperties) {1773 // Preserve original behaviour so backwards compatible when still using properties1774 const result = {};1775 const len = this.options.length;17761777 for (let i = 0; i < len; i++) {1778 const key = this.options[i].attributeName();

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1781–1785why, one step back
1781 }
1782 return result;1783 }17841785 return this._optionValues;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1786why, one step back
1786 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1787–1788why, one step back
1787
1788 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1789why, one step back
1789 * Return an object containing merged local and global option values as key-value pairs.

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1790why, one step back
1790 *

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1791why, one step back
1791 * @return {Object}

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1792why, one step back
1792 */

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1793–1794why, one step back
1793 optsWithGlobals() {
1794 // globals overwrite locals

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1797why, one step back
1797 {},

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1798–1810why, one step back
1798 );
1799 }18001801 /**1802 * Display error message and exit (or call exitOverride).1803 *1804 * @param {string} message1805 * @param {Object} [errorOptions]1806 * @param {string} [errorOptions.code] - an id string representing the error1807 * @param {number} [errorOptions.exitCode] - used with process.exit1808 */1809 error(message, errorOptions) {1810 // output handling

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1811–1814why, one step back
1811 this._outputConfiguration.outputError(
1812 `${message}\n`,1813 this._outputConfiguration.writeErr,1814 );

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 1815–1820why, one step back
1815 if (typeof this._showHelpAfterError === 'string') {
1816 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1817 } else if (this._showHelpAfterError) {1818 this._outputConfiguration.writeErr('\n');1819 this.outputHelp({ error: true });1820 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1821–1825why, one step back
1821
1822 // exit handling1823 const config = errorOptions || {};1824 const exitCode = config.exitCode || 1;1825 const code = config.code || 'commander.error';

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

line 1826why, one step back
1826 this._exit(exitCode, code, message);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1827–1832why, one step back
1827 }
18281829 /**1830 * Apply any option related environment variables, if option does1831 * not have a value from cli or client code.1832 *

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

line 1833why, one step back
1833 * @private

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1834–1838why, one step back
1834 */
1835 _parseOptionsEnv() {1836 this.options.forEach((option) => {1837 if (option.envVar && option.envVar in process.env) {1838 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 1839why, one step back
1839 // Priority check. Do not overwrite cli or options from unknown source (client-code).

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1840–1847why, one step back
1840 if (
1841 this.getOptionValue(optionKey) === undefined ||1842 ['default', 'config', 'env'].includes(1843 this.getOptionValueSource(optionKey),1844 )1845 ) {1846 if (option.required || option.optional) {1847 // option can take a value

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1850–1851why, one step back
1850 } else {
1851 // boolean

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1852–1857why, one step back
1852 // keep very simple, only care that envVar defined and not the value
1853 this.emit(`optionEnv:${option.name()}`);1854 }1855 }1856 }1857 });

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

lines 1858–1862why, one step back
1858 }
18591860 /**1861 * Apply any implied option values, if option is undefined or default value.1862 *

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

line 1863why, one step back
1863 * @private

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

lines 1864–1867why, one step back
1864 */
1865 _parseOptionsImplied() {1866 const dualHelper = new DualOptions(this.options);1867 const hasCustomOptionValue = (optionKey) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1868–1871why, one step back
1868 return (
1869 this.getOptionValue(optionKey) !== undefined &&1870 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1871 );

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

lines 1872–1873why, one step back
1872 };
1873 this.options

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1874–1882why, one step back
1874 .filter(
1875 (option) =>1876 option.implied !== undefined &&1877 hasCustomOptionValue(option.attributeName()) &&1878 dualHelper.valueFromOption(1879 this.getOptionValue(option.attributeName()),1880 option,1881 ),1882 )

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

lines 1883–1884why, one step back
1883 .forEach((option) => {
1884 Object.keys(option.implied)

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1885–1891why, one step back
1885 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
1886 .forEach((impliedKey) => {1887 this.setOptionValueWithSource(1888 impliedKey,1889 option.implied[impliedKey],1890 'implied',1891 );

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

lines 1892–1893why, one step back
1892 });
1893 });

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1894–1899why, one step back
1894 }
18951896 /**1897 * Argument `name` is missing.1898 *1899 * @param {string} name

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

line 1900why, one step back
1900 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1901–1904why, one step back
1901 */
19021903 missingArgument(name) {1904 const message = `error: missing required argument '${name}'`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1905–1906why, one step back
1905 this.error(message, { code: 'commander.missingArgument' });
1906 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1907–1911why, one step back
1907
1908 /**1909 * `Option` is missing an argument.1910 *1911 * @param {Option} option

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

line 1912why, one step back
1912 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1913–1916why, one step back
1913 */
19141915 optionMissingArgument(option) {1916 const message = `error: option '${option.flags}' argument missing`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1917–1918why, one step back
1917 this.error(message, { code: 'commander.optionMissingArgument' });
1918 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1919–1923why, one step back
1919
1920 /**1921 * `Option` does not have a value, and is a mandatory option.1922 *1923 * @param {Option} option

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

line 1924why, one step back
1924 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1925–1928why, one step back
1925 */
19261927 missingMandatoryOptionValue(option) {1928 const message = `error: required option '${option.flags}' not specified`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1929why, one step back
1929 this.error(message, { code: 'commander.missingMandatoryOptionValue' });

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1930–1936why, one step back
1930 }
19311932 /**1933 * `Option` conflicts with another option.1934 *1935 * @param {Option} option1936 * @param {Option} conflictingOption

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

line 1937why, one step back
1937 * @private

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1938–1944why, one step back
1938 */
1939 _conflictingOption(option, conflictingOption) {1940 // The calling code does not know whether a negated option is the source of the1941 // value, so do some work to take an educated guess.1942 const findBestOptionFromValue = (option) => {1943 const optionKey = option.attributeName();1944 const optionValue = this.getOptionValue(optionKey);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1945–1956why, one step back
1945 const negativeOption = this.options.find(
1946 (target) => target.negate && optionKey === target.attributeName(),1947 );1948 const positiveOption = this.options.find(1949 (target) => !target.negate && optionKey === target.attributeName(),1950 );1951 if (1952 negativeOption &&1953 ((negativeOption.presetArg === undefined && optionValue === false) ||1954 (negativeOption.presetArg !== undefined &&1955 optionValue === negativeOption.presetArg))1956 ) {

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1957–1973why, one step back
1957 return negativeOption;
1958 }1959 return positiveOption || option;1960 };19611962 const getErrorMessage = (option) => {1963 const bestOption = findBestOptionFromValue(option);1964 const optionKey = bestOption.attributeName();1965 const source = this.getOptionValueSource(optionKey);1966 if (source === 'env') {1967 return `environment variable '${bestOption.envVar}'`;1968 }1969 return `option '${bestOption.flags}'`;1970 };19711972 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1973 this.error(message, { code: 'commander.conflictingOption' });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1974why, one step back
1974 }

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1975–1979why, one step back
1975
1976 /**1977 * Unknown option `flag`.1978 *1979 * @param {string} flag

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

line 1980why, one step back
1980 * @private

Remove incorrect example output (#1532)John Geebefore adoptiond282f20

lines 1981–1984why, one step back
1981 */
19821983 unknownOption(flag) {1984 if (this._allowUnknownOption) return;

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 1985–1989why, one step back
1985 let suggestion = '';
19861987 if (flag.startsWith('--') && this._showSuggestionAfterError) {1988 // Looping to pick up the global options too1989 let candidateFlags = [];

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

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

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

lines 1991–1992why, one step back
1991 let command = this;
1992 do {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1993–1997why, one step back
1993 const moreFlags = command
1994 .createHelp()1995 .visibleOptions(command)1996 .filter((option) => option.long)1997 .map((option) => option.long);

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 1998why, one step back
1998 candidateFlags = candidateFlags.concat(moreFlags);

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

lines 1999–2000why, one step back
1999 command = command.parent;
2000 } while (command && !command._enablePositionalOptions);

The first 2,000 of 2,504 lines.