Skip to content
Myr

command.js

This file

Path

lib/command.js

2,098 lines · 66.0 KiB · JavaScript

Last changed by

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

History of this file

Take it

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1–4why, one step back
1const EventEmitter = require('events').EventEmitter;
2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');

Follow best practice and require process rather than use global (#1685)John Geebefore adoption47e8b20

line 5why, one step back
5const process = require('process');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 6–10why, one step back
6
7const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, splitOptionFlags } = require('./option.js');

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 12–23why, one step back
12
13// @ts-check1415class Command extends EventEmitter {16 /**17 * Initialize a new `Command`.18 *19 * @param {string} [name]20 */2122 constructor(name) {23 super();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 32why, one step back
32 this._args = [];

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

lines 33–36why, one step back
33 /** @type {string[]} */
34 this.args = []; // cli args with options removed35 this.rawArgs = [];36 this.processedArgs = []; // like .args but after custom processing and collecting variadic

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 37–39why, one step back
37 this._scriptPath = null;
38 this._name = name || '';39 this._optionValues = {};

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 40why, one step back
40 this._optionValueSources = {}; // default < config < env < cli

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 46–54why, one step back
46 this._defaultCommandName = null;
47 this._exitCallback = null;48 this._aliases = [];49 this._combineFlagAndOptionalValue = true;50 this._description = '';51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arrays

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 55–56why, one step back
55 /** @type {boolean | string} */
56 this._showHelpAfterError = false;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 58–81why, one step back
58
59 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65 outputError: (str, write) => write(str)66 };6768 this._hidden = false;69 this._hasHelpOption = true;70 this._helpFlags = '-h, --help';71 this._helpDescription = 'display help for command';72 this._helpShortFlag = '-h';73 this._helpLongFlag = '--help';74 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false75 this._helpCommandName = 'help';76 this._helpCommandnameAndArgs = 'help [command]';77 this._helpCommandDescription = 'display help for command';78 this._helpConfiguration = {};79 }8081 /**

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

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

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 88–105why, one step back
88 */
89 copyInheritedSettings(sourceCommand) {90 this._outputConfiguration = sourceCommand._outputConfiguration;91 this._hasHelpOption = sourceCommand._hasHelpOption;92 this._helpFlags = sourceCommand._helpFlags;93 this._helpDescription = sourceCommand._helpDescription;94 this._helpShortFlag = sourceCommand._helpShortFlag;95 this._helpLongFlag = sourceCommand._helpLongFlag;96 this._helpCommandName = sourceCommand._helpCommandName;97 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;98 this._helpCommandDescription = sourceCommand._helpCommandDescription;99 this._helpConfiguration = sourceCommand._helpConfiguration;100 this._exitCallback = sourceCommand._exitCallback;101 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;102 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;103 this._allowExcessArguments = sourceCommand._allowExcessArguments;104 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;105 this._showHelpAfterError = sourceCommand._showHelpAfterError;

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

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 107–111why, one step back
107
108 return this;109 }110111 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 112–115why, one step back
112 * Define a command.
113 *114 * There are two styles of command: pay attention to where to put the description.115 *

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

lines 116–123why, one step back
116 * @example
117 * // Command implemented using action handler (description is supplied separately to `.command`)118 * program119 * .command('clone <source> [destination]')120 * .description('clone a repository into a newly created directory')121 * .action((source, destination) => {122 * console.log('clone command called');123 * });

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 124why, one step back
124 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 129–145why, one step back
129 *
130 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`131 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)132 * @param {Object} [execOpts] - configuration options (for executable)133 * @return {Command} returns new command for action handler, or `this` for executable command134 */135136 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {137 let desc = actionOptsOrExecDesc;138 let opts = execOpts;139 if (typeof desc === 'object' && desc !== null) {140 opts = desc;141 desc = null;142 }143 opts = opts || {};144 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);145

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 147–156why, one step back
147 if (desc) {
148 cmd.description(desc);149 cmd._executableHandler = true;150 }151 if (opts.isDefault) this._defaultCommandName = cmd._name;152 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden153 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor154 if (args) cmd.arguments(args);155 this.commands.push(cmd);156 cmd.parent = this;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 158–160why, one step back
158
159 if (desc) return this;160 return cmd;

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

line 161why, one step back
161 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 162–174why, one step back
162
163 /**164 * Factory routine to create a new unattached command.165 *166 * See .command() for creating an attached subcommand, which uses this routine to167 * create the command. You can override createCommand to customise subcommands.168 *169 * @param {string} [name]170 * @return {Command} new command171 */172173 createCommand(name) {174 return new Command(name);

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

line 175why, one step back
175 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 176–185why, one step back
176
177 /**178 * You can customise the help with a subclass of Help by overriding createHelp,179 * or by overriding Help properties using configureHelp().180 *181 * @return {Help}182 */183184 createHelp() {185 return Object.assign(new Help(), this.configureHelp());

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

line 186why, one step back
186 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 187–208why, one step back
187
188 /**189 * You can customise the help by overriding Help properties using configureHelp(),190 * or with a subclass of Help by overriding createHelp().191 *192 * @param {Object} [configuration] - configuration options193 * @return {Command|Object} `this` command for chaining, or stored configuration194 */195196 configureHelp(configuration) {197 if (configuration === undefined) return this._helpConfiguration;198199 this._helpConfiguration = configuration;200 return this;201 }202203 /**204 * The default output goes to stdout and stderr. You can customise this for special205 * applications. You can also customise the display of errors by overriding outputError.206 *207 * The configuration properties are all functions:208 *

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

lines 209–216why, one step back
209 * // functions to change where being written, stdout and stderr
210 * writeOut(str)211 * writeErr(str)212 * // matching functions to specify width for wrapping help213 * getOutHelpWidth()214 * getErrHelpWidth()215 * // functions based on what is being written out216 * outputError(str, write) // used for displaying errors, and not used for displaying help

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 217–229why, one step back
217 *
218 * @param {Object} [configuration] - configuration options219 * @return {Command|Object} `this` command for chaining, or stored configuration220 */221222 configureOutput(configuration) {223 if (configuration === undefined) return this._outputConfiguration;224225 Object.assign(this._outputConfiguration, configuration);226 return this;227 }228229 /**

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 230–241why, one step back
230 * Display the help or a custom message after an error occurs.
231 *232 * @param {boolean|string} [displayHelp]233 * @return {Command} `this` command for chaining234 */235 showHelpAfterError(displayHelp = true) {236 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;237 this._showHelpAfterError = displayHelp;238 return this;239 }240241 /**

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

lines 242–252why, one step back
242 * Display suggestion of similar commands for unknown commands, or options for unknown options.
243 *244 * @param {boolean} [displaySuggestion]245 * @return {Command} `this` command for chaining246 */247 showSuggestionAfterError(displaySuggestion = true) {248 this._showSuggestionAfterError = !!displaySuggestion;249 return this;250 }251252 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 253–262why, one step back
253 * Add a prepared subcommand.
254 *255 * See .command() for creating an attached subcommand which inherits settings from its parent.256 *257 * @param {Command} cmd - new subcommand258 * @param {Object} [opts] - configuration options259 * @return {Command} `this` command for chaining260 */261262 addCommand(cmd, opts) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 266–274why, one step back
266 }
267268 opts = opts || {};269 if (opts.isDefault) this._defaultCommandName = cmd._name;270 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation271272 this.commands.push(cmd);273 cmd.parent = this;274 return this;

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

line 275why, one step back
275 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 276–289why, one step back
276
277 /**278 * Factory routine to create a new unattached argument.279 *280 * See .argument() for creating an attached argument, which uses this routine to281 * create the argument. You can override createArgument to return a custom argument.282 *283 * @param {string} name284 * @param {string} [description]285 * @return {Argument} new argument286 */287288 createArgument(name, description) {289 return new Argument(name, description);

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

line 290why, one step back
290 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 291–298why, one step back
291
292 /**293 * Define argument syntax for command.294 *295 * The default is that the argument is required, and you can explicitly296 * indicate this with <> around the name. Put [] around the name for an optional argument.297 *298 * @example

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 301–324why, one step back
301 *
302 * @param {string} name303 * @param {string} [description]304 * @param {Function|*} [fn] - custom argument processing function305 * @param {*} [defaultValue]306 * @return {Command} `this` command for chaining307 */308 argument(name, description, fn, defaultValue) {309 const argument = this.createArgument(name, description);310 if (typeof fn === 'function') {311 argument.default(defaultValue).argParser(fn);312 } else {313 argument.default(fn);314 }315 this.addArgument(argument);316 return this;317 }318319 /**320 * Define argument syntax for command, adding multiple at once (without descriptions).321 *322 * See also .argument().323 *324 * @example

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 326–335why, one step back
326 *
327 * @param {string} names328 * @return {Command} `this` command for chaining329 */330331 arguments(names) {332 names.split(/ +/).forEach((detail) => {333 this.argument(detail);334 });335 return this;

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

line 336why, one step back
336 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 337–377why, one step back
337
338 /**339 * Define argument syntax for command, adding a prepared argument.340 *341 * @param {Argument} argument342 * @return {Command} `this` command for chaining343 */344 addArgument(argument) {345 const previousArgument = this._args.slice(-1)[0];346 if (previousArgument && previousArgument.variadic) {347 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);348 }349 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {350 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);351 }352 this._args.push(argument);353 return this;354 }355356 /**357 * Override default decision whether to add implicit help command.358 *359 * addHelpCommand() // force on360 * addHelpCommand(false); // force off361 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details362 *363 * @return {Command} `this` command for chaining364 */365366 addHelpCommand(enableOrNameAndArgs, description) {367 if (enableOrNameAndArgs === false) {368 this._addImplicitHelpCommand = false;369 } else {370 this._addImplicitHelpCommand = true;371 if (typeof enableOrNameAndArgs === 'string') {372 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];373 this._helpCommandnameAndArgs = enableOrNameAndArgs;374 }375 this._helpCommandDescription = description || this._helpCommandDescription;376 }377 return this;

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

line 378why, one step back
378 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 379–389why, one step back
379
380 /**381 * @return {boolean}382 * @api private383 */384385 _hasImplicitHelpCommand() {386 if (this._addImplicitHelpCommand === undefined) {387 return this.commands.length && !this._actionHandler && !this._findCommand('help');388 }389 return this._addImplicitHelpCommand;

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

line 390why, one step back
390 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 391–433why, one step back
391
392 /**393 * Add hook for life cycle event.394 *395 * @param {string} event396 * @param {Function} listener397 * @return {Command} `this` command for chaining398 */399400 hook(event, listener) {401 const allowedValues = ['preAction', 'postAction'];402 if (!allowedValues.includes(event)) {403 throw new Error(`Unexpected value for event passed to hook : '${event}'.404Expecting one of '${allowedValues.join("', '")}'`);405 }406 if (this._lifeCycleHooks[event]) {407 this._lifeCycleHooks[event].push(listener);408 } else {409 this._lifeCycleHooks[event] = [listener];410 }411 return this;412 }413414 /**415 * Register callback to use as replacement for calling process.exit.416 *417 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing418 * @return {Command} `this` command for chaining419 */420421 exitOverride(fn) {422 if (fn) {423 this._exitCallback = fn;424 } else {425 this._exitCallback = (err) => {426 if (err.code !== 'commander.executeSubCommandAsync') {427 throw err;428 } else {429 // Async callback from spawn events, not useful to throw.430 }431 };432 }433 return this;

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

line 434why, one step back
434 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 435–451why, one step back
435
436 /**437 * Call process.exit, and _exitCallback if defined.438 *439 * @param {number} exitCode exit code for using with process.exit440 * @param {string} code an id string representing the error441 * @param {string} message human-readable description of the error442 * @return never443 * @api private444 */445446 _exit(exitCode, code, message) {447 if (this._exitCallback) {448 this._exitCallback(new CommanderError(exitCode, code, message));449 // Expecting this line is not reached.450 }451 process.exit(exitCode);

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

line 452why, one step back
452 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 453–456why, one step back
453
454 /**455 * Register callback `fn` for the command.456 *

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

lines 457–458why, one step back
457 * @example
458 * program

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

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

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

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 464–484why, one step back
464 *
465 * @param {Function} fn466 * @return {Command} `this` command for chaining467 */468469 action(fn) {470 const listener = (args) => {471 // The .action callback takes an extra parameter which is the command or options.472 const expectedArgsCount = this._args.length;473 const actionArgs = args.slice(0, expectedArgsCount);474 if (this._storeOptionsAsProperties) {475 actionArgs[expectedArgsCount] = this; // backwards compatible "options"476 } else {477 actionArgs[expectedArgsCount] = this.opts();478 }479 actionArgs.push(this);480481 return fn.apply(this, actionArgs);482 };483 this._actionHandler = listener;484 return this;

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

line 485why, one step back
485 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 486–499why, one step back
486
487 /**488 * Factory routine to create a new unattached option.489 *490 * See .option() for creating an attached option, which uses this routine to491 * create the option. You can override createOption to return a custom option.492 *493 * @param {string} flags494 * @param {string} [description]495 * @return {Option} new option496 */497498 createOption(flags, description) {499 return new Option(flags, description);

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

line 500why, one step back
500 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 501–511why, one step back
501
502 /**503 * Add an option.504 *505 * @param {Option} option506 * @return {Command} `this` command for chaining507 */508 addOption(option) {509 const oname = option.name();510 const name = option.attributeName();511

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

lines 512–517why, one step back
512 // store default value
513 if (option.negate) {514 // --no-foo is special and defaults foo to true, unless a --foo option is already defined515 const positiveLongFlag = option.long.replace(/^--no-/, '--');516 if (!this._findOption(positiveLongFlag)) {517 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 518why, one step back
518 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 521–525why, one step back
521 }
522523 // register the option524 this.options.push(option);525

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

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

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

lines 528–532why, one step back
528 // val is null for optional option used without an optional-argument.
529 // val is undefined for boolean and negated option.530 if (val == null && option.presetArg !== undefined) {531 val = option.presetArg;532 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 533–534why, one step back
533
534 // custom processing

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 536–537why, one step back
536 if (val !== null && option.parseArg) {
537 try {

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

line 538why, one step back
538 val = option.parseArg(val, oldValue);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 539–540why, one step back
539 } catch (err) {
540 if (err.code === 'commander.invalidArgument') {

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

line 541why, one step back
541 const message = `${invalidValueMessage} ${err.message}`;

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

line 542why, one step back
542 this.error(message, { exitCode: err.exitCode, code: err.code });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 543–549why, one step back
543 }
544 throw err;545 }546 } else if (val !== null && option.variadic) {547 val = option._concatValue(val, oldValue);548 }549

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

lines 550–555why, one step back
550 // Fill-in appropriate missing values. Long winded but easy to follow.
551 if (val == null) {552 if (option.negate) {553 val = false;554 } else if (option.isBoolean() || option.optional) {555 val = true;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 556why, one step back
556 } else {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 558–559why, one step back
558 }
559 }

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 566–567why, one step back
566 });
567

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

lines 568–574why, one step back
568 if (option.envVar) {
569 this.on('optionEnv:' + oname, (val) => {570 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;571 handleOptionValue(val, invalidValueMessage, 'env');572 });573 }574

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 575–583why, one step back
575 return this;
576 }577578 /**579 * Internal implementation shared by .option() and .requiredOption()580 *581 * @api private582 */583 _optionEx(config, flags, description, fn, defaultValue) {

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

lines 584–586why, one step back
584 if (typeof flags === 'object' && flags instanceof Option) {
585 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');586 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 587–613why, one step back
587 const option = this.createOption(flags, description);
588 option.makeOptionMandatory(!!config.mandatory);589 if (typeof fn === 'function') {590 option.default(defaultValue).argParser(fn);591 } else if (fn instanceof RegExp) {592 // deprecated593 const regex = fn;594 fn = (val, def) => {595 const m = regex.exec(val);596 return m ? m[0] : def;597 };598 option.default(defaultValue).argParser(fn);599 } else {600 option.default(fn);601 }602603 return this.addOption(option);604 }605606 /**607 * Define option with `flags`, `description` and optional608 * coercion `fn`.609 *610 * The `flags` string contains the short and/or long flags,611 * separated by comma, a pipe or space. The following are all valid612 * all will output this way when `--help` is used.613 *

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

lines 614–616why, one step back
614 * "-p, --pepper"
615 * "-p|--pepper"616 * "-p --pepper"

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 617why, one step back
617 *

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

lines 618–620why, one step back
618 * @example
619 * // simple boolean defaulting to undefined620 * program.option('-p, --pepper', 'add pepper');

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 621why, one step back
621 *

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

lines 622–623why, one step back
622 * program.pepper
623 * // => undefined

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 624why, one step back
624 *

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

lines 625–627why, one step back
625 * --pepper
626 * program.pepper627 * // => true

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 628why, one step back
628 *

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

lines 629–630why, one step back
629 * // simple boolean defaulting to true (unless non-negated option is also defined)
630 * program.option('-C, --no-cheese', 'remove cheese');

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 631why, one step back
631 *

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

lines 632–633why, one step back
632 * program.cheese
633 * // => true

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 634why, one step back
634 *

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

lines 635–637why, one step back
635 * --no-cheese
636 * program.cheese637 * // => false

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 638why, one step back
638 *

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

lines 639–640why, one step back
639 * // required argument
640 * program.option('-C, --chdir <path>', 'change the working directory');

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 641why, one step back
641 *

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

lines 642–644why, one step back
642 * --chdir /tmp
643 * program.chdir644 * // => "/tmp"

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 645why, one step back
645 *

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

lines 646–647why, one step back
646 * // optional argument
647 * program.option('-c, --cheese [type]', 'add cheese [marble]');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 648–657why, one step back
648 *
649 * @param {string} flags650 * @param {string} [description]651 * @param {Function|*} [fn] - custom option processing function or default value652 * @param {*} [defaultValue]653 * @return {Command} `this` command for chaining654 */655656 option(flags, description, fn, defaultValue) {657 return this._optionEx({}, flags, description, fn, defaultValue);

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

line 658why, one step back
658 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 659–674why, one step back
659
660 /**661 * Add a required option which must have a value after parsing. This usually means662 * the option must be specified on the command line. (Otherwise the same as .option().)663 *664 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.665 *666 * @param {string} flags667 * @param {string} [description]668 * @param {Function|*} [fn] - custom option processing function or default value669 * @param {*} [defaultValue]670 * @return {Command} `this` command for chaining671 */672673 requiredOption(flags, description, fn, defaultValue) {674 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);

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

line 675why, one step back
675 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 676–679why, one step back
676
677 /**678 * Alter parsing of short flags with optional values.679 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 684–689why, one step back
684 *
685 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.686 */687 combineFlagAndOptionalValue(combine = true) {688 this._combineFlagAndOptionalValue = !!combine;689 return this;

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

line 690why, one step back
690 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 691–700why, one step back
691
692 /**693 * Allow unknown options on the command line.694 *695 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown696 * for unknown options.697 */698 allowUnknownOption(allowUnknown = true) {699 this._allowUnknownOption = !!allowUnknown;700 return this;

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

line 701why, one step back
701 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 702–711why, one step back
702
703 /**704 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.705 *706 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown707 * for excess arguments.708 */709 allowExcessArguments(allowExcess = true) {710 this._allowExcessArguments = !!allowExcess;711 return this;

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

line 712why, one step back
712 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 713–723why, one step back
713
714 /**715 * Enable positional options. Positional means global options are specified before subcommands which lets716 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.717 * The default behaviour is non-positional and global options may appear anywhere on the command line.718 *719 * @param {Boolean} [positional=true]720 */721 enablePositionalOptions(positional = true) {722 this._enablePositionalOptions = !!positional;723 return this;

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

line 724why, one step back
724 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 725–740why, one step back
725
726 /**727 * Pass through options that come after command-arguments rather than treat them as command-options,728 * so actual command-options come before command-arguments. Turning this on for a subcommand requires729 * positional options to have been enabled on the program (parent commands).730 * The default behaviour is non-positional and options may appear before or after command-arguments.731 *732 * @param {Boolean} [passThrough=true]733 * for unknown options.734 */735 passThroughOptions(passThrough = true) {736 this._passThroughOptions = !!passThrough;737 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {738 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');739 }740 return this;

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

line 741why, one step back
741 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 742–756why, one step back
742
743 /**744 * Whether to store option values as properties on command object,745 * or store separately (specify false). In both cases the option values can be accessed using .opts().746 *747 * @param {boolean} [storeAsProperties=true]748 * @return {Command} `this` command for chaining749 */750751 storeOptionsAsProperties(storeAsProperties = true) {752 this._storeOptionsAsProperties = !!storeAsProperties;753 if (this.options.length) {754 throw new Error('call .storeOptionsAsProperties() before adding options');755 }756 return this;

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

line 757why, one step back
757 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 758–770why, one step back
758
759 /**760 * Retrieve option value.761 *762 * @param {string} key763 * @return {Object} value764 */765766 getOptionValue(key) {767 if (this._storeOptionsAsProperties) {768 return this[key];769 }770 return this._optionValues[key];

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

line 771why, one step back
771 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 772–787why, one step back
772
773 /**774 * Store option value.775 *776 * @param {string} key777 * @param {Object} value778 * @return {Command} `this` command for chaining779 */780781 setOptionValue(key, value) {782 if (this._storeOptionsAsProperties) {783 this[key] = value;784 } else {785 this._optionValues[key] = value;786 }787 return this;

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

line 788why, one step back
788 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 789–790why, one step back
789
790 /**

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 791–799why, one step back
791 * Store option value and where the value came from.
792 *793 * @param {string} key794 * @param {Object} value795 * @param {string} source - expected values are default/config/env/cli796 * @return {Command} `this` command for chaining797 */798799 setOptionValueWithSource(key, value, source) {

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

lines 800–801why, one step back
800 this.setOptionValue(key, value);
801 this._optionValueSources[key] = source;

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 802why, one step back
802 return this;

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

lines 803–805why, one step back
803 }
804805 /**

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 806–814why, one step back
806 * Get source of option value.
807 * Expected values are default | config | env | cli808 *809 * @param {string} key810 * @return {string}811 */812813 getOptionValueSource(key) {814 return this._optionValueSources[key];

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

line 815why, one step back
815 }

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 816–817why, one step back
816
817 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 820–863why, one step back
820 *
821 * @api private822 */823824 _prepareUserArgs(argv, parseOptions) {825 if (argv !== undefined && !Array.isArray(argv)) {826 throw new Error('first parameter to parse must be array or undefined');827 }828 parseOptions = parseOptions || {};829830 // Default to using process.argv831 if (argv === undefined) {832 argv = process.argv;833 // @ts-ignore: unknown property834 if (process.versions && process.versions.electron) {835 parseOptions.from = 'electron';836 }837 }838 this.rawArgs = argv.slice();839840 // make it a little easier for callers by supporting various argv conventions841 let userArgs;842 switch (parseOptions.from) {843 case undefined:844 case 'node':845 this._scriptPath = argv[1];846 userArgs = argv.slice(2);847 break;848 case 'electron':849 // @ts-ignore: unknown property850 if (process.defaultApp) {851 this._scriptPath = argv[1];852 userArgs = argv.slice(2);853 } else {854 userArgs = argv.slice(1);855 }856 break;857 case 'user':858 userArgs = argv.slice(0);859 break;860 default:861 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);862 }863

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

lines 864–866why, one step back
864 // Find default name for program from arguments.
865 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);866 this._name = this._name || 'program';

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 867–876why, one step back
867
868 return userArgs;869 }870871 /**872 * Parse `argv`, setting options and invoking commands when defined.873 *874 * The default expectation is that the arguments are from node and have the application as argv[0]875 * and the script being run in argv[1], with user parameters after that.876 *

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

lines 877–880why, one step back
877 * @example
878 * program.parse(process.argv);879 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions880 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 881–892why, one step back
881 *
882 * @param {string[]} [argv] - optional, defaults to process.argv883 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron884 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'885 * @return {Command} `this` command for chaining886 */887888 parse(argv, parseOptions) {889 const userArgs = this._prepareUserArgs(argv, parseOptions);890 this._parseCommand([], userArgs);891892 return this;

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

line 893why, one step back
893 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 894–902why, one step back
894
895 /**896 * Parse `argv`, setting options and invoking commands when defined.897 *898 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.899 *900 * The default expectation is that the arguments are from node and have the application as argv[0]901 * and the script being run in argv[1], with user parameters after that.902 *

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

lines 903–906why, one step back
903 * @example
904 * await program.parseAsync(process.argv);905 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions906 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 907–918why, one step back
907 *
908 * @param {string[]} [argv]909 * @param {Object} [parseOptions]910 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'911 * @return {Promise}912 */913914 async parseAsync(argv, parseOptions) {915 const userArgs = this._prepareUserArgs(argv, parseOptions);916 await this._parseCommand([], userArgs);917918 return this;

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

line 919why, one step back
919 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 920–931why, one step back
920
921 /**922 * Execute a sub-command executable.923 *924 * @api private925 */926927 _executeSubCommand(subcommand, args) {928 args = args.slice();929 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.930 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];931

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

lines 932–935why, one step back
932 function findFile(baseDir, baseName) {
933 // Look for specified file934 const localBin = path.resolve(baseDir, baseName);935 if (fs.existsSync(localBin)) return localBin;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 936why, one step back
936

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 939why, one step back
939

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

lines 940–944why, one step back
940 // Try all the extensions.
941 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));942 if (foundExt) return `${localBin}${foundExt}`;943944 return undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 945–946why, one step back
945 }
946

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

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

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

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

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

lines 950–961why, one step back
950
951 // executableFile and executableDir might be full path, or just a name952 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;953 let executableDir = this._executableDir || '';954 if (this._scriptPath) {955 let resolvedScriptPath; // resolve possible symlink for installed npm binary956 try {957 resolvedScriptPath = fs.realpathSync(this._scriptPath);958 } catch (err) {959 resolvedScriptPath = this._scriptPath;960 }961 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 962–963why, one step back
962 }
963

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

lines 964–972why, one step back
964 // Look for a local file in preference to a command in PATH.
965 if (executableDir) {966 let localFile = findFile(executableDir, executableFile);967968 // Legacy search using prefix of script name instead of command name969 if (!localFile && !subcommand._executableFile && this._scriptPath) {970 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));971 if (legacyName !== this._name) {972 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 973why, one step back
973 }

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

lines 974–975why, one step back
974 }
975 executableFile = localFile || executableFile;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 976–977why, one step back
976 }
977

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 980–982why, one step back
980 let proc;
981 if (process.platform !== 'win32') {982 if (launchWithNode) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 990–991why, one step back
990 }
991 } else {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 993–997why, one step back
993 // add executable arguments to spawn
994 args = incrementNodeInspectorPort(process.execArgv).concat(args);995 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });996 }997

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

lines 998–1006why, one step back
998 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
999 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1000 signals.forEach((signal) => {1001 // @ts-ignore1002 process.on(signal, () => {1003 if (proc.killed === false && proc.exitCode === null) {1004 proc.kill(signal);1005 }1006 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1007why, one step back
1007 });

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

line 1008why, one step back
1008 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1009–1022why, one step back
1009
1010 // By default terminate process when spawned process terminates.1011 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1012 const exitCallback = this._exitCallback;1013 if (!exitCallback) {1014 proc.on('close', process.exit.bind(process));1015 } else {1016 proc.on('close', () => {1017 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1018 });1019 }1020 proc.on('error', (err) => {1021 // @ts-ignore1022 if (err.code === 'ENOENT') {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1030–1032why, one step back
1030 throw new Error(executableMissing);
1031 // @ts-ignore1032 } else if (err.code === 'EACCES') {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1034–1045why, one step back
1034 }
1035 if (!exitCallback) {1036 process.exit(1);1037 } else {1038 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1039 wrappedError.nestedError = err;1040 exitCallback(wrappedError);1041 }1042 });10431044 // Store the reference to the child process1045 this.runningCommand = proc;

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

line 1046why, one step back
1046 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1047–1060why, one step back
1047
1048 /**1049 * @api private1050 */10511052 _dispatchSubcommand(commandName, operands, unknown) {1053 const subCommand = this._findCommand(commandName);1054 if (!subCommand) this.help({ error: true });10551056 if (subCommand._executableHandler) {1057 this._executeSubCommand(subCommand, operands.concat(unknown));1058 } else {1059 return subCommand._parseCommand(operands, unknown);1060 }

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

line 1061why, one step back
1061 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1062–1063why, one step back
1062
1063 /**

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

line 1064why, one step back
1064 * Check this.args against expected this._args.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1065–1068why, one step back
1065 *
1066 * @api private1067 */1068

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

lines 1069–1082why, one step back
1069 _checkNumberOfArguments() {
1070 // too few1071 this._args.forEach((arg, i) => {1072 if (arg.required && this.args[i] == null) {1073 this.missingArgument(arg.name());1074 }1075 });1076 // too many1077 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1078 return;1079 }1080 if (this.args.length > this._args.length) {1081 this._excessArguments(this.args);1082 }

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

line 1083why, one step back
1083 }

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

lines 1084–1091why, one step back
1084
1085 /**1086 * Process this.args using this._args and save as this.processedArgs!1087 *1088 * @api private1089 */10901091 _processArguments() {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1092–1100why, one step back
1092 const myParseArg = (argument, value, previous) => {
1093 // Extra processing for nice error message on parsing failure.1094 let parsedValue = value;1095 if (value !== null && argument.parseArg) {1096 try {1097 parsedValue = argument.parseArg(value, previous);1098 } catch (err) {1099 if (err.code === 'commander.invalidArgument') {1100 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;

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

line 1101why, one step back
1101 this.error(message, { exitCode: err.exitCode, code: err.code });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1102–1108why, one step back
1102 }
1103 throw err;1104 }1105 }1106 return parsedValue;1107 };1108

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

lines 1109–1111why, one step back
1109 this._checkNumberOfArguments();
11101111 const processedArgs = [];

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1112–1131why, one step back
1112 this._args.forEach((declaredArg, index) => {
1113 let value = declaredArg.defaultValue;1114 if (declaredArg.variadic) {1115 // Collect together remaining arguments for passing together as an array.1116 if (index < this.args.length) {1117 value = this.args.slice(index);1118 if (declaredArg.parseArg) {1119 value = value.reduce((processed, v) => {1120 return myParseArg(declaredArg, v, processed);1121 }, declaredArg.defaultValue);1122 }1123 } else if (value === undefined) {1124 value = [];1125 }1126 } else if (index < this.args.length) {1127 value = this.args[index];1128 if (declaredArg.parseArg) {1129 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1130 }1131 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1133why, one step back
1133 });

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1135–1142why, one step back
1135 }
11361137 /**1138 * Once we have a promise we chain, but call synchronously until then.1139 *1140 * @param {Promise|undefined} promise1141 * @param {Function} fn1142 * @return {Promise|undefined}

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 1143why, one step back
1143 * @api private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1144–1195why, one step back
1144 */
11451146 _chainOrCall(promise, fn) {1147 // thenable1148 if (promise && promise.then && typeof promise.then === 'function') {1149 // already have a promise, chain callback1150 return promise.then(() => fn());1151 }1152 // callback might return a promise1153 return fn();1154 }11551156 /**1157 *1158 * @param {Promise|undefined} promise1159 * @param {string} event1160 * @return {Promise|undefined}1161 * @api private1162 */11631164 _chainOrCallHooks(promise, event) {1165 let result = promise;1166 const hooks = [];1167 getCommandAndParents(this)1168 .reverse()1169 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1170 .forEach(hookedCommand => {1171 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1172 hooks.push({ hookedCommand, callback });1173 });1174 });1175 if (event === 'postAction') {1176 hooks.reverse();1177 }11781179 hooks.forEach((hookDetail) => {1180 result = this._chainOrCall(result, () => {1181 return hookDetail.callback(hookDetail.hookedCommand, this);1182 });1183 });1184 return result;1185 }11861187 /**1188 * Process arguments in context of this command.1189 * Returns action result, in case it is a promise.1190 *1191 * @api private1192 */11931194 _parseCommand(operands, unknown) {1195 const parsed = this.parseOptions(unknown);

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1197–1220why, one step back
1197 operands = operands.concat(parsed.operands);
1198 unknown = parsed.unknown;1199 this.args = operands.concat(unknown);12001201 if (operands && this._findCommand(operands[0])) {1202 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1203 }1204 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1205 if (operands.length === 1) {1206 this.help();1207 }1208 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1209 }1210 if (this._defaultCommandName) {1211 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1212 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1213 }1214 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1215 // probably missing subcommand and no handler, user needs help (and exit)1216 this.help({ error: true });1217 }12181219 outputHelpIfRequested(this, parsed.unknown);1220 this._checkForMissingMandatoryOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1222–1232why, one step back
1222
1223 // We do not always call this check to avoid masking a "better" error, like unknown command.1224 const checkForUnknownOptions = () => {1225 if (parsed.unknown.length > 0) {1226 this.unknownOption(parsed.unknown[0]);1227 }1228 };12291230 const commandEvent = `command:${this.name()}`;1231 if (this._actionHandler) {1232 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1234–1236why, one step back
1234
1235 let actionResult;1236 actionResult = this._chainOrCallHooks(actionResult, 'preAction');

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

line 1237why, one step back
1237 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));

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

lines 1238–1242why, one step back
1238 if (this.parent) {
1239 actionResult = this._chainOrCall(actionResult, () => {1240 this.parent.emit(commandEvent, operands, unknown); // legacy1241 });1242 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1243–1247why, one step back
1243 actionResult = this._chainOrCallHooks(actionResult, 'postAction');
1244 return actionResult;1245 }1246 if (this.parent && this.parent.listenerCount(commandEvent)) {1247 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1249–1260why, one step back
1249 this.parent.emit(commandEvent, operands, unknown); // legacy
1250 } else if (operands.length) {1251 if (this._findCommand('*')) { // legacy default command1252 return this._dispatchSubcommand('*', operands, unknown);1253 }1254 if (this.listenerCount('command:*')) {1255 // skip option check, emit event for possible misspelling suggestion1256 this.emit('command:*', operands, unknown);1257 } else if (this.commands.length) {1258 this.unknownCommand();1259 } else {1260 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1272why, one step back
1272 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1273–1281why, one step back
1273
1274 /**1275 * Find matching command.1276 *1277 * @api private1278 */1279 _findCommand(name) {1280 if (!name) return undefined;1281 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));

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

line 1282why, one step back
1282 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1283–1293why, one step back
1283
1284 /**1285 * Return an option matching `arg` if any.1286 *1287 * @param {string} arg1288 * @return {Option}1289 * @api private1290 */12911292 _findOption(arg) {1293 return this.options.find(option => option.is(arg));

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

line 1294why, one step back
1294 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1295–1297why, one step back
1295
1296 /**1297 * Display an error message if a mandatory option does not have a value.

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1299–1311why, one step back
1299 *
1300 * @api private1301 */13021303 _checkForMissingMandatoryOptions() {1304 // Walk up hierarchy so can call in subcommand after checking for displaying help.1305 for (let cmd = this; cmd; cmd = cmd.parent) {1306 cmd.options.forEach((anOption) => {1307 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1308 cmd.missingMandatoryOptionValue(anOption);1309 }1310 });1311 }

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

line 1312why, one step back
1312 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1313–1314why, one step back
1313
1314 /**

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

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

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

lines 1316–1318why, one step back
1316 *
1317 * @api private1318 */

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

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

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

lines 1320–1341why, one step back
1320 const definedNonDefaultOptions = this.options.filter(
1321 (option) => {1322 const optionKey = option.attributeName();1323 if (this.getOptionValue(optionKey) === undefined) {1324 return false;1325 }1326 return this.getOptionValueSource(optionKey) !== 'default';1327 }1328 );13291330 const optionsWithConflicting = definedNonDefaultOptions.filter(1331 (option) => option.conflictsWith.length > 01332 );13331334 optionsWithConflicting.forEach((option) => {1335 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1336 option.conflictsWith.includes(defined.attributeName())1337 );1338 if (conflictingAndDefined) {1339 this._conflictingOption(option, conflictingAndDefined);1340 }1341 });

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

lines 1342–1354why, one step back
1342 }
13431344 /**1345 * Display an error message if conflicting options are used together.1346 * Called after checking for help flags in leaf subcommand.1347 *1348 * @api private1349 */1350 _checkForConflictingOptions() {1351 // Walk up hierarchy so can call in subcommand after checking for displaying help.1352 for (let cmd = this; cmd; cmd = cmd.parent) {1353 cmd._checkForConflictingLocalOptions();1354 }

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

lines 1355–1357why, one step back
1355 }
13561357 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1358–1362why, one step back
1358 * Parse options from `argv` removing known options,
1359 * and return argv split into operands and unknown arguments.1360 *1361 * Examples:1362 *

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

lines 1363–1367why, one step back
1363 * argv => operands, unknown
1364 * --known kkk op => [op], []1365 * op --known kkk => [op], []1366 * sub --unknown uuu op => [sub], [--unknown uuu op]1367 * sub -- --unknown uuu op => [sub --unknown uuu op], []

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1368–1486why, one step back
1368 *
1369 * @param {String[]} argv1370 * @return {{operands: String[], unknown: String[]}}1371 */13721373 parseOptions(argv) {1374 const operands = []; // operands, not options or values1375 const unknown = []; // first unknown option and remaining unknown args1376 let dest = operands;1377 const args = argv.slice();13781379 function maybeOption(arg) {1380 return arg.length > 1 && arg[0] === '-';1381 }13821383 // parse options1384 let activeVariadicOption = null;1385 while (args.length) {1386 const arg = args.shift();13871388 // literal1389 if (arg === '--') {1390 if (dest === unknown) dest.push(arg);1391 dest.push(...args);1392 break;1393 }13941395 if (activeVariadicOption && !maybeOption(arg)) {1396 this.emit(`option:${activeVariadicOption.name()}`, arg);1397 continue;1398 }1399 activeVariadicOption = null;14001401 if (maybeOption(arg)) {1402 const option = this._findOption(arg);1403 // recognised option, call listener to assign value with possible custom processing1404 if (option) {1405 if (option.required) {1406 const value = args.shift();1407 if (value === undefined) this.optionMissingArgument(option);1408 this.emit(`option:${option.name()}`, value);1409 } else if (option.optional) {1410 let value = null;1411 // historical behaviour is optional value is following arg unless an option1412 if (args.length > 0 && !maybeOption(args[0])) {1413 value = args.shift();1414 }1415 this.emit(`option:${option.name()}`, value);1416 } else { // boolean flag1417 this.emit(`option:${option.name()}`);1418 }1419 activeVariadicOption = option.variadic ? option : null;1420 continue;1421 }1422 }14231424 // Look for combo options following single dash, eat first one if known.1425 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1426 const option = this._findOption(`-${arg[1]}`);1427 if (option) {1428 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1429 // option with value following in same argument1430 this.emit(`option:${option.name()}`, arg.slice(2));1431 } else {1432 // boolean option, emit and put back remainder of arg for further processing1433 this.emit(`option:${option.name()}`);1434 args.unshift(`-${arg.slice(2)}`);1435 }1436 continue;1437 }1438 }14391440 // Look for known long flag with value, like --foo=bar1441 if (/^--[^=]+=/.test(arg)) {1442 const index = arg.indexOf('=');1443 const option = this._findOption(arg.slice(0, index));1444 if (option && (option.required || option.optional)) {1445 this.emit(`option:${option.name()}`, arg.slice(index + 1));1446 continue;1447 }1448 }14491450 // Not a recognised option by this command.1451 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14521453 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1454 if (maybeOption(arg)) {1455 dest = unknown;1456 }14571458 // If using positionalOptions, stop processing our options at subcommand.1459 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1460 if (this._findCommand(arg)) {1461 operands.push(arg);1462 if (args.length > 0) unknown.push(...args);1463 break;1464 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1465 operands.push(arg);1466 if (args.length > 0) operands.push(...args);1467 break;1468 } else if (this._defaultCommandName) {1469 unknown.push(arg);1470 if (args.length > 0) unknown.push(...args);1471 break;1472 }1473 }14741475 // If using passThroughOptions, stop processing options at first command-argument.1476 if (this._passThroughOptions) {1477 dest.push(arg);1478 if (args.length > 0) dest.push(...args);1479 break;1480 }14811482 // add arg1483 dest.push(arg);1484 }14851486 return { operands, unknown };

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

line 1487why, one step back
1487 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1488–1489why, one step back
1488
1489 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1491–1507why, one step back
1491 *
1492 * @return {Object}1493 */1494 opts() {1495 if (this._storeOptionsAsProperties) {1496 // Preserve original behaviour so backwards compatible when still using properties1497 const result = {};1498 const len = this.options.length;14991500 for (let i = 0; i < len; i++) {1501 const key = this.options[i].attributeName();1502 result[key] = key === this._versionOptionName ? this._version : this[key];1503 }1504 return result;1505 }15061507 return this._optionValues;

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

line 1508why, one step back
1508 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1509–1510why, one step back
1509
1510 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1512why, one step back
1512 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1514why, one step back
1514 */

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

lines 1515–1532why, one step back
1515 optsWithGlobals() {
1516 // globals overwrite locals1517 return getCommandAndParents(this).reduce(1518 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1519 {}1520 );1521 }15221523 /**1524 * Display error message and exit (or call exitOverride).1525 *1526 * @param {string} message1527 * @param {Object} [errorOptions]1528 * @param {string} [errorOptions.code] - an id string representing the error1529 * @param {number} [errorOptions.exitCode] - used with process.exit1530 */1531 error(message, errorOptions) {1532 // output handling

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1533why, one step back
1533 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 1534–1539why, one step back
1534 if (typeof this._showHelpAfterError === 'string') {
1535 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1536 } else if (this._showHelpAfterError) {1537 this._outputConfiguration.writeErr('\n');1538 this.outputHelp({ error: true });1539 }

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

lines 1540–1544why, one step back
1540
1541 // exit handling1542 const config = errorOptions || {};1543 const exitCode = config.exitCode || 1;1544 const code = config.code || 'commander.error';

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1546–1557why, one step back
1546 }
15471548 /**1549 * Apply any option related environment variables, if option does1550 * not have a value from cli or client code.1551 *1552 * @api private1553 */1554 _parseOptionsEnv() {1555 this.options.forEach((option) => {1556 if (option.envVar && option.envVar in process.env) {1557 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 1558–1559why, one step back
1558 // Priority check. Do not overwrite cli or options from unknown source (client-code).
1559 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {

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

lines 1560–1569why, one step back
1560 if (option.required || option.optional) { // option can take a value
1561 // keep very simple, optional always takes value1562 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1563 } else { // boolean1564 // keep very simple, only care that envVar defined and not the value1565 this.emit(`optionEnv:${option.name()}`);1566 }1567 }1568 }1569 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1570–1580why, one step back
1570 }
15711572 /**1573 * Argument `name` is missing.1574 *1575 * @param {string} name1576 * @api private1577 */15781579 missingArgument(name) {1580 const message = `error: missing required argument '${name}'`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1583–1592why, one step back
1583
1584 /**1585 * `Option` is missing an argument.1586 *1587 * @param {Option} option1588 * @api private1589 */15901591 optionMissingArgument(option) {1592 const message = `error: option '${option.flags}' argument missing`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1595–1604why, one step back
1595
1596 /**1597 * `Option` does not have a value, and is a mandatory option.1598 *1599 * @param {Option} option1600 * @api private1601 */16021603 missingMandatoryOptionValue(option) {1604 const message = `error: required option '${option.flags}' not specified`;

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

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

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

lines 1606–1643why, one step back
1606 }
16071608 /**1609 * `Option` conflicts with another option.1610 *1611 * @param {Option} option1612 * @param {Option} conflictingOption1613 * @api private1614 */1615 _conflictingOption(option, conflictingOption) {1616 // The calling code does not know whether a negated option is the source of the1617 // value, so do some work to take an educated guess.1618 const findBestOptionFromValue = (option) => {1619 const optionKey = option.attributeName();1620 const optionValue = this.getOptionValue(optionKey);1621 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1622 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1623 if (negativeOption && (1624 (negativeOption.presetArg === undefined && optionValue === false) ||1625 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1626 )) {1627 return negativeOption;1628 }1629 return positiveOption || option;1630 };16311632 const getErrorMessage = (option) => {1633 const bestOption = findBestOptionFromValue(option);1634 const optionKey = bestOption.attributeName();1635 const source = this.getOptionValueSource(optionKey);1636 if (source === 'env') {1637 return `environment variable '${bestOption.envVar}'`;1638 }1639 return `option '${bestOption.flags}'`;1640 };16411642 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1643 this.error(message, { code: 'commander.conflictingOption' });

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

line 1644why, one step back
1644 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1645–1654why, one step back
1645
1646 /**1647 * Unknown option `flag`.1648 *1649 * @param {string} flag1650 * @api private1651 */16521653 unknownOption(flag) {1654 if (this._allowUnknownOption) return;

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

lines 1655–1671why, one step back
1655 let suggestion = '';
16561657 if (flag.startsWith('--') && this._showSuggestionAfterError) {1658 // Looping to pick up the global options too1659 let candidateFlags = [];1660 let command = this;1661 do {1662 const moreFlags = command.createHelp().visibleOptions(command)1663 .filter(option => option.long)1664 .map(option => option.long);1665 candidateFlags = candidateFlags.concat(moreFlags);1666 command = command.parent;1667 } while (command && !command._enablePositionalOptions);1668 suggestion = suggestSimilar(flag, candidateFlags);1669 }16701671 const message = `error: unknown option '${flag}'${suggestion}`;

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

lines 1672–1673why, one step back
1672 this.error(message, { code: 'commander.unknownOption' });
1673 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1674–1688why, one step back
1674
1675 /**1676 * Excess arguments, more than expected.1677 *1678 * @param {string[]} receivedArgs1679 * @api private1680 */16811682 _excessArguments(receivedArgs) {1683 if (this._allowExcessArguments) return;16841685 const expected = this._args.length;1686 const s = (expected === 1) ? '' : 's';1687 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1688 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;

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

lines 1689–1690why, one step back
1689 this.error(message, { code: 'commander.excessArguments' });
1690 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1691–1698why, one step back
1691
1692 /**1693 * Unknown command.1694 *1695 * @api private1696 */16971698 unknownCommand() {

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

lines 1699–1712why, one step back
1699 const unknownName = this.args[0];
1700 let suggestion = '';17011702 if (this._showSuggestionAfterError) {1703 const candidateNames = [];1704 this.createHelp().visibleCommands(this).forEach((command) => {1705 candidateNames.push(command.name());1706 // just visible alias1707 if (command.alias()) candidateNames.push(command.alias());1708 });1709 suggestion = suggestSimilar(unknownName, candidateNames);1710 }17111712 const message = `error: unknown command '${unknownName}'${suggestion}`;

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

lines 1713–1714why, one step back
1713 this.error(message, { code: 'commander.unknownCommand' });
1714 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1715–1742why, one step back
1715
1716 /**1717 * Set the program version to `str`.1718 *1719 * This method auto-registers the "-V, --version" flag1720 * which will print the version number when passed.1721 *1722 * You can optionally supply the flags and description to override the defaults.1723 *1724 * @param {string} str1725 * @param {string} [flags]1726 * @param {string} [description]1727 * @return {this | string} `this` command for chaining, or version string if no arguments1728 */17291730 version(str, flags, description) {1731 if (str === undefined) return this._version;1732 this._version = str;1733 flags = flags || '-V, --version';1734 description = description || 'output the version number';1735 const versionOption = this.createOption(flags, description);1736 this._versionOptionName = versionOption.attributeName();1737 this.options.push(versionOption);1738 this.on('option:' + versionOption.name(), () => {1739 this._outputConfiguration.writeOut(`${str}\n`);1740 this._exit(0, 'commander.version', str);1741 });1742 return this;

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

line 1743why, one step back
1743 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1744–1758why, one step back
1744
1745 /**1746 * Set the description to `str`.1747 *1748 * @param {string} [str]1749 * @param {Object} [argsDescription]1750 * @return {string|Command}1751 */1752 description(str, argsDescription) {1753 if (str === undefined && argsDescription === undefined) return this._description;1754 this._description = str;1755 if (argsDescription) {1756 this._argsDescription = argsDescription;1757 }1758 return this;

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

line 1759why, one step back
1759 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1760–1772why, one step back
1760
1761 /**1762 * Set an alias for the command.1763 *1764 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1765 *1766 * @param {string} [alias]1767 * @return {string|Command}1768 */17691770 alias(alias) {1771 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1772

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

line 1773why, one step back
1773 /** @type {Command} */

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1774–1783why, one step back
1774 let command = this;
1775 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1776 // assume adding alias for last added executable subcommand, rather than this1777 command = this.commands[this.commands.length - 1];1778 }17791780 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');17811782 command._aliases.push(alias);1783 return this;

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

line 1784why, one step back
1784 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1785–1800why, one step back
1785
1786 /**1787 * Set aliases for the command.1788 *1789 * Only the first alias is shown in the auto-generated help.1790 *1791 * @param {string[]} [aliases]1792 * @return {string[]|Command}1793 */17941795 aliases(aliases) {1796 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1797 if (aliases === undefined) return this._aliases;17981799 aliases.forEach((alias) => this.alias(alias));1800 return this;

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

line 1801why, one step back
1801 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1802–1825why, one step back
1802
1803 /**1804 * Set / get the command usage `str`.1805 *1806 * @param {string} [str]1807 * @return {String|Command}1808 */18091810 usage(str) {1811 if (str === undefined) {1812 if (this._usage) return this._usage;18131814 const args = this._args.map((arg) => {1815 return humanReadableArgName(arg);1816 });1817 return [].concat(1818 (this.options.length || this._hasHelpOption ? '[options]' : []),1819 (this.commands.length ? '[command]' : []),1820 (this._args.length ? args : [])1821 ).join(' ');1822 }18231824 this._usage = str;1825 return this;

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

line 1826why, one step back
1826 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1827–1828why, one step back
1827
1828 /**

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

line 1829why, one step back
1829 * Get or set the name of the command.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1830–1838why, one step back
1830 *
1831 * @param {string} [str]1832 * @return {string|Command}1833 */18341835 name(str) {1836 if (str === undefined) return this._name;1837 this._name = str;1838 return this;

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

line 1839why, one step back
1839 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1840–1841why, one step back
1840
1841 /**

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

lines 1842–1878why, one step back
1842 * Set the name of the command from script filename, such as process.argv[1],
1843 * or require.main.filename, or __filename.1844 *1845 * (Used internally and public although not documented in README.)1846 *1847 * @example1848 * program.nameFromFilename(require.main.filename);1849 *1850 * @param {string} filename1851 * @return {Command}1852 */18531854 nameFromFilename(filename) {1855 this._name = path.basename(filename, path.extname(filename));18561857 return this;1858 }18591860 /**1861 * Get or set the directory for searching for executable subcommands of this command.1862 *1863 * @example1864 * program.executableDir(__dirname);1865 * // or1866 * program.executableDir('subcommands');1867 *1868 * @param {string} [path]1869 * @return {string|Command}1870 */18711872 executableDir(path) {1873 if (path === undefined) return this._executableDir;1874 this._executableDir = path;1875 return this;1876 }18771878 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1879–1890why, one step back
1879 * Return program help documentation.
1880 *1881 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1882 * @return {string}1883 */18841885 helpInformation(contextOptions) {1886 const helper = this.createHelp();1887 if (helper.helpWidth === undefined) {1888 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1889 }1890 return helper.formatHelp(this, helper);

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

line 1891why, one step back
1891 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1892–1926why, one step back
1892
1893 /**1894 * @api private1895 */18961897 _getHelpContext(contextOptions) {1898 contextOptions = contextOptions || {};1899 const context = { error: !!contextOptions.error };1900 let write;1901 if (context.error) {1902 write = (arg) => this._outputConfiguration.writeErr(arg);1903 } else {1904 write = (arg) => this._outputConfiguration.writeOut(arg);1905 }1906 context.write = contextOptions.write || write;1907 context.command = this;1908 return context;1909 }19101911 /**1912 * Output help information for this command.1913 *1914 * Outputs built-in help, and custom text added using `.addHelpText()`.1915 *1916 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1917 */19181919 outputHelp(contextOptions) {1920 let deprecatedCallback;1921 if (typeof contextOptions === 'function') {1922 deprecatedCallback = contextOptions;1923 contextOptions = undefined;1924 }1925 const context = this._getHelpContext(contextOptions);1926

Use getCommandAndParents for array of parents (#1566)John Geebefore adoption4be69f1

line 1927why, one step back
1927 getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1928–1940why, one step back
1928 this.emit('beforeHelp', context);
19291930 let helpInformation = this.helpInformation(context);1931 if (deprecatedCallback) {1932 helpInformation = deprecatedCallback(helpInformation);1933 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1934 throw new Error('outputHelp callback must return a string or a Buffer');1935 }1936 }1937 context.write(helpInformation);19381939 this.emit(this._helpLongFlag); // deprecated1940 this.emit('afterHelp', context);

Use getCommandAndParents for array of parents (#1566)John Geebefore adoption4be69f1

line 1941why, one step back
1941 getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));

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

line 1942why, one step back
1942 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1943–1966why, one step back
1943
1944 /**1945 * You can pass in flags and a description to override the help1946 * flags and help description for your command. Pass in false to1947 * disable the built-in help option.1948 *1949 * @param {string | boolean} [flags]1950 * @param {string} [description]1951 * @return {Command} `this` command for chaining1952 */19531954 helpOption(flags, description) {1955 if (typeof flags === 'boolean') {1956 this._hasHelpOption = flags;1957 return this;1958 }1959 this._helpFlags = flags || this._helpFlags;1960 this._helpDescription = description || this._helpDescription;19611962 const helpFlags = splitOptionFlags(this._helpFlags);1963 this._helpShortFlag = helpFlags.shortFlag;1964 this._helpLongFlag = helpFlags.longFlag;19651966 return this;

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

line 1967why, one step back
1967 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1968–1984why, one step back
1968
1969 /**1970 * Output help information and exit.1971 *1972 * Outputs built-in help, and custom text added using `.addHelpText()`.1973 *1974 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1975 */19761977 help(contextOptions) {1978 this.outputHelp(contextOptions);1979 let exitCode = process.exitCode || 0;1980 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1981 exitCode = 1;1982 }1983 // message: do not have all displayed text available so only passing placeholder.1984 this._exit(exitCode, 'commander.help', '(outputHelp)');

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

line 1985why, one step back
1985 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1986–2017why, one step back
1986
1987 /**1988 * Add additional text to be displayed with the built-in help.1989 *1990 * Position is 'before' or 'after' to affect just this command,1991 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1992 *1993 * @param {string} position - before or after built-in help1994 * @param {string | Function} text - string to add, or a function returning a string1995 * @return {Command} `this` command for chaining1996 */1997 addHelpText(position, text) {1998 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1999 if (!allowedValues.includes(position)) {2000 throw new Error(`Unexpected value for position to addHelpText.

The first 2,000 of 2,098 lines.