Skip to content
Myr

command.js

This file

Path

lib/command.js

2,196 lines · 68.8 KiB · JavaScript

Last changed by

trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a

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

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

line 10why, one step back
10const { Option, splitOptionFlags, DualOptions } = 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 implied to option value sources (#1794)John Geebefore adoption72be61c

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

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–50why, one step back
46 this._defaultCommandName = null;
47 this._exitCallback = null;48 this._aliases = [];49 this._combineFlagAndOptionalValue = true;50 this._description = '';

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

line 51why, one step back
51 this._summary = '';

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

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

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

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

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 108–112why, one step back
108
109 return this;110 }111112 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 125why, one step back
125 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 162why, one step back
162 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 176why, one step back
176 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 187why, one step back
187 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 188–209why, one step back
188
189 /**190 * You can customise the help by overriding Help properties using configureHelp(),191 * or with a subclass of Help by overriding createHelp().192 *193 * @param {Object} [configuration] - configuration options194 * @return {Command|Object} `this` command for chaining, or stored configuration195 */196197 configureHelp(configuration) {198 if (configuration === undefined) return this._helpConfiguration;199200 this._helpConfiguration = configuration;201 return this;202 }203204 /**205 * The default output goes to stdout and stderr. You can customise this for special206 * applications. You can also customise the display of errors by overriding outputError.207 *208 * The configuration properties are all functions:209 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 218–230why, one step back
218 *
219 * @param {Object} [configuration] - configuration options220 * @return {Command|Object} `this` command for chaining, or stored configuration221 */222223 configureOutput(configuration) {224 if (configuration === undefined) return this._outputConfiguration;225226 Object.assign(this._outputConfiguration, configuration);227 return this;228 }229230 /**

Add showHelpAfterError (#1534)John Geebefore adoption082717f

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 267–275why, one step back
267 }
268269 opts = opts || {};270 if (opts.isDefault) this._defaultCommandName = cmd._name;271 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation272273 this.commands.push(cmd);274 cmd.parent = this;275 return this;

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

line 276why, one step back
276 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 277–290why, one step back
277
278 /**279 * Factory routine to create a new unattached argument.280 *281 * See .argument() for creating an attached argument, which uses this routine to282 * create the argument. You can override createArgument to return a custom argument.283 *284 * @param {string} name285 * @param {string} [description]286 * @return {Argument} new argument287 */288289 createArgument(name, description) {290 return new Argument(name, description);

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

line 291why, one step back
291 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 327–332why, one step back
327 *
328 * @param {string} names329 * @return {Command} `this` command for chaining330 */331332 arguments(names) {

trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a

line 333why, one step back
333 names.trim().split(/ +/).forEach((detail) => {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 334–336why, one step back
334 this.argument(detail);
335 });336 return this;

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

line 337why, one step back
337 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 379why, one step back
379 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 391why, one step back
391 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 392–401why, one step back
392
393 /**394 * Add hook for life cycle event.395 *396 * @param {string} event397 * @param {Function} listener398 * @return {Command} `this` command for chaining399 */400401 hook(event, listener) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 403–434why, one step back
403 if (!allowedValues.includes(event)) {
404 throw new Error(`Unexpected value for event passed to hook : '${event}'.405Expecting one of '${allowedValues.join("', '")}'`);406 }407 if (this._lifeCycleHooks[event]) {408 this._lifeCycleHooks[event].push(listener);409 } else {410 this._lifeCycleHooks[event] = [listener];411 }412 return this;413 }414415 /**416 * Register callback to use as replacement for calling process.exit.417 *418 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing419 * @return {Command} `this` command for chaining420 */421422 exitOverride(fn) {423 if (fn) {424 this._exitCallback = fn;425 } else {426 this._exitCallback = (err) => {427 if (err.code !== 'commander.executeSubCommandAsync') {428 throw err;429 } else {430 // Async callback from spawn events, not useful to throw.431 }432 };433 }434 return this;

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

line 435why, one step back
435 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 453why, one step back
453 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

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

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

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

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 486why, one step back
486 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 487–500why, one step back
487
488 /**489 * Factory routine to create a new unattached option.490 *491 * See .option() for creating an attached option, which uses this routine to492 * create the option. You can override createOption to return a custom option.493 *494 * @param {string} flags495 * @param {string} [description]496 * @return {Option} new option497 */498499 createOption(flags, description) {500 return new Option(flags, description);

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

line 501why, one step back
501 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 519why, one step back
519 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 522–526why, one step back
522 }
523524 // register the option525 this.options.push(option);526

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 557why, one step back
557 } else {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 576–584why, one step back
576 return this;
577 }578579 /**580 * Internal implementation shared by .option() and .requiredOption()581 *582 * @api private583 */584 _optionEx(config, flags, description, fn, defaultValue) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 618why, one step back
618 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 622why, one step back
622 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 625why, one step back
625 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 629why, one step back
629 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 632why, one step back
632 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 635why, one step back
635 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 639why, one step back
639 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 642why, one step back
642 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 646why, one step back
646 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 649–658why, one step back
649 *
650 * @param {string} flags651 * @param {string} [description]652 * @param {Function|*} [fn] - custom option processing function or default value653 * @param {*} [defaultValue]654 * @return {Command} `this` command for chaining655 */656657 option(flags, description, fn, defaultValue) {658 return this._optionEx({}, flags, description, fn, defaultValue);

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

line 659why, one step back
659 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 660–675why, one step back
660
661 /**662 * Add a required option which must have a value after parsing. This usually means663 * the option must be specified on the command line. (Otherwise the same as .option().)664 *665 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.666 *667 * @param {string} flags668 * @param {string} [description]669 * @param {Function|*} [fn] - custom option processing function or default value670 * @param {*} [defaultValue]671 * @return {Command} `this` command for chaining672 */673674 requiredOption(flags, description, fn, defaultValue) {675 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);

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

line 676why, one step back
676 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 691why, one step back
691 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 702why, one step back
702 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 713why, one step back
713 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 725why, one step back
725 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 742why, one step back
742 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 758why, one step back
758 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 759–771why, one step back
759
760 /**761 * Retrieve option value.762 *763 * @param {string} key764 * @return {Object} value765 */766767 getOptionValue(key) {768 if (this._storeOptionsAsProperties) {769 return this[key];770 }771 return this._optionValues[key];

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

line 772why, one step back
772 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 773–782why, one step back
773
774 /**775 * Store option value.776 *777 * @param {string} key778 * @param {Object} value779 * @return {Command} `this` command for chaining780 */781782 setOptionValue(key, value) {

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

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

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

line 784why, one step back
784 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 785–786why, one step back
785
786 /**

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

line 787why, one step back
787 * Store option value and where the value came from.

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 788–790why, one step back
788 *
789 * @param {string} key790 * @param {Object} value

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

line 791why, one step back
791 * @param {string} source - expected values are default/config/env/cli/implied

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 792–795why, one step back
792 * @return {Command} `this` command for chaining
793 */794795 setOptionValueWithSource(key, value, source) {

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

lines 796–800why, one step back
796 if (this._storeOptionsAsProperties) {
797 this[key] = value;798 } else {799 this._optionValues[key] = value;800 }

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

line 801why, one step back
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

line 806why, one step back
806 * Get source of option value.

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

line 807why, one step back
807 * Expected values are default | config | env | cli | implied

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 808–814why, one step back
808 *
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 branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 818–836why, one step back
818 * Get source of option value. See also .optsWithGlobals().
819 * Expected values are default | config | env | cli | implied820 *821 * @param {string} key822 * @return {string}823 */824825 getOptionValueSourceWithGlobals(key) {826 // global overwrites local, like optsWithGlobals827 let source;828 getCommandAndParents(this).forEach((cmd) => {829 if (cmd.getOptionValueSource(key) !== undefined) {830 source = cmd.getOptionValueSource(key);831 }832 });833 return source;834 }835836 /**

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

lines 837–838why, one step back
837 * Get user arguments from implied or explicit arguments.
838 * 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 839–882why, one step back
839 *
840 * @api private841 */842843 _prepareUserArgs(argv, parseOptions) {844 if (argv !== undefined && !Array.isArray(argv)) {845 throw new Error('first parameter to parse must be array or undefined');846 }847 parseOptions = parseOptions || {};848849 // Default to using process.argv850 if (argv === undefined) {851 argv = process.argv;852 // @ts-ignore: unknown property853 if (process.versions && process.versions.electron) {854 parseOptions.from = 'electron';855 }856 }857 this.rawArgs = argv.slice();858859 // make it a little easier for callers by supporting various argv conventions860 let userArgs;861 switch (parseOptions.from) {862 case undefined:863 case 'node':864 this._scriptPath = argv[1];865 userArgs = argv.slice(2);866 break;867 case 'electron':868 // @ts-ignore: unknown property869 if (process.defaultApp) {870 this._scriptPath = argv[1];871 userArgs = argv.slice(2);872 } else {873 userArgs = argv.slice(1);874 }875 break;876 case 'user':877 userArgs = argv.slice(0);878 break;879 default:880 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);881 }882

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 886–895why, one step back
886
887 return userArgs;888 }889890 /**891 * Parse `argv`, setting options and invoking commands when defined.892 *893 * The default expectation is that the arguments are from node and have the application as argv[0]894 * and the script being run in argv[1], with user parameters after that.895 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 900–911why, one step back
900 *
901 * @param {string[]} [argv] - optional, defaults to process.argv902 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron903 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'904 * @return {Command} `this` command for chaining905 */906907 parse(argv, parseOptions) {908 const userArgs = this._prepareUserArgs(argv, parseOptions);909 this._parseCommand([], userArgs);910911 return this;

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

line 912why, one step back
912 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 913–921why, one step back
913
914 /**915 * Parse `argv`, setting options and invoking commands when defined.916 *917 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.918 *919 * The default expectation is that the arguments are from node and have the application as argv[0]920 * and the script being run in argv[1], with user parameters after that.921 *

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

lines 922–925why, one step back
922 * @example
923 * await program.parseAsync(process.argv);924 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions925 * 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 926–937why, one step back
926 *
927 * @param {string[]} [argv]928 * @param {Object} [parseOptions]929 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'930 * @return {Promise}931 */932933 async parseAsync(argv, parseOptions) {934 const userArgs = this._prepareUserArgs(argv, parseOptions);935 await this._parseCommand([], userArgs);936937 return this;

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

line 938why, one step back
938 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 939–950why, one step back
939
940 /**941 * Execute a sub-command executable.942 *943 * @api private944 */945946 _executeSubCommand(subcommand, args) {947 args = args.slice();948 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.949 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];950

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

lines 951–954why, one step back
951 function findFile(baseDir, baseName) {
952 // Look for specified file953 const localBin = path.resolve(baseDir, baseName);954 if (fs.existsSync(localBin)) return localBin;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 955why, one step back
955

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 958why, one step back
958

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

lines 959–963why, one step back
959 // Try all the extensions.
960 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));961 if (foundExt) return `${localBin}${foundExt}`;962963 return undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 964–965why, one step back
964 }
965

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

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

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

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

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

lines 969–980why, one step back
969
970 // executableFile and executableDir might be full path, or just a name971 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;972 let executableDir = this._executableDir || '';973 if (this._scriptPath) {974 let resolvedScriptPath; // resolve possible symlink for installed npm binary975 try {976 resolvedScriptPath = fs.realpathSync(this._scriptPath);977 } catch (err) {978 resolvedScriptPath = this._scriptPath;979 }980 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 981–982why, one step back
981 }
982

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

lines 983–991why, one step back
983 // Look for a local file in preference to a command in PATH.
984 if (executableDir) {985 let localFile = findFile(executableDir, executableFile);986987 // Legacy search using prefix of script name instead of command name988 if (!localFile && !subcommand._executableFile && this._scriptPath) {989 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));990 if (legacyName !== this._name) {991 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 992why, one step back
992 }

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

lines 993–994why, one step back
993 }
994 executableFile = localFile || executableFile;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 995–996why, one step back
995 }
996

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 999–1001why, one step back
999 let proc;
1000 if (process.platform !== 'win32') {1001 if (launchWithNode) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1009–1010why, one step back
1009 }
1010 } else {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1012–1016why, one step back
1012 // add executable arguments to spawn
1013 args = incrementNodeInspectorPort(process.execArgv).concat(args);1014 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1015 }1016

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

lines 1017–1025why, one step back
1017 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
1018 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1019 signals.forEach((signal) => {1020 // @ts-ignore1021 process.on(signal, () => {1022 if (proc.killed === false && proc.exitCode === null) {1023 proc.kill(signal);1024 }1025 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1026why, one step back
1026 });

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

line 1027why, one step back
1027 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1028–1041why, one step back
1028
1029 // By default terminate process when spawned process terminates.1030 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1031 const exitCallback = this._exitCallback;1032 if (!exitCallback) {1033 proc.on('close', process.exit.bind(process));1034 } else {1035 proc.on('close', () => {1036 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1037 });1038 }1039 proc.on('error', (err) => {1040 // @ts-ignore1041 if (err.code === 'ENOENT') {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1049–1051why, one step back
1049 throw new Error(executableMissing);
1050 // @ts-ignore1051 } else if (err.code === 'EACCES') {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1053–1064why, one step back
1053 }
1054 if (!exitCallback) {1055 process.exit(1);1056 } else {1057 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1058 wrappedError.nestedError = err;1059 exitCallback(wrappedError);1060 }1061 });10621063 // Store the reference to the child process1064 this.runningCommand = proc;

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

line 1065why, one step back
1065 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1066–1074why, one step back
1066
1067 /**1068 * @api private1069 */10701071 _dispatchSubcommand(commandName, operands, unknown) {1072 const subCommand = this._findCommand(commandName);1073 if (!subCommand) this.help({ error: true });1074

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

lines 1075–1084why, one step back
1075 let hookResult;
1076 hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand');1077 hookResult = this._chainOrCall(hookResult, () => {1078 if (subCommand._executableHandler) {1079 this._executeSubCommand(subCommand, operands.concat(unknown));1080 } else {1081 return subCommand._parseCommand(operands, unknown);1082 }1083 });1084 return hookResult;

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

line 1085why, one step back
1085 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1086–1087why, one step back
1086
1087 /**

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

lines 1088–1107why, one step back
1088 * Invoke help directly if possible, or dispatch if necessary.
1089 * e.g. help foo1090 *1091 * @api private1092 */10931094 _dispatchHelpCommand(subcommandName) {1095 if (!subcommandName) {1096 this.help();1097 }1098 const subCommand = this._findCommand(subcommandName);1099 if (subCommand && !subCommand._executableHandler) {1100 subCommand.help();1101 }11021103 // Fallback to parsing the help flag to invoke the help.1104 return this._dispatchSubcommand(subcommandName, [], [this._helpLongFlag]);1105 }11061107 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1109–1112why, one step back
1109 *
1110 * @api private1111 */1112

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

lines 1113–1126why, one step back
1113 _checkNumberOfArguments() {
1114 // too few1115 this._args.forEach((arg, i) => {1116 if (arg.required && this.args[i] == null) {1117 this.missingArgument(arg.name());1118 }1119 });1120 // too many1121 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1122 return;1123 }1124 if (this.args.length > this._args.length) {1125 this._excessArguments(this.args);1126 }

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

line 1127why, one step back
1127 }

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

lines 1128–1135why, one step back
1128
1129 /**1130 * Process this.args using this._args and save as this.processedArgs!1131 *1132 * @api private1133 */11341135 _processArguments() {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1136–1144why, one step back
1136 const myParseArg = (argument, value, previous) => {
1137 // Extra processing for nice error message on parsing failure.1138 let parsedValue = value;1139 if (value !== null && argument.parseArg) {1140 try {1141 parsedValue = argument.parseArg(value, previous);1142 } catch (err) {1143 if (err.code === 'commander.invalidArgument') {1144 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 1145why, one step back
1145 this.error(message, { exitCode: err.exitCode, code: err.code });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1146–1152why, one step back
1146 }
1147 throw err;1148 }1149 }1150 return parsedValue;1151 };1152

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

lines 1153–1155why, one step back
1153 this._checkNumberOfArguments();
11541155 const processedArgs = [];

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1156–1175why, one step back
1156 this._args.forEach((declaredArg, index) => {
1157 let value = declaredArg.defaultValue;1158 if (declaredArg.variadic) {1159 // Collect together remaining arguments for passing together as an array.1160 if (index < this.args.length) {1161 value = this.args.slice(index);1162 if (declaredArg.parseArg) {1163 value = value.reduce((processed, v) => {1164 return myParseArg(declaredArg, v, processed);1165 }, declaredArg.defaultValue);1166 }1167 } else if (value === undefined) {1168 value = [];1169 }1170 } else if (index < this.args.length) {1171 value = this.args[index];1172 if (declaredArg.parseArg) {1173 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1174 }1175 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1177why, one step back
1177 });

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1179–1186why, one step back
1179 }
11801181 /**1182 * Once we have a promise we chain, but call synchronously until then.1183 *1184 * @param {Promise|undefined} promise1185 * @param {Function} fn1186 * @return {Promise|undefined}

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1188–1227why, one step back
1188 */
11891190 _chainOrCall(promise, fn) {1191 // thenable1192 if (promise && promise.then && typeof promise.then === 'function') {1193 // already have a promise, chain callback1194 return promise.then(() => fn());1195 }1196 // callback might return a promise1197 return fn();1198 }11991200 /**1201 *1202 * @param {Promise|undefined} promise1203 * @param {string} event1204 * @return {Promise|undefined}1205 * @api private1206 */12071208 _chainOrCallHooks(promise, event) {1209 let result = promise;1210 const hooks = [];1211 getCommandAndParents(this)1212 .reverse()1213 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1214 .forEach(hookedCommand => {1215 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1216 hooks.push({ hookedCommand, callback });1217 });1218 });1219 if (event === 'postAction') {1220 hooks.reverse();1221 }12221223 hooks.forEach((hookDetail) => {1224 result = this._chainOrCall(result, () => {1225 return hookDetail.callback(hookDetail.hookedCommand, this);1226 });1227 });

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

lines 1228–1248why, one step back
1228 return result;
1229 }12301231 /**1232 *1233 * @param {Promise|undefined} promise1234 * @param {Command} subCommand1235 * @param {string} event1236 * @return {Promise|undefined}1237 * @api private1238 */12391240 _chainOrCallSubCommandHook(promise, subCommand, event) {1241 let result = promise;1242 if (this._lifeCycleHooks[event] !== undefined) {1243 this._lifeCycleHooks[event].forEach((hook) => {1244 result = this._chainOrCall(result, () => {1245 return hook(this, subCommand);1246 });1247 });1248 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1249–1260why, one step back
1249 return result;
1250 }12511252 /**1253 * Process arguments in context of this command.1254 * Returns action result, in case it is a promise.1255 *1256 * @api private1257 */12581259 _parseCommand(operands, unknown) {1260 const parsed = this.parseOptions(unknown);

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1263–1270why, one step back
1263 operands = operands.concat(parsed.operands);
1264 unknown = parsed.unknown;1265 this.args = operands.concat(unknown);12661267 if (operands && this._findCommand(operands[0])) {1268 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1269 }1270 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1272–1283why, one step back
1272 }
1273 if (this._defaultCommandName) {1274 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1275 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1276 }1277 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1278 // probably missing subcommand and no handler, user needs help (and exit)1279 this.help({ error: true });1280 }12811282 outputHelpIfRequested(this, parsed.unknown);1283 this._checkForMissingMandatoryOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1285–1295why, one step back
1285
1286 // We do not always call this check to avoid masking a "better" error, like unknown command.1287 const checkForUnknownOptions = () => {1288 if (parsed.unknown.length > 0) {1289 this.unknownOption(parsed.unknown[0]);1290 }1291 };12921293 const commandEvent = `command:${this.name()}`;1294 if (this._actionHandler) {1295 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1297–1299why, one step back
1297
1298 let actionResult;1299 actionResult = this._chainOrCallHooks(actionResult, 'preAction');

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

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

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

lines 1301–1305why, one step back
1301 if (this.parent) {
1302 actionResult = this._chainOrCall(actionResult, () => {1303 this.parent.emit(commandEvent, operands, unknown); // legacy1304 });1305 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1306–1310why, one step back
1306 actionResult = this._chainOrCallHooks(actionResult, 'postAction');
1307 return actionResult;1308 }1309 if (this.parent && this.parent.listenerCount(commandEvent)) {1310 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1312–1323why, one step back
1312 this.parent.emit(commandEvent, operands, unknown); // legacy
1313 } else if (operands.length) {1314 if (this._findCommand('*')) { // legacy default command1315 return this._dispatchSubcommand('*', operands, unknown);1316 }1317 if (this.listenerCount('command:*')) {1318 // skip option check, emit event for possible misspelling suggestion1319 this.emit('command:*', operands, unknown);1320 } else if (this.commands.length) {1321 this.unknownCommand();1322 } else {1323 checkForUnknownOptions();

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1335why, one step back
1335 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1336–1344why, one step back
1336
1337 /**1338 * Find matching command.1339 *1340 * @api private1341 */1342 _findCommand(name) {1343 if (!name) return undefined;1344 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));

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

line 1345why, one step back
1345 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1346–1356why, one step back
1346
1347 /**1348 * Return an option matching `arg` if any.1349 *1350 * @param {string} arg1351 * @return {Option}1352 * @api private1353 */13541355 _findOption(arg) {1356 return this.options.find(option => option.is(arg));

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

line 1357why, one step back
1357 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1358–1360why, one step back
1358
1359 /**1360 * Display an error message if a mandatory option does not have a value.

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1362–1374why, one step back
1362 *
1363 * @api private1364 */13651366 _checkForMissingMandatoryOptions() {1367 // Walk up hierarchy so can call in subcommand after checking for displaying help.1368 for (let cmd = this; cmd; cmd = cmd.parent) {1369 cmd.options.forEach((anOption) => {1370 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1371 cmd.missingMandatoryOptionValue(anOption);1372 }1373 });1374 }

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

line 1375why, one step back
1375 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1376–1377why, one step back
1376
1377 /**

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

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

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

lines 1379–1381why, one step back
1379 *
1380 * @api private1381 */

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

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

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

lines 1383–1404why, one step back
1383 const definedNonDefaultOptions = this.options.filter(
1384 (option) => {1385 const optionKey = option.attributeName();1386 if (this.getOptionValue(optionKey) === undefined) {1387 return false;1388 }1389 return this.getOptionValueSource(optionKey) !== 'default';1390 }1391 );13921393 const optionsWithConflicting = definedNonDefaultOptions.filter(1394 (option) => option.conflictsWith.length > 01395 );13961397 optionsWithConflicting.forEach((option) => {1398 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1399 option.conflictsWith.includes(defined.attributeName())1400 );1401 if (conflictingAndDefined) {1402 this._conflictingOption(option, conflictingAndDefined);1403 }1404 });

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

lines 1405–1417why, one step back
1405 }
14061407 /**1408 * Display an error message if conflicting options are used together.1409 * Called after checking for help flags in leaf subcommand.1410 *1411 * @api private1412 */1413 _checkForConflictingOptions() {1414 // Walk up hierarchy so can call in subcommand after checking for displaying help.1415 for (let cmd = this; cmd; cmd = cmd.parent) {1416 cmd._checkForConflictingLocalOptions();1417 }

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

lines 1418–1420why, one step back
1418 }
14191420 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1421–1425why, one step back
1421 * Parse options from `argv` removing known options,
1422 * and return argv split into operands and unknown arguments.1423 *1424 * Examples:1425 *

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

lines 1426–1430why, one step back
1426 * argv => operands, unknown
1427 * --known kkk op => [op], []1428 * op --known kkk => [op], []1429 * sub --unknown uuu op => [sub], [--unknown uuu op]1430 * sub -- --unknown uuu op => [sub --unknown uuu op], []

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1431–1549why, one step back
1431 *
1432 * @param {String[]} argv1433 * @return {{operands: String[], unknown: String[]}}1434 */14351436 parseOptions(argv) {1437 const operands = []; // operands, not options or values1438 const unknown = []; // first unknown option and remaining unknown args1439 let dest = operands;1440 const args = argv.slice();14411442 function maybeOption(arg) {1443 return arg.length > 1 && arg[0] === '-';1444 }14451446 // parse options1447 let activeVariadicOption = null;1448 while (args.length) {1449 const arg = args.shift();14501451 // literal1452 if (arg === '--') {1453 if (dest === unknown) dest.push(arg);1454 dest.push(...args);1455 break;1456 }14571458 if (activeVariadicOption && !maybeOption(arg)) {1459 this.emit(`option:${activeVariadicOption.name()}`, arg);1460 continue;1461 }1462 activeVariadicOption = null;14631464 if (maybeOption(arg)) {1465 const option = this._findOption(arg);1466 // recognised option, call listener to assign value with possible custom processing1467 if (option) {1468 if (option.required) {1469 const value = args.shift();1470 if (value === undefined) this.optionMissingArgument(option);1471 this.emit(`option:${option.name()}`, value);1472 } else if (option.optional) {1473 let value = null;1474 // historical behaviour is optional value is following arg unless an option1475 if (args.length > 0 && !maybeOption(args[0])) {1476 value = args.shift();1477 }1478 this.emit(`option:${option.name()}`, value);1479 } else { // boolean flag1480 this.emit(`option:${option.name()}`);1481 }1482 activeVariadicOption = option.variadic ? option : null;1483 continue;1484 }1485 }14861487 // Look for combo options following single dash, eat first one if known.1488 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1489 const option = this._findOption(`-${arg[1]}`);1490 if (option) {1491 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1492 // option with value following in same argument1493 this.emit(`option:${option.name()}`, arg.slice(2));1494 } else {1495 // boolean option, emit and put back remainder of arg for further processing1496 this.emit(`option:${option.name()}`);1497 args.unshift(`-${arg.slice(2)}`);1498 }1499 continue;1500 }1501 }15021503 // Look for known long flag with value, like --foo=bar1504 if (/^--[^=]+=/.test(arg)) {1505 const index = arg.indexOf('=');1506 const option = this._findOption(arg.slice(0, index));1507 if (option && (option.required || option.optional)) {1508 this.emit(`option:${option.name()}`, arg.slice(index + 1));1509 continue;1510 }1511 }15121513 // Not a recognised option by this command.1514 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15151516 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1517 if (maybeOption(arg)) {1518 dest = unknown;1519 }15201521 // If using positionalOptions, stop processing our options at subcommand.1522 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1523 if (this._findCommand(arg)) {1524 operands.push(arg);1525 if (args.length > 0) unknown.push(...args);1526 break;1527 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1528 operands.push(arg);1529 if (args.length > 0) operands.push(...args);1530 break;1531 } else if (this._defaultCommandName) {1532 unknown.push(arg);1533 if (args.length > 0) unknown.push(...args);1534 break;1535 }1536 }15371538 // If using passThroughOptions, stop processing options at first command-argument.1539 if (this._passThroughOptions) {1540 dest.push(arg);1541 if (args.length > 0) dest.push(...args);1542 break;1543 }15441545 // add arg1546 dest.push(arg);1547 }15481549 return { operands, unknown };

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

line 1550why, one step back
1550 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1551–1552why, one step back
1551
1552 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1554–1570why, one step back
1554 *
1555 * @return {Object}1556 */1557 opts() {1558 if (this._storeOptionsAsProperties) {1559 // Preserve original behaviour so backwards compatible when still using properties1560 const result = {};1561 const len = this.options.length;15621563 for (let i = 0; i < len; i++) {1564 const key = this.options[i].attributeName();1565 result[key] = key === this._versionOptionName ? this._version : this[key];1566 }1567 return result;1568 }15691570 return this._optionValues;

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

line 1571why, one step back
1571 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1572–1573why, one step back
1572
1573 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1575why, one step back
1575 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1577why, one step back
1577 */

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

lines 1578–1595why, one step back
1578 optsWithGlobals() {
1579 // globals overwrite locals1580 return getCommandAndParents(this).reduce(1581 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1582 {}1583 );1584 }15851586 /**1587 * Display error message and exit (or call exitOverride).1588 *1589 * @param {string} message1590 * @param {Object} [errorOptions]1591 * @param {string} [errorOptions.code] - an id string representing the error1592 * @param {number} [errorOptions.exitCode] - used with process.exit1593 */1594 error(message, errorOptions) {1595 // output handling

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 1597–1602why, one step back
1597 if (typeof this._showHelpAfterError === 'string') {
1598 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1599 } else if (this._showHelpAfterError) {1600 this._outputConfiguration.writeErr('\n');1601 this.outputHelp({ error: true });1602 }

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

lines 1603–1607why, one step back
1603
1604 // exit handling1605 const config = errorOptions || {};1606 const exitCode = config.exitCode || 1;1607 const code = config.code || 'commander.error';

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1609–1620why, one step back
1609 }
16101611 /**1612 * Apply any option related environment variables, if option does1613 * not have a value from cli or client code.1614 *1615 * @api private1616 */1617 _parseOptionsEnv() {1618 this.options.forEach((option) => {1619 if (option.envVar && option.envVar in process.env) {1620 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 1621–1622why, one step back
1621 // Priority check. Do not overwrite cli or options from unknown source (client-code).
1622 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 1623–1632why, one step back
1623 if (option.required || option.optional) { // option can take a value
1624 // keep very simple, optional always takes value1625 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1626 } else { // boolean1627 // keep very simple, only care that envVar defined and not the value1628 this.emit(`optionEnv:${option.name()}`);1629 }1630 }1631 }1632 });

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

lines 1633–1655why, one step back
1633 }
16341635 /**1636 * Apply any implied option values, if option is undefined or default value.1637 *1638 * @api private1639 */1640 _parseOptionsImplied() {1641 const dualHelper = new DualOptions(this.options);1642 const hasCustomOptionValue = (optionKey) => {1643 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1644 };1645 this.options1646 .filter(option => (option.implied !== undefined) &&1647 hasCustomOptionValue(option.attributeName()) &&1648 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1649 .forEach((option) => {1650 Object.keys(option.implied)1651 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1652 .forEach(impliedKey => {1653 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1654 });1655 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1656–1666why, one step back
1656 }
16571658 /**1659 * Argument `name` is missing.1660 *1661 * @param {string} name1662 * @api private1663 */16641665 missingArgument(name) {1666 const message = `error: missing required argument '${name}'`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1669–1678why, one step back
1669
1670 /**1671 * `Option` is missing an argument.1672 *1673 * @param {Option} option1674 * @api private1675 */16761677 optionMissingArgument(option) {1678 const message = `error: option '${option.flags}' argument missing`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1681–1690why, one step back
1681
1682 /**1683 * `Option` does not have a value, and is a mandatory option.1684 *1685 * @param {Option} option1686 * @api private1687 */16881689 missingMandatoryOptionValue(option) {1690 const message = `error: required option '${option.flags}' not specified`;

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

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

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

lines 1692–1729why, one step back
1692 }
16931694 /**1695 * `Option` conflicts with another option.1696 *1697 * @param {Option} option1698 * @param {Option} conflictingOption1699 * @api private1700 */1701 _conflictingOption(option, conflictingOption) {1702 // The calling code does not know whether a negated option is the source of the1703 // value, so do some work to take an educated guess.1704 const findBestOptionFromValue = (option) => {1705 const optionKey = option.attributeName();1706 const optionValue = this.getOptionValue(optionKey);1707 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1708 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1709 if (negativeOption && (1710 (negativeOption.presetArg === undefined && optionValue === false) ||1711 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1712 )) {1713 return negativeOption;1714 }1715 return positiveOption || option;1716 };17171718 const getErrorMessage = (option) => {1719 const bestOption = findBestOptionFromValue(option);1720 const optionKey = bestOption.attributeName();1721 const source = this.getOptionValueSource(optionKey);1722 if (source === 'env') {1723 return `environment variable '${bestOption.envVar}'`;1724 }1725 return `option '${bestOption.flags}'`;1726 };17271728 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1729 this.error(message, { code: 'commander.conflictingOption' });

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

line 1730why, one step back
1730 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1731–1740why, one step back
1731
1732 /**1733 * Unknown option `flag`.1734 *1735 * @param {string} flag1736 * @api private1737 */17381739 unknownOption(flag) {1740 if (this._allowUnknownOption) return;

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

lines 1741–1757why, one step back
1741 let suggestion = '';
17421743 if (flag.startsWith('--') && this._showSuggestionAfterError) {1744 // Looping to pick up the global options too1745 let candidateFlags = [];1746 let command = this;1747 do {1748 const moreFlags = command.createHelp().visibleOptions(command)1749 .filter(option => option.long)1750 .map(option => option.long);1751 candidateFlags = candidateFlags.concat(moreFlags);1752 command = command.parent;1753 } while (command && !command._enablePositionalOptions);1754 suggestion = suggestSimilar(flag, candidateFlags);1755 }17561757 const message = `error: unknown option '${flag}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1760–1774why, one step back
1760
1761 /**1762 * Excess arguments, more than expected.1763 *1764 * @param {string[]} receivedArgs1765 * @api private1766 */17671768 _excessArguments(receivedArgs) {1769 if (this._allowExcessArguments) return;17701771 const expected = this._args.length;1772 const s = (expected === 1) ? '' : 's';1773 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1774 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 1775–1776why, one step back
1775 this.error(message, { code: 'commander.excessArguments' });
1776 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1777–1784why, one step back
1777
1778 /**1779 * Unknown command.1780 *1781 * @api private1782 */17831784 unknownCommand() {

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

lines 1785–1798why, one step back
1785 const unknownName = this.args[0];
1786 let suggestion = '';17871788 if (this._showSuggestionAfterError) {1789 const candidateNames = [];1790 this.createHelp().visibleCommands(this).forEach((command) => {1791 candidateNames.push(command.name());1792 // just visible alias1793 if (command.alias()) candidateNames.push(command.alias());1794 });1795 suggestion = suggestSimilar(unknownName, candidateNames);1796 }17971798 const message = `error: unknown command '${unknownName}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1801–1828why, one step back
1801
1802 /**1803 * Set the program version to `str`.1804 *1805 * This method auto-registers the "-V, --version" flag1806 * which will print the version number when passed.1807 *1808 * You can optionally supply the flags and description to override the defaults.1809 *1810 * @param {string} str1811 * @param {string} [flags]1812 * @param {string} [description]1813 * @return {this | string} `this` command for chaining, or version string if no arguments1814 */18151816 version(str, flags, description) {1817 if (str === undefined) return this._version;1818 this._version = str;1819 flags = flags || '-V, --version';1820 description = description || 'output the version number';1821 const versionOption = this.createOption(flags, description);1822 this._versionOptionName = versionOption.attributeName();1823 this.options.push(versionOption);1824 this.on('option:' + versionOption.name(), () => {1825 this._outputConfiguration.writeOut(`${str}\n`);1826 this._exit(0, 'commander.version', str);1827 });1828 return this;

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

line 1829why, one step back
1829 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1830–1831why, one step back
1830
1831 /**

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

line 1832why, one step back
1832 * Set the description.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1833–1843why, one step back
1833 *
1834 * @param {string} [str]1835 * @param {Object} [argsDescription]1836 * @return {string|Command}1837 */1838 description(str, argsDescription) {1839 if (str === undefined && argsDescription === undefined) return this._description;1840 this._description = str;1841 if (argsDescription) {1842 this._argsDescription = argsDescription;1843 }

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

lines 1844–1855why, one step back
1844 return this;
1845 }18461847 /**1848 * Set the summary. Used when listed as subcommand of parent.1849 *1850 * @param {string} [str]1851 * @return {string|Command}1852 */1853 summary(str) {1854 if (str === undefined) return this._summary;1855 this._summary = str;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1856why, one step back
1856 return this;

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

line 1857why, one step back
1857 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1858–1870why, one step back
1858
1859 /**1860 * Set an alias for the command.1861 *1862 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1863 *1864 * @param {string} [alias]1865 * @return {string|Command}1866 */18671868 alias(alias) {1869 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1870

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1872–1881why, one step back
1872 let command = this;
1873 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1874 // assume adding alias for last added executable subcommand, rather than this1875 command = this.commands[this.commands.length - 1];1876 }18771878 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18791880 command._aliases.push(alias);1881 return this;

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

line 1882why, one step back
1882 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1883–1898why, one step back
1883
1884 /**1885 * Set aliases for the command.1886 *1887 * Only the first alias is shown in the auto-generated help.1888 *1889 * @param {string[]} [aliases]1890 * @return {string[]|Command}1891 */18921893 aliases(aliases) {1894 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1895 if (aliases === undefined) return this._aliases;18961897 aliases.forEach((alias) => this.alias(alias));1898 return this;

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

line 1899why, one step back
1899 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1900–1923why, one step back
1900
1901 /**1902 * Set / get the command usage `str`.1903 *1904 * @param {string} [str]1905 * @return {String|Command}1906 */19071908 usage(str) {1909 if (str === undefined) {1910 if (this._usage) return this._usage;19111912 const args = this._args.map((arg) => {1913 return humanReadableArgName(arg);1914 });1915 return [].concat(1916 (this.options.length || this._hasHelpOption ? '[options]' : []),1917 (this.commands.length ? '[command]' : []),1918 (this._args.length ? args : [])1919 ).join(' ');1920 }19211922 this._usage = str;1923 return this;

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

line 1924why, one step back
1924 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1925–1926why, one step back
1925
1926 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1928–1936why, one step back
1928 *
1929 * @param {string} [str]1930 * @return {string|Command}1931 */19321933 name(str) {1934 if (str === undefined) return this._name;1935 this._name = str;1936 return this;

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

line 1937why, one step back
1937 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1938–1939why, one step back
1938
1939 /**

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

lines 1940–1976why, one step back
1940 * Set the name of the command from script filename, such as process.argv[1],
1941 * or require.main.filename, or __filename.1942 *1943 * (Used internally and public although not documented in README.)1944 *1945 * @example1946 * program.nameFromFilename(require.main.filename);1947 *1948 * @param {string} filename1949 * @return {Command}1950 */19511952 nameFromFilename(filename) {1953 this._name = path.basename(filename, path.extname(filename));19541955 return this;1956 }19571958 /**1959 * Get or set the directory for searching for executable subcommands of this command.1960 *1961 * @example1962 * program.executableDir(__dirname);1963 * // or1964 * program.executableDir('subcommands');1965 *1966 * @param {string} [path]1967 * @return {string|Command}1968 */19691970 executableDir(path) {1971 if (path === undefined) return this._executableDir;1972 this._executableDir = path;1973 return this;1974 }19751976 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1977–1988why, one step back
1977 * Return program help documentation.
1978 *1979 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1980 * @return {string}1981 */19821983 helpInformation(contextOptions) {1984 const helper = this.createHelp();1985 if (helper.helpWidth === undefined) {1986 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1987 }1988 return helper.formatHelp(this, helper);

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

line 1989why, one step back
1989 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1990–2024why, one step back
1990
1991 /**1992 * @api private1993 */19941995 _getHelpContext(contextOptions) {1996 contextOptions = contextOptions || {};1997 const context = { error: !!contextOptions.error };1998 let write;1999 if (context.error) {2000 write = (arg) => this._outputConfiguration.writeErr(arg);

The first 2,000 of 2,196 lines.