Skip to content
Myr

command.js

This file

Path

lib/command.js

2,084 lines · 65.6 KiB · JavaScript

Last changed by

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

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–960why, 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();949950 // executableFile and executableDir might be full path, or just a name951 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;952 let executableDir = this._executableDir || '';953 if (this._scriptPath) {954 let resolvedScriptPath; // resolve possible symlink for installed npm binary955 try {956 resolvedScriptPath = fs.realpathSync(this._scriptPath);957 } catch (err) {958 resolvedScriptPath = this._scriptPath;959 }960 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 972why, one step back
972 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1006why, one step back
1006 });

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

line 1007why, one step back
1007 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1045why, one step back
1045 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1046–1059why, one step back
1046
1047 /**1048 * @api private1049 */10501051 _dispatchSubcommand(commandName, operands, unknown) {1052 const subCommand = this._findCommand(commandName);1053 if (!subCommand) this.help({ error: true });10541055 if (subCommand._executableHandler) {1056 this._executeSubCommand(subCommand, operands.concat(unknown));1057 } else {1058 return subCommand._parseCommand(operands, unknown);1059 }

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

line 1060why, one step back
1060 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1064–1067why, one step back
1064 *
1065 * @api private1066 */1067

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

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

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

line 1082why, one step back
1082 }

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

lines 1083–1090why, one step back
1083
1084 /**1085 * Process this.args using this._args and save as this.processedArgs!1086 *1087 * @api private1088 */10891090 _processArguments() {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1091–1099why, one step back
1091 const myParseArg = (argument, value, previous) => {
1092 // Extra processing for nice error message on parsing failure.1093 let parsedValue = value;1094 if (value !== null && argument.parseArg) {1095 try {1096 parsedValue = argument.parseArg(value, previous);1097 } catch (err) {1098 if (err.code === 'commander.invalidArgument') {1099 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 1100why, one step back
1100 this.error(message, { exitCode: err.exitCode, code: err.code });

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1108–1110why, one step back
1108 this._checkNumberOfArguments();
11091110 const processedArgs = [];

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1132why, one step back
1132 });

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1134–1141why, one step back
1134 }
11351136 /**1137 * Once we have a promise we chain, but call synchronously until then.1138 *1139 * @param {Promise|undefined} promise1140 * @param {Function} fn1141 * @return {Promise|undefined}

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1143–1194why, one step back
1143 */
11441145 _chainOrCall(promise, fn) {1146 // thenable1147 if (promise && promise.then && typeof promise.then === 'function') {1148 // already have a promise, chain callback1149 return promise.then(() => fn());1150 }1151 // callback might return a promise1152 return fn();1153 }11541155 /**1156 *1157 * @param {Promise|undefined} promise1158 * @param {string} event1159 * @return {Promise|undefined}1160 * @api private1161 */11621163 _chainOrCallHooks(promise, event) {1164 let result = promise;1165 const hooks = [];1166 getCommandAndParents(this)1167 .reverse()1168 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1169 .forEach(hookedCommand => {1170 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1171 hooks.push({ hookedCommand, callback });1172 });1173 });1174 if (event === 'postAction') {1175 hooks.reverse();1176 }11771178 hooks.forEach((hookDetail) => {1179 result = this._chainOrCall(result, () => {1180 return hookDetail.callback(hookDetail.hookedCommand, this);1181 });1182 });1183 return result;1184 }11851186 /**1187 * Process arguments in context of this command.1188 * Returns action result, in case it is a promise.1189 *1190 * @api private1191 */11921193 _parseCommand(operands, unknown) {1194 const parsed = this.parseOptions(unknown);

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1271why, one step back
1271 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1281why, one step back
1281 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1282–1292why, one step back
1282
1283 /**1284 * Return an option matching `arg` if any.1285 *1286 * @param {string} arg1287 * @return {Option}1288 * @api private1289 */12901291 _findOption(arg) {1292 return this.options.find(option => option.is(arg));

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

line 1293why, one step back
1293 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1294–1310why, one step back
1294
1295 /**1296 * Display an error message if a mandatory option does not have a value.1297 * Lazy calling after checking for help flags from leaf subcommand.1298 *1299 * @api private1300 */13011302 _checkForMissingMandatoryOptions() {1303 // Walk up hierarchy so can call in subcommand after checking for displaying help.1304 for (let cmd = this; cmd; cmd = cmd.parent) {1305 cmd.options.forEach((anOption) => {1306 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1307 cmd.missingMandatoryOptionValue(anOption);1308 }1309 });1310 }

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

line 1311why, one step back
1311 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1314–1343why, one step back
1314 * Display an error message if conflicting options are used together.
1315 *1316 * @api private1317 */1318 _checkForConflictingOptions() {1319 const definedNonDefaultOptions = this.options.filter(1320 (option) => {1321 const optionKey = option.attributeName();1322 if (this.getOptionValue(optionKey) === undefined) {1323 return false;1324 }1325 return this.getOptionValueSource(optionKey) !== 'default';1326 }1327 );13281329 const optionsWithConflicting = definedNonDefaultOptions.filter(1330 (option) => option.conflictsWith.length > 01331 );13321333 optionsWithConflicting.forEach((option) => {1334 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1335 option.conflictsWith.includes(defined.attributeName())1336 );1337 if (conflictingAndDefined) {1338 this._conflictingOption(option, conflictingAndDefined);1339 }1340 });1341 }13421343 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1344–1348why, one step back
1344 * Parse options from `argv` removing known options,
1345 * and return argv split into operands and unknown arguments.1346 *1347 * Examples:1348 *

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

lines 1349–1353why, one step back
1349 * argv => operands, unknown
1350 * --known kkk op => [op], []1351 * op --known kkk => [op], []1352 * sub --unknown uuu op => [sub], [--unknown uuu op]1353 * sub -- --unknown uuu op => [sub --unknown uuu op], []

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1354–1472why, one step back
1354 *
1355 * @param {String[]} argv1356 * @return {{operands: String[], unknown: String[]}}1357 */13581359 parseOptions(argv) {1360 const operands = []; // operands, not options or values1361 const unknown = []; // first unknown option and remaining unknown args1362 let dest = operands;1363 const args = argv.slice();13641365 function maybeOption(arg) {1366 return arg.length > 1 && arg[0] === '-';1367 }13681369 // parse options1370 let activeVariadicOption = null;1371 while (args.length) {1372 const arg = args.shift();13731374 // literal1375 if (arg === '--') {1376 if (dest === unknown) dest.push(arg);1377 dest.push(...args);1378 break;1379 }13801381 if (activeVariadicOption && !maybeOption(arg)) {1382 this.emit(`option:${activeVariadicOption.name()}`, arg);1383 continue;1384 }1385 activeVariadicOption = null;13861387 if (maybeOption(arg)) {1388 const option = this._findOption(arg);1389 // recognised option, call listener to assign value with possible custom processing1390 if (option) {1391 if (option.required) {1392 const value = args.shift();1393 if (value === undefined) this.optionMissingArgument(option);1394 this.emit(`option:${option.name()}`, value);1395 } else if (option.optional) {1396 let value = null;1397 // historical behaviour is optional value is following arg unless an option1398 if (args.length > 0 && !maybeOption(args[0])) {1399 value = args.shift();1400 }1401 this.emit(`option:${option.name()}`, value);1402 } else { // boolean flag1403 this.emit(`option:${option.name()}`);1404 }1405 activeVariadicOption = option.variadic ? option : null;1406 continue;1407 }1408 }14091410 // Look for combo options following single dash, eat first one if known.1411 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1412 const option = this._findOption(`-${arg[1]}`);1413 if (option) {1414 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1415 // option with value following in same argument1416 this.emit(`option:${option.name()}`, arg.slice(2));1417 } else {1418 // boolean option, emit and put back remainder of arg for further processing1419 this.emit(`option:${option.name()}`);1420 args.unshift(`-${arg.slice(2)}`);1421 }1422 continue;1423 }1424 }14251426 // Look for known long flag with value, like --foo=bar1427 if (/^--[^=]+=/.test(arg)) {1428 const index = arg.indexOf('=');1429 const option = this._findOption(arg.slice(0, index));1430 if (option && (option.required || option.optional)) {1431 this.emit(`option:${option.name()}`, arg.slice(index + 1));1432 continue;1433 }1434 }14351436 // Not a recognised option by this command.1437 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14381439 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1440 if (maybeOption(arg)) {1441 dest = unknown;1442 }14431444 // If using positionalOptions, stop processing our options at subcommand.1445 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1446 if (this._findCommand(arg)) {1447 operands.push(arg);1448 if (args.length > 0) unknown.push(...args);1449 break;1450 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1451 operands.push(arg);1452 if (args.length > 0) operands.push(...args);1453 break;1454 } else if (this._defaultCommandName) {1455 unknown.push(arg);1456 if (args.length > 0) unknown.push(...args);1457 break;1458 }1459 }14601461 // If using passThroughOptions, stop processing options at first command-argument.1462 if (this._passThroughOptions) {1463 dest.push(arg);1464 if (args.length > 0) dest.push(...args);1465 break;1466 }14671468 // add arg1469 dest.push(arg);1470 }14711472 return { operands, unknown };

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

line 1473why, one step back
1473 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1474–1475why, one step back
1474
1475 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1477–1493why, one step back
1477 *
1478 * @return {Object}1479 */1480 opts() {1481 if (this._storeOptionsAsProperties) {1482 // Preserve original behaviour so backwards compatible when still using properties1483 const result = {};1484 const len = this.options.length;14851486 for (let i = 0; i < len; i++) {1487 const key = this.options[i].attributeName();1488 result[key] = key === this._versionOptionName ? this._version : this[key];1489 }1490 return result;1491 }14921493 return this._optionValues;

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

line 1494why, one step back
1494 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1495–1496why, one step back
1495
1496 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1498why, one step back
1498 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1500why, one step back
1500 */

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

lines 1501–1518why, one step back
1501 optsWithGlobals() {
1502 // globals overwrite locals1503 return getCommandAndParents(this).reduce(1504 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1505 {}1506 );1507 }15081509 /**1510 * Display error message and exit (or call exitOverride).1511 *1512 * @param {string} message1513 * @param {Object} [errorOptions]1514 * @param {string} [errorOptions.code] - an id string representing the error1515 * @param {number} [errorOptions.exitCode] - used with process.exit1516 */1517 error(message, errorOptions) {1518 // output handling

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 1520–1525why, one step back
1520 if (typeof this._showHelpAfterError === 'string') {
1521 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1522 } else if (this._showHelpAfterError) {1523 this._outputConfiguration.writeErr('\n');1524 this.outputHelp({ error: true });1525 }

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

lines 1526–1530why, one step back
1526
1527 // exit handling1528 const config = errorOptions || {};1529 const exitCode = config.exitCode || 1;1530 const code = config.code || 'commander.error';

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1532–1543why, one step back
1532 }
15331534 /**1535 * Apply any option related environment variables, if option does1536 * not have a value from cli or client code.1537 *1538 * @api private1539 */1540 _parseOptionsEnv() {1541 this.options.forEach((option) => {1542 if (option.envVar && option.envVar in process.env) {1543 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 1544–1545why, one step back
1544 // Priority check. Do not overwrite cli or options from unknown source (client-code).
1545 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 1546–1555why, one step back
1546 if (option.required || option.optional) { // option can take a value
1547 // keep very simple, optional always takes value1548 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1549 } else { // boolean1550 // keep very simple, only care that envVar defined and not the value1551 this.emit(`optionEnv:${option.name()}`);1552 }1553 }1554 }1555 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1556–1566why, one step back
1556 }
15571558 /**1559 * Argument `name` is missing.1560 *1561 * @param {string} name1562 * @api private1563 */15641565 missingArgument(name) {1566 const message = `error: missing required argument '${name}'`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1569–1578why, one step back
1569
1570 /**1571 * `Option` is missing an argument.1572 *1573 * @param {Option} option1574 * @api private1575 */15761577 optionMissingArgument(option) {1578 const message = `error: option '${option.flags}' argument missing`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1581–1590why, one step back
1581
1582 /**1583 * `Option` does not have a value, and is a mandatory option.1584 *1585 * @param {Option} option1586 * @api private1587 */15881589 missingMandatoryOptionValue(option) {1590 const message = `error: required option '${option.flags}' not specified`;

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

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

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

lines 1592–1629why, one step back
1592 }
15931594 /**1595 * `Option` conflicts with another option.1596 *1597 * @param {Option} option1598 * @param {Option} conflictingOption1599 * @api private1600 */1601 _conflictingOption(option, conflictingOption) {1602 // The calling code does not know whether a negated option is the source of the1603 // value, so do some work to take an educated guess.1604 const findBestOptionFromValue = (option) => {1605 const optionKey = option.attributeName();1606 const optionValue = this.getOptionValue(optionKey);1607 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1608 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1609 if (negativeOption && (1610 (negativeOption.presetArg === undefined && optionValue === false) ||1611 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1612 )) {1613 return negativeOption;1614 }1615 return positiveOption || option;1616 };16171618 const getErrorMessage = (option) => {1619 const bestOption = findBestOptionFromValue(option);1620 const optionKey = bestOption.attributeName();1621 const source = this.getOptionValueSource(optionKey);1622 if (source === 'env') {1623 return `environment variable '${bestOption.envVar}'`;1624 }1625 return `option '${bestOption.flags}'`;1626 };16271628 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1629 this.error(message, { code: 'commander.conflictingOption' });

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

line 1630why, one step back
1630 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1631–1640why, one step back
1631
1632 /**1633 * Unknown option `flag`.1634 *1635 * @param {string} flag1636 * @api private1637 */16381639 unknownOption(flag) {1640 if (this._allowUnknownOption) return;

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

lines 1641–1657why, one step back
1641 let suggestion = '';
16421643 if (flag.startsWith('--') && this._showSuggestionAfterError) {1644 // Looping to pick up the global options too1645 let candidateFlags = [];1646 let command = this;1647 do {1648 const moreFlags = command.createHelp().visibleOptions(command)1649 .filter(option => option.long)1650 .map(option => option.long);1651 candidateFlags = candidateFlags.concat(moreFlags);1652 command = command.parent;1653 } while (command && !command._enablePositionalOptions);1654 suggestion = suggestSimilar(flag, candidateFlags);1655 }16561657 const message = `error: unknown option '${flag}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1660–1674why, one step back
1660
1661 /**1662 * Excess arguments, more than expected.1663 *1664 * @param {string[]} receivedArgs1665 * @api private1666 */16671668 _excessArguments(receivedArgs) {1669 if (this._allowExcessArguments) return;16701671 const expected = this._args.length;1672 const s = (expected === 1) ? '' : 's';1673 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1674 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 1675–1676why, one step back
1675 this.error(message, { code: 'commander.excessArguments' });
1676 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1677–1684why, one step back
1677
1678 /**1679 * Unknown command.1680 *1681 * @api private1682 */16831684 unknownCommand() {

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

lines 1685–1698why, one step back
1685 const unknownName = this.args[0];
1686 let suggestion = '';16871688 if (this._showSuggestionAfterError) {1689 const candidateNames = [];1690 this.createHelp().visibleCommands(this).forEach((command) => {1691 candidateNames.push(command.name());1692 // just visible alias1693 if (command.alias()) candidateNames.push(command.alias());1694 });1695 suggestion = suggestSimilar(unknownName, candidateNames);1696 }16971698 const message = `error: unknown command '${unknownName}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1701–1728why, one step back
1701
1702 /**1703 * Set the program version to `str`.1704 *1705 * This method auto-registers the "-V, --version" flag1706 * which will print the version number when passed.1707 *1708 * You can optionally supply the flags and description to override the defaults.1709 *1710 * @param {string} str1711 * @param {string} [flags]1712 * @param {string} [description]1713 * @return {this | string} `this` command for chaining, or version string if no arguments1714 */17151716 version(str, flags, description) {1717 if (str === undefined) return this._version;1718 this._version = str;1719 flags = flags || '-V, --version';1720 description = description || 'output the version number';1721 const versionOption = this.createOption(flags, description);1722 this._versionOptionName = versionOption.attributeName();1723 this.options.push(versionOption);1724 this.on('option:' + versionOption.name(), () => {1725 this._outputConfiguration.writeOut(`${str}\n`);1726 this._exit(0, 'commander.version', str);1727 });1728 return this;

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

line 1729why, one step back
1729 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1730–1744why, one step back
1730
1731 /**1732 * Set the description to `str`.1733 *1734 * @param {string} [str]1735 * @param {Object} [argsDescription]1736 * @return {string|Command}1737 */1738 description(str, argsDescription) {1739 if (str === undefined && argsDescription === undefined) return this._description;1740 this._description = str;1741 if (argsDescription) {1742 this._argsDescription = argsDescription;1743 }1744 return this;

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

line 1745why, one step back
1745 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1746–1758why, one step back
1746
1747 /**1748 * Set an alias for the command.1749 *1750 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1751 *1752 * @param {string} [alias]1753 * @return {string|Command}1754 */17551756 alias(alias) {1757 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1758

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1760–1769why, one step back
1760 let command = this;
1761 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1762 // assume adding alias for last added executable subcommand, rather than this1763 command = this.commands[this.commands.length - 1];1764 }17651766 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');17671768 command._aliases.push(alias);1769 return this;

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

line 1770why, one step back
1770 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1771–1786why, one step back
1771
1772 /**1773 * Set aliases for the command.1774 *1775 * Only the first alias is shown in the auto-generated help.1776 *1777 * @param {string[]} [aliases]1778 * @return {string[]|Command}1779 */17801781 aliases(aliases) {1782 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1783 if (aliases === undefined) return this._aliases;17841785 aliases.forEach((alias) => this.alias(alias));1786 return this;

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

line 1787why, one step back
1787 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1788–1811why, one step back
1788
1789 /**1790 * Set / get the command usage `str`.1791 *1792 * @param {string} [str]1793 * @return {String|Command}1794 */17951796 usage(str) {1797 if (str === undefined) {1798 if (this._usage) return this._usage;17991800 const args = this._args.map((arg) => {1801 return humanReadableArgName(arg);1802 });1803 return [].concat(1804 (this.options.length || this._hasHelpOption ? '[options]' : []),1805 (this.commands.length ? '[command]' : []),1806 (this._args.length ? args : [])1807 ).join(' ');1808 }18091810 this._usage = str;1811 return this;

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

line 1812why, one step back
1812 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1813–1814why, one step back
1813
1814 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1816–1824why, one step back
1816 *
1817 * @param {string} [str]1818 * @return {string|Command}1819 */18201821 name(str) {1822 if (str === undefined) return this._name;1823 this._name = str;1824 return this;

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

line 1825why, one step back
1825 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1828–1864why, one step back
1828 * Set the name of the command from script filename, such as process.argv[1],
1829 * or require.main.filename, or __filename.1830 *1831 * (Used internally and public although not documented in README.)1832 *1833 * @example1834 * program.nameFromFilename(require.main.filename);1835 *1836 * @param {string} filename1837 * @return {Command}1838 */18391840 nameFromFilename(filename) {1841 this._name = path.basename(filename, path.extname(filename));18421843 return this;1844 }18451846 /**1847 * Get or set the directory for searching for executable subcommands of this command.1848 *1849 * @example1850 * program.executableDir(__dirname);1851 * // or1852 * program.executableDir('subcommands');1853 *1854 * @param {string} [path]1855 * @return {string|Command}1856 */18571858 executableDir(path) {1859 if (path === undefined) return this._executableDir;1860 this._executableDir = path;1861 return this;1862 }18631864 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1865–1876why, one step back
1865 * Return program help documentation.
1866 *1867 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1868 * @return {string}1869 */18701871 helpInformation(contextOptions) {1872 const helper = this.createHelp();1873 if (helper.helpWidth === undefined) {1874 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1875 }1876 return helper.formatHelp(this, helper);

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

line 1877why, one step back
1877 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1878–1912why, one step back
1878
1879 /**1880 * @api private1881 */18821883 _getHelpContext(contextOptions) {1884 contextOptions = contextOptions || {};1885 const context = { error: !!contextOptions.error };1886 let write;1887 if (context.error) {1888 write = (arg) => this._outputConfiguration.writeErr(arg);1889 } else {1890 write = (arg) => this._outputConfiguration.writeOut(arg);1891 }1892 context.write = contextOptions.write || write;1893 context.command = this;1894 return context;1895 }18961897 /**1898 * Output help information for this command.1899 *1900 * Outputs built-in help, and custom text added using `.addHelpText()`.1901 *1902 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1903 */19041905 outputHelp(contextOptions) {1906 let deprecatedCallback;1907 if (typeof contextOptions === 'function') {1908 deprecatedCallback = contextOptions;1909 contextOptions = undefined;1910 }1911 const context = this._getHelpContext(contextOptions);1912

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1914–1926why, one step back
1914 this.emit('beforeHelp', context);
19151916 let helpInformation = this.helpInformation(context);1917 if (deprecatedCallback) {1918 helpInformation = deprecatedCallback(helpInformation);1919 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1920 throw new Error('outputHelp callback must return a string or a Buffer');1921 }1922 }1923 context.write(helpInformation);19241925 this.emit(this._helpLongFlag); // deprecated1926 this.emit('afterHelp', context);

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

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

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

line 1928why, one step back
1928 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1929–1952why, one step back
1929
1930 /**1931 * You can pass in flags and a description to override the help1932 * flags and help description for your command. Pass in false to1933 * disable the built-in help option.1934 *1935 * @param {string | boolean} [flags]1936 * @param {string} [description]1937 * @return {Command} `this` command for chaining1938 */19391940 helpOption(flags, description) {1941 if (typeof flags === 'boolean') {1942 this._hasHelpOption = flags;1943 return this;1944 }1945 this._helpFlags = flags || this._helpFlags;1946 this._helpDescription = description || this._helpDescription;19471948 const helpFlags = splitOptionFlags(this._helpFlags);1949 this._helpShortFlag = helpFlags.shortFlag;1950 this._helpLongFlag = helpFlags.longFlag;19511952 return this;

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

line 1953why, one step back
1953 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1954–1970why, one step back
1954
1955 /**1956 * Output help information and exit.1957 *1958 * Outputs built-in help, and custom text added using `.addHelpText()`.1959 *1960 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1961 */19621963 help(contextOptions) {1964 this.outputHelp(contextOptions);1965 let exitCode = process.exitCode || 0;1966 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1967 exitCode = 1;1968 }1969 // message: do not have all displayed text available so only passing placeholder.1970 this._exit(exitCode, 'commander.help', '(outputHelp)');

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

line 1971why, one step back
1971 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1972–2003why, one step back
1972
1973 /**1974 * Add additional text to be displayed with the built-in help.1975 *1976 * Position is 'before' or 'after' to affect just this command,1977 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1978 *1979 * @param {string} position - before or after built-in help1980 * @param {string | Function} text - string to add, or a function returning a string1981 * @return {Command} `this` command for chaining1982 */1983 addHelpText(position, text) {1984 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1985 if (!allowedValues.includes(position)) {1986 throw new Error(`Unexpected value for position to addHelpText.1987Expecting one of '${allowedValues.join("', '")}'`);1988 }1989 const helpEvent = `${position}Help`;1990 this.on(helpEvent, (context) => {1991 let helpStr;1992 if (typeof text === 'function') {1993 helpStr = text({ error: context.error, command: context.command });1994 } else {1995 helpStr = text;1996 }1997 // Ignore falsy value when nothing to output.1998 if (helpStr) {1999 context.write(`${helpStr}\n`);2000 }

The first 2,000 of 2,084 lines.