Skip to content
Myr

command.js

This file

Path

lib/command.js

2,585 lines · 79.1 KiB · JavaScript

Last changed by

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

History of this file

Take it

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 6–8why, one step back
6
7const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');

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

line 9why, one step back
9const { Help, stripColor } = require('./help.js');

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

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 12–27why, 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();22 /** @type {Command[]} */23 this.commands = [];24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;

Disallow excess arguments (#2223)John Geebefore adoption58c28eb

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 32–38why, one step back
32 /** @type {string[]} */
33 this.args = []; // cli args with options removed34 this.rawArgs = [];35 this.processedArgs = []; // like .args but after custom processing and collecting variadic36 this._scriptPath = null;37 this._name = name || '';38 this._optionValues = {};

Add implied to option value sources (#1794)John Geebefore adoption72be61c

line 39why, one step back
39 this._optionValueSources = {}; // default, env, cli etc

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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 = '';

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 58why, one step back
58

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 60–62why, one step back
60 this._outputConfiguration = {
61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),

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

line 63why, one step back
63 outputError: (str, write) => write(str),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 68–72why, one step back
68 getOutHasColors: () =>
69 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),70 getErrHasColors: () =>71 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),72 stripColor: (str) => stripColor(str),

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 73–75why, one step back
73 };
7475 this._hidden = false;

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 81–89why, one step back
81 this._helpConfiguration = {};
82 }8384 /**85 * Copy settings that are useful to have in common across root command and subcommands.86 *87 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)88 *89 * @param {Command} sourceCommand

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 91–93why, one step back
91 */
92 copyInheritedSettings(sourceCommand) {93 this._outputConfiguration = sourceCommand._outputConfiguration;

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 96–98why, one step back
96 this._helpConfiguration = sourceCommand._helpConfiguration;
97 this._exitCallback = sourceCommand._exitCallback;98 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 99–100why, one step back
99 this._combineFlagAndOptionalValue =
100 sourceCommand._combineFlagAndOptionalValue;

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 101–103why, one step back
101 this._allowExcessArguments = sourceCommand._allowExcessArguments;
102 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103 this._showHelpAfterError = sourceCommand._showHelpAfterError;

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 105–109why, one step back
105
106 return this;107 }108109 /**

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

line 111why, one step back
111 * @private

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 112–115why, one step back
112 */
113114 _getCommandAndAncestors() {115 const result = [];

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

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

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 117–123why, one step back
117 for (let command = this; command; command = command.parent) {
118 result.push(command);119 }120 return result;121 }122123 /**

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 124–142why, one step back
124 * Define a command.
125 *126 * There are two styles of command: pay attention to where to put the description.127 *128 * @example129 * // Command implemented using action handler (description is supplied separately to `.command`)130 * program131 * .command('clone <source> [destination]')132 * .description('clone a repository into a newly created directory')133 * .action((source, destination) => {134 * console.log('clone command called');135 * });136 *137 * // Command implemented using separate executable file (description is second parameter to `.command`)138 * program139 * .command('start <service>', 'start named service')140 * .command('stop [service]', 'stop named service, or all if no name supplied');141 *142 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`

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

lines 143–144why, one step back
143 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
144 * @param {object} [execOpts] - configuration options (for executable)

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 145–166why, one step back
145 * @return {Command} returns new command for action handler, or `this` for executable command
146 */147148 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {149 let desc = actionOptsOrExecDesc;150 let opts = execOpts;151 if (typeof desc === 'object' && desc !== null) {152 opts = desc;153 desc = null;154 }155 opts = opts || {};156 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);157158 const cmd = this.createCommand(name);159 if (desc) {160 cmd.description(desc);161 cmd._executableHandler = true;162 }163 if (opts.isDefault) this._defaultCommandName = cmd._name;164 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden165 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor166 if (args) cmd.arguments(args);

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 168–172why, one step back
168 cmd.parent = this;
169 cmd.copyInheritedSettings(this);170171 if (desc) return this;172 return cmd;

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

line 173why, one step back
173 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 174–186why, one step back
174
175 /**176 * Factory routine to create a new unattached command.177 *178 * See .command() for creating an attached subcommand, which uses this routine to179 * create the command. You can override createCommand to customise subcommands.180 *181 * @param {string} [name]182 * @return {Command} new command183 */184185 createCommand(name) {186 return new Command(name);

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

line 187why, one step back
187 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 188–197why, one step back
188
189 /**190 * You can customise the help with a subclass of Help by overriding createHelp,191 * or by overriding Help properties using configureHelp().192 *193 * @return {Help}194 */195196 createHelp() {197 return Object.assign(new Help(), this.configureHelp());

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

line 198why, one step back
198 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 199–203why, one step back
199
200 /**201 * You can customise the help by overriding Help properties using configureHelp(),202 * or with a subclass of Help by overriding createHelp().203 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 206–220why, one step back
206 */
207208 configureHelp(configuration) {209 if (configuration === undefined) return this._helpConfiguration;210211 this._helpConfiguration = configuration;212 return this;213 }214215 /**216 * The default output goes to stdout and stderr. You can customise this for special217 * applications. You can also customise the display of errors by overriding outputError.218 *219 * The configuration properties are all functions:220 *

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

line 221why, one step back
221 * // change how output being written, defaults to stdout and stderr

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 222–223why, one step back
222 * writeOut(str)
223 * writeErr(str)

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 227–228why, one step back
227 * getOutHelpWidth()
228 * getErrHelpWidth()

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

lines 229–231why, one step back
229 * // color support, currently only used with Help
230 * getOutHasColors()231 * getErrHasColors()

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 233why, one step back
233 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 236–247why, one step back
236 */
237238 configureOutput(configuration) {239 if (configuration === undefined) return this._outputConfiguration;240241 Object.assign(this._outputConfiguration, configuration);242 return this;243 }244245 /**246 * Display the help or a custom message after an error occurs.247 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 249–257why, one step back
249 * @return {Command} `this` command for chaining
250 */251 showHelpAfterError(displayHelp = true) {252 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;253 this._showHelpAfterError = displayHelp;254 return this;255 }256257 /**

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

lines 258–268why, one step back
258 * Display suggestion of similar commands for unknown commands, or options for unknown options.
259 *260 * @param {boolean} [displaySuggestion]261 * @return {Command} `this` command for chaining262 */263 showSuggestionAfterError(displaySuggestion = true) {264 this._showSuggestionAfterError = !!displaySuggestion;265 return this;266 }267268 /**

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 269–273why, one step back
269 * Add a prepared subcommand.
270 *271 * See .command() for creating an attached subcommand which inherits settings from its parent.272 *273 * @param {Command} cmd - new subcommand

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 275–278why, one step back
275 * @return {Command} `this` command for chaining
276 */277278 addCommand(cmd, opts) {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 282–287why, one step back
282 }
283284 opts = opts || {};285 if (opts.isDefault) this._defaultCommandName = cmd._name;286 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation287

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

lines 290–291why, one step back
290 cmd._checkForBrokenPassThrough();
291

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 292why, one step back
292 return this;

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

line 293why, one step back
293 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 294–307why, one step back
294
295 /**296 * Factory routine to create a new unattached argument.297 *298 * See .argument() for creating an attached argument, which uses this routine to299 * create the argument. You can override createArgument to return a custom argument.300 *301 * @param {string} name302 * @param {string} [description]303 * @return {Argument} new argument304 */305306 createArgument(name, description) {307 return new Argument(name, description);

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

line 308why, one step back
308 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 309–321why, one step back
309
310 /**311 * Define argument syntax for command.312 *313 * The default is that the argument is required, and you can explicitly314 * indicate this with <> around the name. Put [] around the name for an optional argument.315 *316 * @example317 * program.argument('<input-file>');318 * program.argument('[output-file]');319 *320 * @param {string} name321 * @param {string} [description]

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 323–349why, one step back
323 * @param {*} [defaultValue]
324 * @return {Command} `this` command for chaining325 */326 argument(name, description, fn, defaultValue) {327 const argument = this.createArgument(name, description);328 if (typeof fn === 'function') {329 argument.default(defaultValue).argParser(fn);330 } else {331 argument.default(fn);332 }333 this.addArgument(argument);334 return this;335 }336337 /**338 * Define argument syntax for command, adding multiple at once (without descriptions).339 *340 * See also .argument().341 *342 * @example343 * program.arguments('<cmd> [env]');344 *345 * @param {string} names346 * @return {Command} `this` command for chaining347 */348349 arguments(names) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 350–355why, one step back
350 names
351 .trim()352 .split(/ +/)353 .forEach((detail) => {354 this.argument(detail);355 });

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 356why, one step back
356 return this;

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

line 357why, one step back
357 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 358–365why, one step back
358
359 /**360 * Define argument syntax for command, adding a prepared argument.361 *362 * @param {Argument} argument363 * @return {Command} `this` command for chaining364 */365 addArgument(argument) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 371why, one step back
371 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 372–379why, one step back
372 if (
373 argument.required &&374 argument.defaultValue !== undefined &&375 argument.parseArg === undefined376 ) {377 throw new Error(378 `a default value for a required argument is never used: '${argument.name()}'`,379 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 380why, one step back
380 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 382–385why, one step back
382 return this;
383 }384385 /**

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 387why, one step back
387 *

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

line 388why, one step back
388 * @example

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

lines 389–392why, one step back
389 * program.helpCommand('help [cmd]');
390 * program.helpCommand('help [cmd]', 'show help');391 * program.helpCommand(false); // suppress default help command392 * program.helpCommand(true); // add help command even if no subcommands

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 393why, one step back
393 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 396–398why, one step back
396 * @return {Command} `this` command for chaining
397 */398

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

lines 399–402why, one step back
399 helpCommand(enableOrNameAndArgs, description) {
400 if (typeof enableOrNameAndArgs === 'boolean') {401 this._addImplicitHelpCommand = enableOrNameAndArgs;402 return this;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 403why, one step back
403 }

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

lines 404–416why, one step back
404
405 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';406 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);407 const helpDescription = description ?? 'display help for command';408409 const helpCommand = this.createCommand(helpName);410 helpCommand.helpOption(false);411 if (helpArgs) helpCommand.arguments(helpArgs);412 if (helpDescription) helpCommand.description(helpDescription);413414 this._addImplicitHelpCommand = true;415 this._helpCommand = helpCommand;416

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 417why, one step back
417 return this;

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

line 418why, one step back
418 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 419–420why, one step back
419
420 /**

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

lines 421–425why, one step back
421 * Add prepared custom help command.
422 *423 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`424 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only425 * @return {Command} `this` command for chaining

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 426why, one step back
426 */

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

lines 427–433why, one step back
427 addHelpCommand(helpCommand, deprecatedDescription) {
428 // If not passed an object, call through to helpCommand for backwards compatibility,429 // as addHelpCommand was originally used like helpCommand is now.430 if (typeof helpCommand !== 'object') {431 this.helpCommand(helpCommand, deprecatedDescription);432 return this;433 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 434why, one step back
434

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

lines 435–446why, one step back
435 this._addImplicitHelpCommand = true;
436 this._helpCommand = helpCommand;437 return this;438 }439440 /**441 * Lazy create help command.442 *443 * @return {(Command|null)}444 * @package445 */446 _getHelpCommand() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 447–451why, one step back
447 const hasImplicitHelpCommand =
448 this._addImplicitHelpCommand ??449 (this.commands.length &&450 !this._actionHandler &&451 !this._findCommand('help'));

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

lines 452–457why, one step back
452
453 if (hasImplicitHelpCommand) {454 if (this._helpCommand === undefined) {455 this.helpCommand(undefined, undefined); // use default name and description456 }457 return this._helpCommand;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 458why, one step back
458 }

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

line 459why, one step back
459 return null;

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

line 460why, one step back
460 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 461–470why, one step back
461
462 /**463 * Add hook for life cycle event.464 *465 * @param {string} event466 * @param {Function} listener467 * @return {Command} `this` command for chaining468 */469470 hook(event, listener) {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 472–503why, one step back
472 if (!allowedValues.includes(event)) {
473 throw new Error(`Unexpected value for event passed to hook : '${event}'.474Expecting one of '${allowedValues.join("', '")}'`);475 }476 if (this._lifeCycleHooks[event]) {477 this._lifeCycleHooks[event].push(listener);478 } else {479 this._lifeCycleHooks[event] = [listener];480 }481 return this;482 }483484 /**485 * Register callback to use as replacement for calling process.exit.486 *487 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing488 * @return {Command} `this` command for chaining489 */490491 exitOverride(fn) {492 if (fn) {493 this._exitCallback = fn;494 } else {495 this._exitCallback = (err) => {496 if (err.code !== 'commander.executeSubCommandAsync') {497 throw err;498 } else {499 // Async callback from spawn events, not useful to throw.500 }501 };502 }503 return this;

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

line 504why, one step back
504 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 505–512why, one step back
505
506 /**507 * Call process.exit, and _exitCallback if defined.508 *509 * @param {number} exitCode exit code for using with process.exit510 * @param {string} code an id string representing the error511 * @param {string} message human-readable description of the error512 * @return never

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

line 513why, one step back
513 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 514–521why, one step back
514 */
515516 _exit(exitCode, code, message) {517 if (this._exitCallback) {518 this._exitCallback(new CommanderError(exitCode, code, message));519 // Expecting this line is not reached.520 }521 process.exit(exitCode);

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

line 522why, one step back
522 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 523–528why, one step back
523
524 /**525 * Register callback `fn` for the command.526 *527 * @example528 * program

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 533–541why, one step back
533 * });
534 *535 * @param {Function} fn536 * @return {Command} `this` command for chaining537 */538539 action(fn) {540 const listener = (args) => {541 // The .action callback takes an extra parameter which is the command or options.

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 543–554why, one step back
543 const actionArgs = args.slice(0, expectedArgsCount);
544 if (this._storeOptionsAsProperties) {545 actionArgs[expectedArgsCount] = this; // backwards compatible "options"546 } else {547 actionArgs[expectedArgsCount] = this.opts();548 }549 actionArgs.push(this);550551 return fn.apply(this, actionArgs);552 };553 this._actionHandler = listener;554 return this;

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

line 555why, one step back
555 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 556–569why, one step back
556
557 /**558 * Factory routine to create a new unattached option.559 *560 * See .option() for creating an attached option, which uses this routine to561 * create the option. You can override createOption to return a custom option.562 *563 * @param {string} flags564 * @param {string} [description]565 * @return {Option} new option566 */567568 createOption(flags, description) {569 return new Option(flags, description);

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

line 570why, one step back
570 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 571–572why, one step back
571
572 /**

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

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

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

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

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

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

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

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

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

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

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

line 579why, one step back
579 * @private

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

lines 580–594why, one step back
580 */
581582 _callParseArg(target, value, previous, invalidArgumentMessage) {583 try {584 return target.parseArg(value, previous);585 } catch (err) {586 if (err.code === 'commander.invalidArgument') {587 const message = `${invalidArgumentMessage} ${err.message}`;588 this.error(message, { exitCode: err.exitCode, code: err.code });589 }590 throw err;591 }592 }593594 /**

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

lines 595–598why, one step back
595 * Check for option flag conflicts.
596 * Register option if no conflicts found, or throw on conflict.597 *598 * @param {Option} option

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

line 599why, one step back
599 * @private

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

lines 600–602why, one step back
600 */
601602 _registerOption(option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 607–610why, one step back
607 const matchingFlag =
608 option.long && this._findOption(option.long)609 ? option.long610 : option.short;

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

lines 611–622why, one step back
611 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
612- already used by option '${matchingOption.flags}'`);613 }614615 this.options.push(option);616 }617618 /**619 * Check for command name and alias conflicts with existing commands.620 * Register command if no conflicts found, or throw on conflict.621 *622 * @param {Command} command

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

line 623why, one step back
623 * @private

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

lines 624–630why, one step back
624 */
625626 _registerCommand(command) {627 const knownBy = (cmd) => {628 return [cmd.name()].concat(cmd.aliases());629 };630

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 631–633why, one step back
631 const alreadyUsed = knownBy(command).find((name) =>
632 this._findCommand(name),633 );

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 640–645why, one step back
640 }
641642 this.commands.push(command);643 }644645 /**

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 646–651why, one step back
646 * Add an option.
647 *648 * @param {Option} option649 * @return {Command} `this` command for chaining650 */651 addOption(option) {

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

lines 652–653why, one step back
652 this._registerOption(option);
653

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 654–656why, one step back
654 const oname = option.name();
655 const name = option.attributeName();656

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 662–666why, one step back
662 this.setOptionValueWithSource(
663 name,664 option.defaultValue === undefined ? true : option.defaultValue,665 'default',666 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 667why, one step back
667 }

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 670–671why, one step back
670 }
671

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

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

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

lines 674–678why, one step back
674 // val is null for optional option used without an optional-argument.
675 // val is undefined for boolean and negated option.676 if (val == null && option.presetArg !== undefined) {677 val = option.presetArg;678 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 679–680why, one step back
679
680 // custom processing

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 684–687why, one step back
684 } else if (val !== null && option.variadic) {
685 val = option._concatValue(val, oldValue);686 }687

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

lines 688–693why, one step back
688 // Fill-in appropriate missing values. Long winded but easy to follow.
689 if (val == null) {690 if (option.negate) {691 val = false;692 } else if (option.isBoolean() || option.optional) {693 val = true;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 694why, one step back
694 } else {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 696–697why, one step back
696 }
697 }

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

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 704–705why, one step back
704 });
705

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

lines 706–712why, one step back
706 if (option.envVar) {
707 this.on('optionEnv:' + oname, (val) => {708 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;709 handleOptionValue(val, invalidValueMessage, 'env');710 });711 }712

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 713–718why, one step back
713 return this;
714 }715716 /**717 * Internal implementation shared by .option() and .requiredOption()718 *

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

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

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

line 720why, one step back
720 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

line 727why, one step back
727 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 728–747why, one step back
728 const option = this.createOption(flags, description);
729 option.makeOptionMandatory(!!config.mandatory);730 if (typeof fn === 'function') {731 option.default(defaultValue).argParser(fn);732 } else if (fn instanceof RegExp) {733 // deprecated734 const regex = fn;735 fn = (val, def) => {736 const m = regex.exec(val);737 return m ? m[0] : def;738 };739 option.default(defaultValue).argParser(fn);740 } else {741 option.default(fn);742 }743744 return this.addOption(option);745 }746747 /**

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 749why, one step back
749 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 752why, one step back
752 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 754–755why, one step back
754 *
755 * @example

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 756–760why, one step back
756 * program
757 * .option('-p, --pepper', 'add pepper')758 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument759 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default760 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 761–763why, one step back
761 *
762 * @param {string} flags763 * @param {string} [description]

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 765–768why, one step back
765 * @param {*} [defaultValue]
766 * @return {Command} `this` command for chaining767 */768

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

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

line 771why, one step back
771 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 772–773why, one step back
772
773 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 774–784why, one step back
774 * Add a required option which must have a value after parsing. This usually means
775 * the option must be specified on the command line. (Otherwise the same as .option().)776 *777 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.778 *779 * @param {string} flags780 * @param {string} [description]781 * @param {(Function|*)} [parseArg] - custom option processing function or default value782 * @param {*} [defaultValue]783 * @return {Command} `this` command for chaining784 */

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 785why, one step back
785

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 787–793why, one step back
787 return this._optionEx(
788 { mandatory: true },789 flags,790 description,791 parseArg,792 defaultValue,793 );

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

line 794why, one step back
794 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 795–803why, one step back
795
796 /**797 * Alter parsing of short flags with optional values.798 *799 * @example800 * // for `.option('-f,--flag [value]'):801 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour802 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`803 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 806–809why, one step back
806 */
807 combineFlagAndOptionalValue(combine = true) {808 this._combineFlagAndOptionalValue = !!combine;809 return this;

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

line 810why, one step back
810 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 811–814why, one step back
811
812 /**813 * Allow unknown options on the command line.814 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 817–820why, one step back
817 */
818 allowUnknownOption(allowUnknown = true) {819 this._allowUnknownOption = !!allowUnknown;820 return this;

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

line 821why, one step back
821 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 822–825why, one step back
822
823 /**824 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.825 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 828–831why, one step back
828 */
829 allowExcessArguments(allowExcess = true) {830 this._allowExcessArguments = !!allowExcess;831 return this;

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

line 832why, one step back
832 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 833–838why, one step back
833
834 /**835 * Enable positional options. Positional means global options are specified before subcommands which lets836 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.837 * The default behaviour is non-positional and global options may appear anywhere on the command line.838 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 841–844why, one step back
841 */
842 enablePositionalOptions(positional = true) {843 this._enablePositionalOptions = !!positional;844 return this;

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

line 845why, one step back
845 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 846–852why, one step back
846
847 /**848 * Pass through options that come after command-arguments rather than treat them as command-options,849 * so actual command-options come before command-arguments. Turning this on for a subcommand requires850 * positional options to have been enabled on the program (parent commands).851 * The default behaviour is non-positional and options may appear before or after command-arguments.852 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 855–857why, one step back
855 */
856 passThroughOptions(passThrough = true) {857 this._passThroughOptions = !!passThrough;

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 859why, one step back
859 return this;

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

line 860why, one step back
860 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 861–862why, one step back
861
862 /**

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

lines 863–866why, one step back
863 * @private
864 */865866 _checkForBrokenPassThrough() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 867–874why, one step back
867 if (
868 this.parent &&869 this._passThroughOptions &&870 !this.parent._enablePositionalOptions871 ) {872 throw new Error(873 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,874 );

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

lines 875–878why, one step back
875 }
876 }877878 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 879–884why, one step back
879 * Whether to store option values as properties on command object,
880 * or store separately (specify false). In both cases the option values can be accessed using .opts().881 *882 * @param {boolean} [storeAsProperties=true]883 * @return {Command} `this` command for chaining884 */

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 885–889why, one step back
885
886 storeOptionsAsProperties(storeAsProperties = true) {887 if (this.options.length) {888 throw new Error('call .storeOptionsAsProperties() before adding options');889 }

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 891–893why, one step back
891 throw new Error(
892 'call .storeOptionsAsProperties() before setting option values',893 );

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

line 894why, one step back
894 }

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 896why, one step back
896 return this;

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

line 897why, one step back
897 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 898–902why, one step back
898
899 /**900 * Retrieve option value.901 *902 * @param {string} key

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 904–910why, one step back
904 */
905906 getOptionValue(key) {907 if (this._storeOptionsAsProperties) {908 return this[key];909 }910 return this._optionValues[key];

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

line 911why, one step back
911 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 912–916why, one step back
912
913 /**914 * Store option value.915 *916 * @param {string} key

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 918–921why, one step back
918 * @return {Command} `this` command for chaining
919 */920921 setOptionValue(key, value) {

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

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

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

line 923why, one step back
923 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 924–925why, one step back
924
925 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 926–928why, one step back
926 * Store option value and where the value came from.
927 *928 * @param {string} key

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 930–932why, one step back
930 * @param {string} source - expected values are default/config/env/cli/implied
931 * @return {Command} `this` command for chaining932 */

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 933–934why, one step back
933
934 setOptionValueWithSource(key, value, source) {

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

lines 935–939why, one step back
935 if (this._storeOptionsAsProperties) {
936 this[key] = value;937 } else {938 this._optionValues[key] = value;939 }

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

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 941why, one step back
941 return this;

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

lines 942–944why, one step back
942 }
943944 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 951–953why, one step back
951
952 getOptionValueSource(key) {953 return this._optionValueSources[key];

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

line 954why, one step back
954 }

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 955–956why, one step back
955
956 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 957–962why, one step back
957 * Get source of option value. See also .optsWithGlobals().
958 * Expected values are default | config | env | cli | implied959 *960 * @param {string} key961 * @return {string}962 */

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

lines 963–966why, one step back
963
964 getOptionValueSourceWithGlobals(key) {965 // global overwrites local, like optsWithGlobals966 let source;

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

lines 968–975why, one step back
968 if (cmd.getOptionValueSource(key) !== undefined) {
969 source = cmd.getOptionValueSource(key);970 }971 });972 return source;973 }974975 /**

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 978why, one step back
978 *

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

line 979why, one step back
979 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 980–987why, one step back
980 */
981982 _prepareUserArgs(argv, parseOptions) {983 if (argv !== undefined && !Array.isArray(argv)) {984 throw new Error('first parameter to parse must be array or undefined');985 }986 parseOptions = parseOptions || {};987

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 991–992why, one step back
991 parseOptions.from = 'electron';
992 }

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

lines 993–1002why, one step back
993 // check node specific options for scenarios where user CLI args follow executable without scriptname
994 const execArgv = process.execArgv ?? [];995 if (996 execArgv.includes('-e') ||997 execArgv.includes('--eval') ||998 execArgv.includes('-p') ||999 execArgv.includes('--print')1000 ) {1001 parseOptions.from = 'eval'; // internal usage, not documented1002 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1003why, one step back
1003 }

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

lines 1004–1008why, one step back
1004
1005 // default to using process.argv1006 if (argv === undefined) {1007 argv = process.argv;1008 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1012–1019why, one step back
1012 let userArgs;
1013 switch (parseOptions.from) {1014 case undefined:1015 case 'node':1016 this._scriptPath = argv[1];1017 userArgs = argv.slice(2);1018 break;1019 case 'electron':

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1021–1030why, one step back
1021 if (process.defaultApp) {
1022 this._scriptPath = argv[1];1023 userArgs = argv.slice(2);1024 } else {1025 userArgs = argv.slice(1);1026 }1027 break;1028 case 'user':1029 userArgs = argv.slice(0);1030 break;

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

lines 1031–1033why, one step back
1031 case 'eval':
1032 userArgs = argv.slice(1);1033 break;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1034why, one step back
1034 default:

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1038–1039why, one step back
1038 }
1039

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1044–1050why, one step back
1044
1045 return userArgs;1046 }10471048 /**1049 * Parse `argv`, setting options and invoking commands when defined.1050 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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–1059why, one step back
1053 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1054 *1055 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1056 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1057 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1058 * - `'user'`: just user arguments1059 *

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1060why, one step back
1060 * @example

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1068–1075why, one step back
1068 * @return {Command} `this` command for chaining
1069 */10701071 parse(argv, parseOptions) {1072 const userArgs = this._prepareUserArgs(argv, parseOptions);1073 this._parseCommand([], userArgs);10741075 return this;

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

line 1076why, one step back
1076 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1077–1080why, one step back
1077
1078 /**1079 * Parse `argv`, setting options and invoking commands when defined.1080 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1082why, one step back
1082 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1087–1088why, one step back
1087 *
1088 * @example

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1096–1103why, one step back
1096 * @return {Promise}
1097 */10981099 async parseAsync(argv, parseOptions) {1100 const userArgs = this._prepareUserArgs(argv, parseOptions);1101 await this._parseCommand([], userArgs);11021103 return this;

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

line 1104why, one step back
1104 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1105–1108why, one step back
1105
1106 /**1107 * Execute a sub-command executable.1108 *

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

line 1109why, one step back
1109 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

lines 1117–1120why, one step back
1117 function findFile(baseDir, baseName) {
1118 // Look for specified file1119 const localBin = path.resolve(baseDir, baseName);1120 if (fs.existsSync(localBin)) return localBin;

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1121why, one step back
1121

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1124why, one step back
1124

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 1129–1131why, one step back
1129 if (foundExt) return `${localBin}${foundExt}`;
11301131 return undefined;

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1132–1133why, one step back
1132 }
1133

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

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

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

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 1141–1145why, one step back
1141 let executableDir = this._executableDir || '';
1142 if (this._scriptPath) {1143 let resolvedScriptPath; // resolve possible symlink for installed npm binary1144 try {1145 resolvedScriptPath = fs.realpathSync(this._scriptPath);

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

line 1146why, one step back
1146 } catch {

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

lines 1147–1148why, one step back
1147 resolvedScriptPath = this._scriptPath;
1148 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1149–1152why, one step back
1149 executableDir = path.resolve(
1150 path.dirname(resolvedScriptPath),1151 executableDir,1152 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1153–1154why, one step back
1153 }
1154

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

lines 1155–1160why, one step back
1155 // Look for a local file in preference to a command in PATH.
1156 if (executableDir) {1157 let localFile = findFile(executableDir, executableFile);11581159 // Legacy search using prefix of script name instead of command name1160 if (!localFile && !subcommand._executableFile && this._scriptPath) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1161–1164why, one step back
1161 const legacyName = path.basename(
1162 this._scriptPath,1163 path.extname(this._scriptPath),1164 );

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1166–1169why, one step back
1166 localFile = findFile(
1167 executableDir,1168 `${legacyName}-${subcommand._name}`,1169 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1170why, one step back
1170 }

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

lines 1171–1172why, one step back
1171 }
1172 executableFile = localFile || executableFile;

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1173–1174why, one step back
1173 }
1174

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1177–1179why, one step back
1177 let proc;
1178 if (process.platform !== 'win32') {1179 if (launchWithNode) {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1187–1188why, one step back
1187 }
1188 } else {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1190–1194why, one step back
1190 // add executable arguments to spawn
1191 args = incrementNodeInspectorPort(process.execArgv).concat(args);1192 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1193 }1194

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

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

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

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

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

lines 1202–1204why, one step back
1202 proc.kill(signal);
1203 }1204 });

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1205why, one step back
1205 });

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

line 1206why, one step back
1206 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1207–1209why, one step back
1207
1208 // By default terminate process when spawned process terminates.1209 const exitCallback = this._exitCallback;

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

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1215–1221why, one step back
1215 exitCallback(
1216 new CommanderError(1217 code,1218 'commander.executeSubCommandAsync',1219 '(close)',1220 ),1221 );

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

lines 1222–1223why, one step back
1222 }
1223 });

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1231why, one step back
1231 - 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 1232–1233why, one step back
1232 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1233 - ${executableDirMessage}`;

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1238–1241why, one step back
1238 }
1239 if (!exitCallback) {1240 process.exit(1);1241 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1242–1246why, one step back
1242 const wrappedError = new CommanderError(
1243 1,1244 'commander.executeSubCommandAsync',1245 '(error)',1246 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1247–1253why, one step back
1247 wrappedError.nestedError = err;
1248 exitCallback(wrappedError);1249 }1250 });12511252 // Store the reference to the child process1253 this.runningCommand = proc;

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

line 1254why, one step back
1254 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1255–1256why, one step back
1255
1256 /**

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

line 1257why, one step back
1257 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1258–1263why, one step back
1258 */
12591260 _dispatchSubcommand(commandName, operands, unknown) {1261 const subCommand = this._findCommand(commandName);1262 if (!subCommand) this.help({ error: true });1263

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1264why, one step back
1264 let promiseChain;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1265–1269why, one step back
1265 promiseChain = this._chainOrCallSubCommandHook(
1266 promiseChain,1267 subCommand,1268 'preSubcommand',1269 );

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

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

lines 1271–1276why, one step back
1271 if (subCommand._executableHandler) {
1272 this._executeSubCommand(subCommand, operands.concat(unknown));1273 } else {1274 return subCommand._parseCommand(operands, unknown);1275 }1276 });

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1277why, one step back
1277 return promiseChain;

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

line 1278why, one step back
1278 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1279–1280why, one step back
1279
1280 /**

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

lines 1281–1283why, one step back
1281 * Invoke help directly if possible, or dispatch if necessary.
1282 * e.g. help foo1283 *

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

line 1284why, one step back
1284 * @private

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

lines 1285–1296why, one step back
1285 */
12861287 _dispatchHelpCommand(subcommandName) {1288 if (!subcommandName) {1289 this.help();1290 }1291 const subCommand = this._findCommand(subcommandName);1292 if (subCommand && !subCommand._executableHandler) {1293 subCommand.help();1294 }12951296 // Fallback to parsing the help flag to invoke the help.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1297–1301why, one step back
1297 return this._dispatchSubcommand(
1298 subcommandName,1299 [],1300 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1301 );

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

lines 1302–1304why, one step back
1302 }
13031304 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1306why, one step back
1306 *

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

line 1307why, one step back
1307 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1308–1311why, one step back
1308 */
13091310 _checkNumberOfArguments() {1311 // too few

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1313–1317why, one step back
1313 if (arg.required && this.args[i] == null) {
1314 this.missingArgument(arg.name());1315 }1316 });1317 // too many

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1318–1321why, one step back
1318 if (
1319 this.registeredArguments.length > 0 &&1320 this.registeredArguments[this.registeredArguments.length - 1].variadic1321 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1322–1323why, one step back
1322 return;
1323 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1325–1326why, one step back
1325 this._excessArguments(this.args);
1326 }

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

line 1327why, one step back
1327 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1328–1329why, one step back
1328
1329 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1331why, one step back
1331 *

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

line 1332why, one step back
1332 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1333–1339why, one step back
1333 */
13341335 _processArguments() {1336 const myParseArg = (argument, value, previous) => {1337 // Extra processing for nice error message on parsing failure.1338 let parsedValue = value;1339 if (value !== null && argument.parseArg) {

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1341–1346why, one step back
1341 parsedValue = this._callParseArg(
1342 argument,1343 value,1344 previous,1345 invalidValueMessage,1346 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1347–1353why, one step back
1347 }
1348 return parsedValue;1349 };13501351 this._checkNumberOfArguments();13521353 const processedArgs = [];

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1355–1381why, one step back
1355 let value = declaredArg.defaultValue;
1356 if (declaredArg.variadic) {1357 // Collect together remaining arguments for passing together as an array.1358 if (index < this.args.length) {1359 value = this.args.slice(index);1360 if (declaredArg.parseArg) {1361 value = value.reduce((processed, v) => {1362 return myParseArg(declaredArg, v, processed);1363 }, declaredArg.defaultValue);1364 }1365 } else if (value === undefined) {1366 value = [];1367 }1368 } else if (index < this.args.length) {1369 value = this.args[index];1370 if (declaredArg.parseArg) {1371 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1372 }1373 }1374 processedArgs[index] = value;1375 });1376 this.processedArgs = processedArgs;1377 }13781379 /**1380 * Once we have a promise we chain, but call synchronously until then.1381 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1386–1399why, one step back
1386 */
13871388 _chainOrCall(promise, fn) {1389 // thenable1390 if (promise && promise.then && typeof promise.then === 'function') {1391 // already have a promise, chain callback1392 return promise.then(() => fn());1393 }1394 // callback might return a promise1395 return fn();1396 }13971398 /**1399 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1404–1408why, one step back
1404 */
14051406 _chainOrCallHooks(promise, event) {1407 let result = promise;1408 const hooks = [];

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1413–1425why, one step back
1413 hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1414 hooks.push({ hookedCommand, callback });1415 });1416 });1417 if (event === 'postAction') {1418 hooks.reverse();1419 }14201421 hooks.forEach((hookDetail) => {1422 result = this._chainOrCall(result, () => {1423 return hookDetail.callback(hookDetail.hookedCommand, this);1424 });1425 });

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

lines 1426–1430why, one step back
1426 return result;
1427 }14281429 /**1430 *

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

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

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

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

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

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

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

lines 1436–1446why, one step back
1436 */
14371438 _chainOrCallSubCommandHook(promise, subCommand, event) {1439 let result = promise;1440 if (this._lifeCycleHooks[event] !== undefined) {1441 this._lifeCycleHooks[event].forEach((hook) => {1442 result = this._chainOrCall(result, () => {1443 return hook(this, subCommand);1444 });1445 });1446 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1447–1453why, one step back
1447 return result;
1448 }14491450 /**1451 * Process arguments in context of this command.1452 * Returns action result, in case it is a promise.1453 *

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

line 1454why, one step back
1454 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1455–1458why, one step back
1455 */
14561457 _parseCommand(operands, unknown) {1458 const parsed = this.parseOptions(unknown);

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

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1461–1467why, one step back
1461 operands = operands.concat(parsed.operands);
1462 unknown = parsed.unknown;1463 this.args = operands.concat(unknown);14641465 if (operands && this._findCommand(operands[0])) {1466 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1467 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1468–1471why, one step back
1468 if (
1469 this._getHelpCommand() &&1470 operands[0] === this._getHelpCommand().name()1471 ) {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1473–1474why, one step back
1473 }
1474 if (this._defaultCommandName) {

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

line 1475why, one step back
1475 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 1476–1480why, one step back
1476 return this._dispatchSubcommand(
1477 this._defaultCommandName,1478 operands,1479 unknown,1480 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1481why, one step back
1481 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1482–1487why, one step back
1482 if (
1483 this.commands.length &&1484 this.args.length === 0 &&1485 !this._actionHandler &&1486 !this._defaultCommandName1487 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1488–1491why, one step back
1488 // probably missing subcommand and no handler, user needs help (and exit)
1489 this.help({ error: true });1490 }1491

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1495–1507why, one step back
1495
1496 // We do not always call this check to avoid masking a "better" error, like unknown command.1497 const checkForUnknownOptions = () => {1498 if (parsed.unknown.length > 0) {1499 this.unknownOption(parsed.unknown[0]);1500 }1501 };15021503 const commandEvent = `command:${this.name()}`;1504 if (this._actionHandler) {1505 checkForUnknownOptions();1506 this._processArguments();1507

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1510–1512why, one step back
1510 promiseChain = this._chainOrCall(promiseChain, () =>
1511 this._actionHandler(this.processedArgs),1512 );

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

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

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

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

lines 1515–1517why, one step back
1515 this.parent.emit(commandEvent, operands, unknown); // legacy
1516 });1517 }

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1520–1525why, one step back
1520 }
1521 if (this.parent && this.parent.listenerCount(commandEvent)) {1522 checkForUnknownOptions();1523 this._processArguments();1524 this.parent.emit(commandEvent, operands, unknown); // legacy1525 } else if (operands.length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1528–1539why, one step back
1528 return this._dispatchSubcommand('*', operands, unknown);
1529 }1530 if (this.listenerCount('command:*')) {1531 // skip option check, emit event for possible misspelling suggestion1532 this.emit('command:*', operands, unknown);1533 } else if (this.commands.length) {1534 this.unknownCommand();1535 } else {1536 checkForUnknownOptions();1537 this._processArguments();1538 }1539 } else if (this.commands.length) {

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1541–1547why, one step back
1541 // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1542 this.help({ error: true });1543 } else {1544 checkForUnknownOptions();1545 this._processArguments();1546 // fall through for caller to handle after calling .parse()1547 }

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

line 1548why, one step back
1548 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1549–1552why, one step back
1549
1550 /**1551 * Find matching command.1552 *

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

line 1553why, one step back
1553 * @private

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1555–1557why, one step back
1555 */
1556 _findCommand(name) {1557 if (!name) return undefined;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1558–1560why, one step back
1558 return this.commands.find(
1559 (cmd) => cmd._name === name || cmd._aliases.includes(name),1560 );

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

line 1561why, one step back
1561 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1562–1567why, one step back
1562
1563 /**1564 * Return an option matching `arg` if any.1565 *1566 * @param {string} arg1567 * @return {Option}

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

line 1568why, one step back
1568 * @package

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1569–1571why, one step back
1569 */
15701571 _findOption(arg) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

line 1573why, one step back
1573 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1574–1576why, one step back
1574
1575 /**1576 * Display an error message if a mandatory option does not have a value.

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1578why, one step back
1578 *

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

line 1579why, one step back
1579 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1586–1589why, one step back
1586 if (
1587 anOption.mandatory &&1588 cmd.getOptionValue(anOption.attributeName()) === undefined1589 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1590–1592why, one step back
1590 cmd.missingMandatoryOptionValue(anOption);
1591 }1592 });

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1593why, one step back
1593 });

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

line 1594why, one step back
1594 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1595–1596why, one step back
1595
1596 /**

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

line 1597why, one step back
1597 * 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 1598why, one step back
1598 *

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

line 1599why, one step back
1599 * @private

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

line 1600why, one step back
1600 */

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1602–1605why, one step back
1602 const definedNonDefaultOptions = this.options.filter((option) => {
1603 const optionKey = option.attributeName();1604 if (this.getOptionValue(optionKey) === undefined) {1605 return false;

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

line 1606why, one step back
1606 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 1609–1610why, one step back
1609
1610 const optionsWithConflicting = definedNonDefaultOptions.filter(

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 1612–1615why, one step back
1612 );
16131614 optionsWithConflicting.forEach((option) => {1615 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

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

lines 1617–1621why, one step back
1617 );
1618 if (conflictingAndDefined) {1619 this._conflictingOption(option, conflictingAndDefined);1620 }1621 });

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

lines 1622–1627why, one step back
1622 }
16231624 /**1625 * Display an error message if conflicting options are used together.1626 * Called after checking for help flags in leaf subcommand.1627 *

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

line 1628why, one step back
1628 * @private

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

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

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

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1634why, one step back
1634 });

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

lines 1635–1637why, one step back
1635 }
16361637 /**

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1638–1648why, one step back
1638 * Parse options from `argv` removing known options,
1639 * and return argv split into operands and unknown arguments.1640 *1641 * Examples:1642 *1643 * argv => operands, unknown1644 * --known kkk op => [op], []1645 * op --known kkk => [op], []1646 * sub --unknown uuu op => [sub], [--unknown uuu op]1647 * sub -- --unknown uuu op => [sub --unknown uuu op], []1648 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1651–1695why, one step back
1651 */
16521653 parseOptions(argv) {1654 const operands = []; // operands, not options or values1655 const unknown = []; // first unknown option and remaining unknown args1656 let dest = operands;1657 const args = argv.slice();16581659 function maybeOption(arg) {1660 return arg.length > 1 && arg[0] === '-';1661 }16621663 // parse options1664 let activeVariadicOption = null;1665 while (args.length) {1666 const arg = args.shift();16671668 // literal1669 if (arg === '--') {1670 if (dest === unknown) dest.push(arg);1671 dest.push(...args);1672 break;1673 }16741675 if (activeVariadicOption && !maybeOption(arg)) {1676 this.emit(`option:${activeVariadicOption.name()}`, arg);1677 continue;1678 }1679 activeVariadicOption = null;16801681 if (maybeOption(arg)) {1682 const option = this._findOption(arg);1683 // recognised option, call listener to assign value with possible custom processing1684 if (option) {1685 if (option.required) {1686 const value = args.shift();1687 if (value === undefined) this.optionMissingArgument(option);1688 this.emit(`option:${option.name()}`, value);1689 } else if (option.optional) {1690 let value = null;1691 // historical behaviour is optional value is following arg unless an option1692 if (args.length > 0 && !maybeOption(args[0])) {1693 value = args.shift();1694 }1695 this.emit(`option:${option.name()}`, value);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1696–1697why, one step back
1696 } else {
1697 // boolean flag

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1698–1708why, one step back
1698 this.emit(`option:${option.name()}`);
1699 }1700 activeVariadicOption = option.variadic ? option : null;1701 continue;1702 }1703 }17041705 // Look for combo options following single dash, eat first one if known.1706 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1707 const option = this._findOption(`-${arg[1]}`);1708 if (option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1709–1712why, one step back
1709 if (
1710 option.required ||1711 (option.optional && this._combineFlagAndOptionalValue)1712 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1713–1742why, one step back
1713 // option with value following in same argument
1714 this.emit(`option:${option.name()}`, arg.slice(2));1715 } else {1716 // boolean option, emit and put back remainder of arg for further processing1717 this.emit(`option:${option.name()}`);1718 args.unshift(`-${arg.slice(2)}`);1719 }1720 continue;1721 }1722 }17231724 // Look for known long flag with value, like --foo=bar1725 if (/^--[^=]+=/.test(arg)) {1726 const index = arg.indexOf('=');1727 const option = this._findOption(arg.slice(0, index));1728 if (option && (option.required || option.optional)) {1729 this.emit(`option:${option.name()}`, arg.slice(index + 1));1730 continue;1731 }1732 }17331734 // Not a recognised option by this command.1735 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.17361737 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1738 if (maybeOption(arg)) {1739 dest = unknown;1740 }17411742 // If using positionalOptions, stop processing our options at subcommand.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1743–1747why, one step back
1743 if (
1744 (this._enablePositionalOptions || this._passThroughOptions) &&1745 operands.length === 0 &&1746 unknown.length === 01747 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1748–1751why, one step back
1748 if (this._findCommand(arg)) {
1749 operands.push(arg);1750 if (args.length > 0) unknown.push(...args);1751 break;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1752–1755why, one step back
1752 } else if (
1753 this._getHelpCommand() &&1754 arg === this._getHelpCommand().name()1755 ) {

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1756–1777why, one step back
1756 operands.push(arg);
1757 if (args.length > 0) operands.push(...args);1758 break;1759 } else if (this._defaultCommandName) {1760 unknown.push(arg);1761 if (args.length > 0) unknown.push(...args);1762 break;1763 }1764 }17651766 // If using passThroughOptions, stop processing options at first command-argument.1767 if (this._passThroughOptions) {1768 dest.push(arg);1769 if (args.length > 0) dest.push(...args);1770 break;1771 }17721773 // add arg1774 dest.push(arg);1775 }17761777 return { operands, unknown };

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

line 1778why, one step back
1778 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1779–1780why, one step back
1779
1780 /**

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1782why, one step back
1782 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1784–1792why, one step back
1784 */
1785 opts() {1786 if (this._storeOptionsAsProperties) {1787 // Preserve original behaviour so backwards compatible when still using properties1788 const result = {};1789 const len = this.options.length;17901791 for (let i = 0; i < len; i++) {1792 const key = this.options[i].attributeName();

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1795–1799why, one step back
1795 }
1796 return result;1797 }17981799 return this._optionValues;

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

line 1800why, one step back
1800 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1801–1802why, one step back
1801
1802 /**

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1804why, one step back
1804 *

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

line 1806why, one step back
1806 */

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

lines 1807–1808why, one step back
1807 optsWithGlobals() {
1808 // globals overwrite locals

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1811why, one step back
1811 {},

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

lines 1812–1818why, one step back
1812 );
1813 }18141815 /**1816 * Display error message and exit (or call exitOverride).1817 *1818 * @param {string} message

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

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

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

lines 1820–1824why, one step back
1820 * @param {string} [errorOptions.code] - an id string representing the error
1821 * @param {number} [errorOptions.exitCode] - used with process.exit1822 */1823 error(message, errorOptions) {1824 // output handling

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1825–1828why, one step back
1825 this._outputConfiguration.outputError(
1826 `${message}\n`,1827 this._outputConfiguration.writeErr,1828 );

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1829–1834why, one step back
1829 if (typeof this._showHelpAfterError === 'string') {
1830 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1831 } else if (this._showHelpAfterError) {1832 this._outputConfiguration.writeErr('\n');1833 this.outputHelp({ error: true });1834 }

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

lines 1835–1839why, one step back
1835
1836 // exit handling1837 const config = errorOptions || {};1838 const exitCode = config.exitCode || 1;1839 const code = config.code || 'commander.error';

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

lines 1841–1846why, one step back
1841 }
18421843 /**1844 * Apply any option related environment variables, if option does1845 * not have a value from cli or client code.1846 *

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

line 1847why, one step back
1847 * @private

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

lines 1848–1852why, one step back
1848 */
1849 _parseOptionsEnv() {1850 this.options.forEach((option) => {1851 if (option.envVar && option.envVar in process.env) {1852 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1854–1861why, one step back
1854 if (
1855 this.getOptionValue(optionKey) === undefined ||1856 ['default', 'config', 'env'].includes(1857 this.getOptionValueSource(optionKey),1858 )1859 ) {1860 if (option.required || option.optional) {1861 // option can take a value

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1864–1865why, one step back
1864 } else {
1865 // boolean

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

lines 1866–1871why, one step back
1866 // keep very simple, only care that envVar defined and not the value
1867 this.emit(`optionEnv:${option.name()}`);1868 }1869 }1870 }1871 });

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

lines 1872–1876why, one step back
1872 }
18731874 /**1875 * Apply any implied option values, if option is undefined or default value.1876 *

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

line 1877why, one step back
1877 * @private

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

lines 1878–1881why, one step back
1878 */
1879 _parseOptionsImplied() {1880 const dualHelper = new DualOptions(this.options);1881 const hasCustomOptionValue = (optionKey) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1882–1885why, one step back
1882 return (
1883 this.getOptionValue(optionKey) !== undefined &&1884 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1885 );

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

lines 1886–1887why, one step back
1886 };
1887 this.options

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1888–1896why, one step back
1888 .filter(
1889 (option) =>1890 option.implied !== undefined &&1891 hasCustomOptionValue(option.attributeName()) &&1892 dualHelper.valueFromOption(1893 this.getOptionValue(option.attributeName()),1894 option,1895 ),1896 )

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

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

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1899–1905why, one step back
1899 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
1900 .forEach((impliedKey) => {1901 this.setOptionValueWithSource(1902 impliedKey,1903 option.implied[impliedKey],1904 'implied',1905 );

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

lines 1906–1907why, one step back
1906 });
1907 });

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1908–1913why, one step back
1908 }
19091910 /**1911 * Argument `name` is missing.1912 *1913 * @param {string} name

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

line 1914why, one step back
1914 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1921–1925why, one step back
1921
1922 /**1923 * `Option` is missing an argument.1924 *1925 * @param {Option} option

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

line 1926why, one step back
1926 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1933–1937why, one step back
1933
1934 /**1935 * `Option` does not have a value, and is a mandatory option.1936 *1937 * @param {Option} option

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

line 1938why, one step back
1938 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

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

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

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

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

lines 1944–1950why, one step back
1944 }
19451946 /**1947 * `Option` conflicts with another option.1948 *1949 * @param {Option} option1950 * @param {Option} conflictingOption

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

line 1951why, one step back
1951 * @private

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

lines 1952–1958why, one step back
1952 */
1953 _conflictingOption(option, conflictingOption) {1954 // The calling code does not know whether a negated option is the source of the1955 // value, so do some work to take an educated guess.1956 const findBestOptionFromValue = (option) => {1957 const optionKey = option.attributeName();1958 const optionValue = this.getOptionValue(optionKey);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1959–1970why, one step back
1959 const negativeOption = this.options.find(
1960 (target) => target.negate && optionKey === target.attributeName(),1961 );1962 const positiveOption = this.options.find(1963 (target) => !target.negate && optionKey === target.attributeName(),1964 );1965 if (1966 negativeOption &&1967 ((negativeOption.presetArg === undefined && optionValue === false) ||1968 (negativeOption.presetArg !== undefined &&1969 optionValue === negativeOption.presetArg))1970 ) {

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

lines 1971–1987why, one step back
1971 return negativeOption;
1972 }1973 return positiveOption || option;1974 };19751976 const getErrorMessage = (option) => {1977 const bestOption = findBestOptionFromValue(option);1978 const optionKey = bestOption.attributeName();1979 const source = this.getOptionValueSource(optionKey);1980 if (source === 'env') {1981 return `environment variable '${bestOption.envVar}'`;1982 }1983 return `option '${bestOption.flags}'`;1984 };19851986 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1987 this.error(message, { code: 'commander.conflictingOption' });

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

line 1988why, one step back
1988 }

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1989–1993why, one step back
1989
1990 /**1991 * Unknown option `flag`.1992 *1993 * @param {string} flag

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

line 1994why, one step back
1994 * @private

Clarify that more than just READMEJohn Geebefore adoption411ca95

lines 1995–1998why, one step back
1995 */
19961997 unknownOption(flag) {1998 if (this._allowUnknownOption) return;

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

lines 1999–2003why, one step back
1999 let suggestion = '';
2000

The first 2,000 of 2,585 lines.