command.js
This file
Path
lib/command.js
2,203 lines · 69.0 KiB · JavaScript
Last changed by
Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
History of this fileTake it
Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1–4why, one step back1const 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 back5const process = require('process');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 6–9why, one step back67const { 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 back10const { Option, splitOptionFlags, DualOptions } = require('./option.js');Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 11why, one step back11const { suggestSimilar } = require('./suggestSimilar');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 12–23why, one step back1213// @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 back24 /** @type {Command[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 25why, one step back25 this.commands = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 26why, one step back26 /** @type {Option[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 27–30why, one step back27 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 back31 /** @type {Argument[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 32why, one step back32 this._args = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 33–36why, one step back33 /** @type {string[]} */34 this.args = []; // cli args with options removed35 this.rawArgs = [];36 this.processedArgs = []; // like .args but after custom processing and collecting variadicRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 37–39why, one step back37 this._scriptPath = null;38 this._name = name || '';39 this._optionValues = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 40why, one step back40 this._optionValueSources = {}; // default, env, cli etcRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 41–44why, one step back41 this._storeOptionsAsProperties = false;42 this._actionHandler = null;43 this._executableHandler = false;44 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 45why, one step back45 this._executableDir = null; // custom search directory for subcommandsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 46–50why, one step back46 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 back51 this._summary = '';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 52–55why, one step back52 this._argsDescription = undefined; // legacy53 this._enablePositionalOptions = false;54 this._passThroughOptions = false;55 this._lifeCycleHooks = {}; // a hash of arraysAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 56–57why, one step back56 /** @type {boolean | string} */57 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 58why, one step back58 this._showSuggestionAfterError = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 59–82why, one step back5960 // 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 back83 * 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} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 88why, one step back88 * @return {Command} `this` command for chainingAdd copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 89–106why, one step back89 */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 back107 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 108–112why, one step back108109 return this;110 }111112 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 113–116why, one step back113 * 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 back117 * @example118 * // 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 back125 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 126–129why, one step back126 * // 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 back130 *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(/([^ ]+) *(.*)/);146Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 147why, one step back147 const cmd = this.createCommand(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 148–157why, one step back148 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 back158 cmd.copyInheritedSettings(this);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 159–161why, one step back159160 if (desc) return this;161 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 162why, one step back162 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 163–175why, one step back163164 /**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 back176 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 177–186why, one step back177178 /**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 back187 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 188–209why, one step back188189 /**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 back210 * // functions to change where being written, stdout and stderr211 * 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 helpRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 218–230why, one step back218 *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 back231 * 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 back243 * 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 back254 * 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 back264 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 back267 }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 back276 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 277–290why, one step back277278 /**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 back291 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 292–299why, one step back292293 /**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 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 300–301why, one step back300 * program.argument('<input-file>');301 * program.argument('[output-file]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 302–325why, one step back302 *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 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 326why, one step back326 * program.arguments('<cmd> [env]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 327–332why, one step back327 *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 back333 names.trim().split(/ +/).forEach((detail) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 334–336why, one step back334 this.argument(detail);335 });336 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 337why, one step back337 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 338–378why, one step back338339 /**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 back379 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 380–390why, one step back380381 /**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 back391 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 392–401why, one step back392393 /**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 back402 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 403–434why, one step back403 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 back435 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 436–452why, one step back436437 /**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 back453 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 454–457why, one step back454455 /**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 back458 * @example459 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 460–461why, one step back460 * .command('serve')461 * .description('start service')Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 462why, one step back462 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 463why, one step back463 * // do work hereFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 464why, one step back464 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 465–485why, one step back465 *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 back486 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 487–500why, one step back487488 /**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 back501 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 502–512why, one step back502503 /**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();512Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 513–518why, one step back513 // store default value514 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 back519 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 520–521why, one step back520 } 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 back522 }523524 // register the option525 this.options.push(option);526Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 527–528why, one step back527 // handler for cli and env supplied values528 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 529–533why, one step back529 // 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 back534535 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 536why, one step back536 const oldValue = this.getOptionValue(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 537–538why, one step back537 if (val !== null && option.parseArg) {538 try {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 539why, one step back539 val = option.parseArg(val, oldValue);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 540–541why, one step back540 } 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 back542 const message = `${invalidValueMessage} ${err.message}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 543why, one step back543 this.error(message, { exitCode: err.exitCode, code: err.code });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 544–550why, one step back544 }545 throw err;546 }547 } else if (val !== null && option.variadic) {548 val = option._concatValue(val, oldValue);549 }550Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 551–556why, one step back551 // 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 back557 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 558why, one step back558 val = ''; // not normal, parseArg might have failed or be a mock function for testingRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 559–560why, one step back559 }560 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 561why, one step back561 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 back562 };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 back567 });568Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 569–575why, one step back569 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 }575Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 576–584why, one step back576 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 back585 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 back588 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 back615 * "-p, --pepper"616 * "-p|--pepper"617 * "-p --pepper"Refactor classes into files (#1522)John Geebefore adoption08245cc
line 618why, one step back618 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 619–621why, one step back619 * @example620 * // simple boolean defaulting to undefined621 * program.option('-p, --pepper', 'add pepper');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 622why, one step back622 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 623–624why, one step back623 * program.pepper624 * // => undefinedRefactor classes into files (#1522)John Geebefore adoption08245cc
line 625why, one step back625 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 626–628why, one step back626 * --pepper627 * program.pepper628 * // => trueRefactor classes into files (#1522)John Geebefore adoption08245cc
line 629why, one step back629 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 630–631why, one step back630 * // 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 back632 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 633–634why, one step back633 * program.cheese634 * // => trueRefactor classes into files (#1522)John Geebefore adoption08245cc
line 635why, one step back635 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 636–638why, one step back636 * --no-cheese637 * program.cheese638 * // => falseRefactor classes into files (#1522)John Geebefore adoption08245cc
line 639why, one step back639 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 640–641why, one step back640 * // required argument641 * program.option('-C, --chdir <path>', 'change the working directory');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 642why, one step back642 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 643–645why, one step back643 * --chdir /tmp644 * program.chdir645 * // => "/tmp"Refactor classes into files (#1522)John Geebefore adoption08245cc
line 646why, one step back646 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 647–648why, one step back647 * // optional argument648 * program.option('-c, --cheese [type]', 'add cheese [marble]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 649–658why, one step back649 *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 back659 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 660–675why, one step back660661 /**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 back676 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 677–680why, one step back677678 /**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 back681 * @example682 * // 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 back685 *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 back691 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 692–701why, one step back692693 /**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 back702 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 703–712why, one step back703704 /**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 back713 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 714–724why, one step back714715 /**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 back725 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 726–741why, one step back726727 /**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 back742 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 743–755why, one step back743744 /**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 if (this.options.length) {754 throw new Error('call .storeOptionsAsProperties() before adding options');755 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
lines 756–759why, one step back756 if (Object.keys(this._optionValues).length) {757 throw new Error('call .storeOptionsAsProperties() before setting option values');758 }759 this._storeOptionsAsProperties = !!storeAsProperties;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 760why, one step back760 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 761why, one step back761 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 762–774why, one step back762763 /**764 * Retrieve option value.765 *766 * @param {string} key767 * @return {Object} value768 */769770 getOptionValue(key) {771 if (this._storeOptionsAsProperties) {772 return this[key];773 }774 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 775why, one step back775 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 776–785why, one step back776777 /**778 * Store option value.779 *780 * @param {string} key781 * @param {Object} value782 * @return {Command} `this` command for chaining783 */784785 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 786why, one step back786 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 787why, one step back787 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 788–789why, one step back788789 /**Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 790why, one step back790 * Store option value and where the value came from.Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 791–793why, one step back791 *792 * @param {string} key793 * @param {Object} valueAdd implied to option value sources (#1794)John Geebefore adoption72be61c
line 794why, one step back794 * @param {string} source - expected values are default/config/env/cli/impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 795–798why, one step back795 * @return {Command} `this` command for chaining796 */797798 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 799–803why, one step back799 if (this._storeOptionsAsProperties) {800 this[key] = value;801 } else {802 this._optionValues[key] = value;803 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 804why, one step back804 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 805why, one step back805 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 806–808why, one step back806 }807808 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 809why, one step back809 * Get source of option value.Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 810why, one step back810 * Expected values are default | config | env | cli | impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 811–817why, one step back811 *812 * @param {string} key813 * @return {string}814 */815816 getOptionValueSource(key) {817 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 818why, one step back818 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 819–820why, one step back819820 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 821–839why, one step back821 * Get source of option value. See also .optsWithGlobals().822 * Expected values are default | config | env | cli | implied823 *824 * @param {string} key825 * @return {string}826 */827828 getOptionValueSourceWithGlobals(key) {829 // global overwrites local, like optsWithGlobals830 let source;831 getCommandAndParents(this).forEach((cmd) => {832 if (cmd.getOptionValueSource(key) !== undefined) {833 source = cmd.getOptionValueSource(key);834 }835 });836 return source;837 }838839 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 840–841why, one step back840 * Get user arguments from implied or explicit arguments.841 * 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 842–885why, one step back842 *843 * @api private844 */845846 _prepareUserArgs(argv, parseOptions) {847 if (argv !== undefined && !Array.isArray(argv)) {848 throw new Error('first parameter to parse must be array or undefined');849 }850 parseOptions = parseOptions || {};851852 // Default to using process.argv853 if (argv === undefined) {854 argv = process.argv;855 // @ts-ignore: unknown property856 if (process.versions && process.versions.electron) {857 parseOptions.from = 'electron';858 }859 }860 this.rawArgs = argv.slice();861862 // make it a little easier for callers by supporting various argv conventions863 let userArgs;864 switch (parseOptions.from) {865 case undefined:866 case 'node':867 this._scriptPath = argv[1];868 userArgs = argv.slice(2);869 break;870 case 'electron':871 // @ts-ignore: unknown property872 if (process.defaultApp) {873 this._scriptPath = argv[1];874 userArgs = argv.slice(2);875 } else {876 userArgs = argv.slice(1);877 }878 break;879 case 'user':880 userArgs = argv.slice(0);881 break;882 default:883 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);884 }885Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 886–888why, one step back886 // Find default name for program from arguments.887 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);888 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 889–898why, one step back889890 return userArgs;891 }892893 /**894 * Parse `argv`, setting options and invoking commands when defined.895 *896 * The default expectation is that the arguments are from node and have the application as argv[0]897 * and the script being run in argv[1], with user parameters after that.898 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 899–902why, one step back899 * @example900 * program.parse(process.argv);901 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions902 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 903–914why, one step back903 *904 * @param {string[]} [argv] - optional, defaults to process.argv905 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron906 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'907 * @return {Command} `this` command for chaining908 */909910 parse(argv, parseOptions) {911 const userArgs = this._prepareUserArgs(argv, parseOptions);912 this._parseCommand([], userArgs);913914 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 915why, one step back915 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 916–924why, one step back916917 /**918 * Parse `argv`, setting options and invoking commands when defined.919 *920 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.921 *922 * The default expectation is that the arguments are from node and have the application as argv[0]923 * and the script being run in argv[1], with user parameters after that.924 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 925–928why, one step back925 * @example926 * await program.parseAsync(process.argv);927 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions928 * 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 929–940why, one step back929 *930 * @param {string[]} [argv]931 * @param {Object} [parseOptions]932 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'933 * @return {Promise}934 */935936 async parseAsync(argv, parseOptions) {937 const userArgs = this._prepareUserArgs(argv, parseOptions);938 await this._parseCommand([], userArgs);939940 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 941why, one step back941 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 942–953why, one step back942943 /**944 * Execute a sub-command executable.945 *946 * @api private947 */948949 _executeSubCommand(subcommand, args) {950 args = args.slice();951 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.952 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];953Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 954–957why, one step back954 function findFile(baseDir, baseName) {955 // Look for specified file956 const localBin = path.resolve(baseDir, baseName);957 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 958why, one step back958Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 959–960why, one step back959 // Stop looking if candidate already has an expected extension.960 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 961why, one step back961Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 962–966why, one step back962 // Try all the extensions.963 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));964 if (foundExt) return `${localBin}${foundExt}`;965966 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 967–968why, one step back967 }968Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 969–970why, one step back969 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.970 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 971why, one step back971 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 972–983why, one step back972973 // executableFile and executableDir might be full path, or just a name974 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;975 let executableDir = this._executableDir || '';976 if (this._scriptPath) {977 let resolvedScriptPath; // resolve possible symlink for installed npm binary978 try {979 resolvedScriptPath = fs.realpathSync(this._scriptPath);980 } catch (err) {981 resolvedScriptPath = this._scriptPath;982 }983 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 984–985why, one step back984 }985Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 986–994why, one step back986 // Look for a local file in preference to a command in PATH.987 if (executableDir) {988 let localFile = findFile(executableDir, executableFile);989990 // Legacy search using prefix of script name instead of command name991 if (!localFile && !subcommand._executableFile && this._scriptPath) {992 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));993 if (legacyName !== this._name) {994 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 995why, one step back995 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 996–997why, one step back996 }997 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 998–999why, one step back998 }999Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1000–1001why, one step back1000 launchWithNode = sourceExt.includes(path.extname(executableFile));1001Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1002–1004why, one step back1002 let proc;1003 if (process.platform !== 'win32') {1004 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1005why, one step back1005 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1006–1010why, one step back1006 // add executable arguments to spawn1007 args = incrementNodeInspectorPort(process.execArgv).concat(args);10081009 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1010 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1011why, one step back1011 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1012–1013why, one step back1012 }1013 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1014why, one step back1014 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1015–1019why, one step back1015 // add executable arguments to spawn1016 args = incrementNodeInspectorPort(process.execArgv).concat(args);1017 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1018 }1019Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1020–1028why, one step back1020 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1021 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1022 signals.forEach((signal) => {1023 // @ts-ignore1024 process.on(signal, () => {1025 if (proc.killed === false && proc.exitCode === null) {1026 proc.kill(signal);1027 }1028 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1029why, one step back1029 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1030why, one step back1030 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1031–1044why, one step back10311032 // By default terminate process when spawned process terminates.1033 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1034 const exitCallback = this._exitCallback;1035 if (!exitCallback) {1036 proc.on('close', process.exit.bind(process));1037 } else {1038 proc.on('close', () => {1039 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1040 });1041 }1042 proc.on('error', (err) => {1043 // @ts-ignore1044 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1045–1048why, one step back1045 const executableDirMessage = executableDir1046 ? `searched for local subcommand relative to directory '${executableDir}'`1047 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1048 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1049why, one step back1049 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' insteadMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1050–1051why, one step back1050 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1051 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1052–1054why, one step back1052 throw new Error(executableMissing);1053 // @ts-ignore1054 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1055why, one step back1055 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1056–1067why, one step back1056 }1057 if (!exitCallback) {1058 process.exit(1);1059 } else {1060 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1061 wrappedError.nestedError = err;1062 exitCallback(wrappedError);1063 }1064 });10651066 // Store the reference to the child process1067 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1068why, one step back1068 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1069–1077why, one step back10691070 /**1071 * @api private1072 */10731074 _dispatchSubcommand(commandName, operands, unknown) {1075 const subCommand = this._findCommand(commandName);1076 if (!subCommand) this.help({ error: true });1077feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1078–1087why, one step back1078 let hookResult;1079 hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand');1080 hookResult = this._chainOrCall(hookResult, () => {1081 if (subCommand._executableHandler) {1082 this._executeSubCommand(subCommand, operands.concat(unknown));1083 } else {1084 return subCommand._parseCommand(operands, unknown);1085 }1086 });1087 return hookResult;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1088why, one step back1088 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1089–1090why, one step back10891090 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1091–1106why, one step back1091 * Invoke help directly if possible, or dispatch if necessary.1092 * e.g. help foo1093 *1094 * @api private1095 */10961097 _dispatchHelpCommand(subcommandName) {1098 if (!subcommandName) {1099 this.help();1100 }1101 const subCommand = this._findCommand(subcommandName);1102 if (subCommand && !subCommand._executableHandler) {1103 subCommand.help();1104 }11051106 // Fallback to parsing the help flag to invoke the help.Fix help for commands with executable handler & only a short help flagWee Bitbefore adoptionc117172
lines 1107–1109why, one step back1107 return this._dispatchSubcommand(subcommandName, [], [1108 this._helpLongFlag || this._helpShortFlag1109 ]);Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1110–1112why, one step back1110 }11111112 /**Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1113why, one step back1113 * Check this.args against expected this._args.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1114–1117why, one step back1114 *1115 * @api private1116 */1117Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1118–1131why, one step back1118 _checkNumberOfArguments() {1119 // too few1120 this._args.forEach((arg, i) => {1121 if (arg.required && this.args[i] == null) {1122 this.missingArgument(arg.name());1123 }1124 });1125 // too many1126 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1127 return;1128 }1129 if (this.args.length > this._args.length) {1130 this._excessArguments(this.args);1131 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1132why, one step back1132 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1133–1140why, one step back11331134 /**1135 * Process this.args using this._args and save as this.processedArgs!1136 *1137 * @api private1138 */11391140 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1141–1149why, one step back1141 const myParseArg = (argument, value, previous) => {1142 // Extra processing for nice error message on parsing failure.1143 let parsedValue = value;1144 if (value !== null && argument.parseArg) {1145 try {1146 parsedValue = argument.parseArg(value, previous);1147 } catch (err) {1148 if (err.code === 'commander.invalidArgument') {1149 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 1150why, one step back1150 this.error(message, { exitCode: err.exitCode, code: err.code });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1151–1157why, one step back1151 }1152 throw err;1153 }1154 }1155 return parsedValue;1156 };1157Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1158–1160why, one step back1158 this._checkNumberOfArguments();11591160 const processedArgs = [];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1161–1180why, one step back1161 this._args.forEach((declaredArg, index) => {1162 let value = declaredArg.defaultValue;1163 if (declaredArg.variadic) {1164 // Collect together remaining arguments for passing together as an array.1165 if (index < this.args.length) {1166 value = this.args.slice(index);1167 if (declaredArg.parseArg) {1168 value = value.reduce((processed, v) => {1169 return myParseArg(declaredArg, v, processed);1170 }, declaredArg.defaultValue);1171 }1172 } else if (value === undefined) {1173 value = [];1174 }1175 } else if (index < this.args.length) {1176 value = this.args[index];1177 if (declaredArg.parseArg) {1178 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1179 }1180 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1181why, one step back1181 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1182why, one step back1182 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1183why, one step back1183 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1184–1191why, one step back1184 }11851186 /**1187 * Once we have a promise we chain, but call synchronously until then.1188 *1189 * @param {Promise|undefined} promise1190 * @param {Function} fn1191 * @return {Promise|undefined}Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1192why, one step back1192 * @api privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1193–1232why, one step back1193 */11941195 _chainOrCall(promise, fn) {1196 // thenable1197 if (promise && promise.then && typeof promise.then === 'function') {1198 // already have a promise, chain callback1199 return promise.then(() => fn());1200 }1201 // callback might return a promise1202 return fn();1203 }12041205 /**1206 *1207 * @param {Promise|undefined} promise1208 * @param {string} event1209 * @return {Promise|undefined}1210 * @api private1211 */12121213 _chainOrCallHooks(promise, event) {1214 let result = promise;1215 const hooks = [];1216 getCommandAndParents(this)1217 .reverse()1218 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1219 .forEach(hookedCommand => {1220 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1221 hooks.push({ hookedCommand, callback });1222 });1223 });1224 if (event === 'postAction') {1225 hooks.reverse();1226 }12271228 hooks.forEach((hookDetail) => {1229 result = this._chainOrCall(result, () => {1230 return hookDetail.callback(hookDetail.hookedCommand, this);1231 });1232 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1233–1253why, one step back1233 return result;1234 }12351236 /**1237 *1238 * @param {Promise|undefined} promise1239 * @param {Command} subCommand1240 * @param {string} event1241 * @return {Promise|undefined}1242 * @api private1243 */12441245 _chainOrCallSubCommandHook(promise, subCommand, event) {1246 let result = promise;1247 if (this._lifeCycleHooks[event] !== undefined) {1248 this._lifeCycleHooks[event].forEach((hook) => {1249 result = this._chainOrCall(result, () => {1250 return hook(this, subCommand);1251 });1252 });1253 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1254–1265why, one step back1254 return result;1255 }12561257 /**1258 * Process arguments in context of this command.1259 * Returns action result, in case it is a promise.1260 *1261 * @api private1262 */12631264 _parseCommand(operands, unknown) {1265 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1266why, one step back1266 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1267why, one step back1267 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1268–1275why, one step back1268 operands = operands.concat(parsed.operands);1269 unknown = parsed.unknown;1270 this.args = operands.concat(unknown);12711272 if (operands && this._findCommand(operands[0])) {1273 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1274 }1275 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1276why, one step back1276 return this._dispatchHelpCommand(operands[1]);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1277–1288why, one step back1277 }1278 if (this._defaultCommandName) {1279 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1280 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1281 }1282 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1283 // probably missing subcommand and no handler, user needs help (and exit)1284 this.help({ error: true });1285 }12861287 outputHelpIfRequested(this, parsed.unknown);1288 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1289why, one step back1289 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1290–1300why, one step back12901291 // We do not always call this check to avoid masking a "better" error, like unknown command.1292 const checkForUnknownOptions = () => {1293 if (parsed.unknown.length > 0) {1294 this.unknownOption(parsed.unknown[0]);1295 }1296 };12971298 const commandEvent = `command:${this.name()}`;1299 if (this._actionHandler) {1300 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1301why, one step back1301 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1302–1304why, one step back13021303 let actionResult;1304 actionResult = this._chainOrCallHooks(actionResult, 'preAction');Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1305why, one step back1305 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1306–1310why, one step back1306 if (this.parent) {1307 actionResult = this._chainOrCall(actionResult, () => {1308 this.parent.emit(commandEvent, operands, unknown); // legacy1309 });1310 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1311–1315why, one step back1311 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1312 return actionResult;1313 }1314 if (this.parent && this.parent.listenerCount(commandEvent)) {1315 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1316why, one step back1316 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1317–1328why, one step back1317 this.parent.emit(commandEvent, operands, unknown); // legacy1318 } else if (operands.length) {1319 if (this._findCommand('*')) { // legacy default command1320 return this._dispatchSubcommand('*', operands, unknown);1321 }1322 if (this.listenerCount('command:*')) {1323 // skip option check, emit event for possible misspelling suggestion1324 this.emit('command:*', operands, unknown);1325 } else if (this.commands.length) {1326 this.unknownCommand();1327 } else {1328 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1329why, one step back1329 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1330–1331why, one step back1330 }1331 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1332why, one step back1332 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1333–1336why, one step back1333 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1334 this.help({ error: true });1335 } else {1336 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1337why, one step back1337 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1338–1339why, one step back1338 // fall through for caller to handle after calling .parse()1339 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1340why, one step back1340 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1341–1349why, one step back13411342 /**1343 * Find matching command.1344 *1345 * @api private1346 */1347 _findCommand(name) {1348 if (!name) return undefined;1349 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1350why, one step back1350 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1351–1361why, one step back13511352 /**1353 * Return an option matching `arg` if any.1354 *1355 * @param {string} arg1356 * @return {Option}1357 * @api private1358 */13591360 _findOption(arg) {1361 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1362why, one step back1362 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1363–1365why, one step back13631364 /**1365 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1366why, one step back1366 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1367–1379why, one step back1367 *1368 * @api private1369 */13701371 _checkForMissingMandatoryOptions() {1372 // Walk up hierarchy so can call in subcommand after checking for displaying help.1373 for (let cmd = this; cmd; cmd = cmd.parent) {1374 cmd.options.forEach((anOption) => {1375 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1376 cmd.missingMandatoryOptionValue(anOption);1377 }1378 });1379 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1380why, one step back1380 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1381–1382why, one step back13811382 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1383why, one step back1383 * 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 1384–1386why, one step back1384 *1385 * @api private1386 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1387why, one step back1387 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1388–1409why, one step back1388 const definedNonDefaultOptions = this.options.filter(1389 (option) => {1390 const optionKey = option.attributeName();1391 if (this.getOptionValue(optionKey) === undefined) {1392 return false;1393 }1394 return this.getOptionValueSource(optionKey) !== 'default';1395 }1396 );13971398 const optionsWithConflicting = definedNonDefaultOptions.filter(1399 (option) => option.conflictsWith.length > 01400 );14011402 optionsWithConflicting.forEach((option) => {1403 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1404 option.conflictsWith.includes(defined.attributeName())1405 );1406 if (conflictingAndDefined) {1407 this._conflictingOption(option, conflictingAndDefined);1408 }1409 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1410–1422why, one step back1410 }14111412 /**1413 * Display an error message if conflicting options are used together.1414 * Called after checking for help flags in leaf subcommand.1415 *1416 * @api private1417 */1418 _checkForConflictingOptions() {1419 // Walk up hierarchy so can call in subcommand after checking for displaying help.1420 for (let cmd = this; cmd; cmd = cmd.parent) {1421 cmd._checkForConflictingLocalOptions();1422 }feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1423–1425why, one step back1423 }14241425 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1426–1430why, one step back1426 * Parse options from `argv` removing known options,1427 * and return argv split into operands and unknown arguments.1428 *1429 * Examples:1430 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1431–1435why, one step back1431 * argv => operands, unknown1432 * --known kkk op => [op], []1433 * op --known kkk => [op], []1434 * sub --unknown uuu op => [sub], [--unknown uuu op]1435 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1436–1554why, one step back1436 *1437 * @param {String[]} argv1438 * @return {{operands: String[], unknown: String[]}}1439 */14401441 parseOptions(argv) {1442 const operands = []; // operands, not options or values1443 const unknown = []; // first unknown option and remaining unknown args1444 let dest = operands;1445 const args = argv.slice();14461447 function maybeOption(arg) {1448 return arg.length > 1 && arg[0] === '-';1449 }14501451 // parse options1452 let activeVariadicOption = null;1453 while (args.length) {1454 const arg = args.shift();14551456 // literal1457 if (arg === '--') {1458 if (dest === unknown) dest.push(arg);1459 dest.push(...args);1460 break;1461 }14621463 if (activeVariadicOption && !maybeOption(arg)) {1464 this.emit(`option:${activeVariadicOption.name()}`, arg);1465 continue;1466 }1467 activeVariadicOption = null;14681469 if (maybeOption(arg)) {1470 const option = this._findOption(arg);1471 // recognised option, call listener to assign value with possible custom processing1472 if (option) {1473 if (option.required) {1474 const value = args.shift();1475 if (value === undefined) this.optionMissingArgument(option);1476 this.emit(`option:${option.name()}`, value);1477 } else if (option.optional) {1478 let value = null;1479 // historical behaviour is optional value is following arg unless an option1480 if (args.length > 0 && !maybeOption(args[0])) {1481 value = args.shift();1482 }1483 this.emit(`option:${option.name()}`, value);1484 } else { // boolean flag1485 this.emit(`option:${option.name()}`);1486 }1487 activeVariadicOption = option.variadic ? option : null;1488 continue;1489 }1490 }14911492 // Look for combo options following single dash, eat first one if known.1493 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1494 const option = this._findOption(`-${arg[1]}`);1495 if (option) {1496 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1497 // option with value following in same argument1498 this.emit(`option:${option.name()}`, arg.slice(2));1499 } else {1500 // boolean option, emit and put back remainder of arg for further processing1501 this.emit(`option:${option.name()}`);1502 args.unshift(`-${arg.slice(2)}`);1503 }1504 continue;1505 }1506 }15071508 // Look for known long flag with value, like --foo=bar1509 if (/^--[^=]+=/.test(arg)) {1510 const index = arg.indexOf('=');1511 const option = this._findOption(arg.slice(0, index));1512 if (option && (option.required || option.optional)) {1513 this.emit(`option:${option.name()}`, arg.slice(index + 1));1514 continue;1515 }1516 }15171518 // Not a recognised option by this command.1519 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15201521 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1522 if (maybeOption(arg)) {1523 dest = unknown;1524 }15251526 // If using positionalOptions, stop processing our options at subcommand.1527 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1528 if (this._findCommand(arg)) {1529 operands.push(arg);1530 if (args.length > 0) unknown.push(...args);1531 break;1532 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1533 operands.push(arg);1534 if (args.length > 0) operands.push(...args);1535 break;1536 } else if (this._defaultCommandName) {1537 unknown.push(arg);1538 if (args.length > 0) unknown.push(...args);1539 break;1540 }1541 }15421543 // If using passThroughOptions, stop processing options at first command-argument.1544 if (this._passThroughOptions) {1545 dest.push(arg);1546 if (args.length > 0) dest.push(...args);1547 break;1548 }15491550 // add arg1551 dest.push(arg);1552 }15531554 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1555why, one step back1555 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1556–1557why, one step back15561557 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1558why, one step back1558 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1559–1575why, one step back1559 *1560 * @return {Object}1561 */1562 opts() {1563 if (this._storeOptionsAsProperties) {1564 // Preserve original behaviour so backwards compatible when still using properties1565 const result = {};1566 const len = this.options.length;15671568 for (let i = 0; i < len; i++) {1569 const key = this.options[i].attributeName();1570 result[key] = key === this._versionOptionName ? this._version : this[key];1571 }1572 return result;1573 }15741575 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1576why, one step back1576 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1577–1578why, one step back15771578 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1579why, one step back1579 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1580why, one step back1580 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1581why, one step back1581 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1582why, one step back1582 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1583–1600why, one step back1583 optsWithGlobals() {1584 // globals overwrite locals1585 return getCommandAndParents(this).reduce(1586 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1587 {}1588 );1589 }15901591 /**1592 * Display error message and exit (or call exitOverride).1593 *1594 * @param {string} message1595 * @param {Object} [errorOptions]1596 * @param {string} [errorOptions.code] - an id string representing the error1597 * @param {number} [errorOptions.exitCode] - used with process.exit1598 */1599 error(message, errorOptions) {1600 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1601why, one step back1601 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1602–1607why, one step back1602 if (typeof this._showHelpAfterError === 'string') {1603 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1604 } else if (this._showHelpAfterError) {1605 this._outputConfiguration.writeErr('\n');1606 this.outputHelp({ error: true });1607 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1608–1612why, one step back16081609 // exit handling1610 const config = errorOptions || {};1611 const exitCode = config.exitCode || 1;1612 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1613why, one step back1613 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1614–1625why, one step back1614 }16151616 /**1617 * Apply any option related environment variables, if option does1618 * not have a value from cli or client code.1619 *1620 * @api private1621 */1622 _parseOptionsEnv() {1623 this.options.forEach((option) => {1624 if (option.envVar && option.envVar in process.env) {1625 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1626–1627why, one step back1626 // Priority check. Do not overwrite cli or options from unknown source (client-code).1627 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 1628–1637why, one step back1628 if (option.required || option.optional) { // option can take a value1629 // keep very simple, optional always takes value1630 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1631 } else { // boolean1632 // keep very simple, only care that envVar defined and not the value1633 this.emit(`optionEnv:${option.name()}`);1634 }1635 }1636 }1637 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1638–1660why, one step back1638 }16391640 /**1641 * Apply any implied option values, if option is undefined or default value.1642 *1643 * @api private1644 */1645 _parseOptionsImplied() {1646 const dualHelper = new DualOptions(this.options);1647 const hasCustomOptionValue = (optionKey) => {1648 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1649 };1650 this.options1651 .filter(option => (option.implied !== undefined) &&1652 hasCustomOptionValue(option.attributeName()) &&1653 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1654 .forEach((option) => {1655 Object.keys(option.implied)1656 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1657 .forEach(impliedKey => {1658 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1659 });1660 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1661–1671why, one step back1661 }16621663 /**1664 * Argument `name` is missing.1665 *1666 * @param {string} name1667 * @api private1668 */16691670 missingArgument(name) {1671 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1672–1673why, one step back1672 this.error(message, { code: 'commander.missingArgument' });1673 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1674–1683why, one step back16741675 /**1676 * `Option` is missing an argument.1677 *1678 * @param {Option} option1679 * @api private1680 */16811682 optionMissingArgument(option) {1683 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1684–1685why, one step back1684 this.error(message, { code: 'commander.optionMissingArgument' });1685 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1686–1695why, one step back16861687 /**1688 * `Option` does not have a value, and is a mandatory option.1689 *1690 * @param {Option} option1691 * @api private1692 */16931694 missingMandatoryOptionValue(option) {1695 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1696why, one step back1696 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1697–1734why, one step back1697 }16981699 /**1700 * `Option` conflicts with another option.1701 *1702 * @param {Option} option1703 * @param {Option} conflictingOption1704 * @api private1705 */1706 _conflictingOption(option, conflictingOption) {1707 // The calling code does not know whether a negated option is the source of the1708 // value, so do some work to take an educated guess.1709 const findBestOptionFromValue = (option) => {1710 const optionKey = option.attributeName();1711 const optionValue = this.getOptionValue(optionKey);1712 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1713 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1714 if (negativeOption && (1715 (negativeOption.presetArg === undefined && optionValue === false) ||1716 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1717 )) {1718 return negativeOption;1719 }1720 return positiveOption || option;1721 };17221723 const getErrorMessage = (option) => {1724 const bestOption = findBestOptionFromValue(option);1725 const optionKey = bestOption.attributeName();1726 const source = this.getOptionValueSource(optionKey);1727 if (source === 'env') {1728 return `environment variable '${bestOption.envVar}'`;1729 }1730 return `option '${bestOption.flags}'`;1731 };17321733 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1734 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1735why, one step back1735 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1736–1745why, one step back17361737 /**1738 * Unknown option `flag`.1739 *1740 * @param {string} flag1741 * @api private1742 */17431744 unknownOption(flag) {1745 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1746–1762why, one step back1746 let suggestion = '';17471748 if (flag.startsWith('--') && this._showSuggestionAfterError) {1749 // Looping to pick up the global options too1750 let candidateFlags = [];1751 let command = this;1752 do {1753 const moreFlags = command.createHelp().visibleOptions(command)1754 .filter(option => option.long)1755 .map(option => option.long);1756 candidateFlags = candidateFlags.concat(moreFlags);1757 command = command.parent;1758 } while (command && !command._enablePositionalOptions);1759 suggestion = suggestSimilar(flag, candidateFlags);1760 }17611762 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1763–1764why, one step back1763 this.error(message, { code: 'commander.unknownOption' });1764 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1765–1779why, one step back17651766 /**1767 * Excess arguments, more than expected.1768 *1769 * @param {string[]} receivedArgs1770 * @api private1771 */17721773 _excessArguments(receivedArgs) {1774 if (this._allowExcessArguments) return;17751776 const expected = this._args.length;1777 const s = (expected === 1) ? '' : 's';1778 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1779 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 1780–1781why, one step back1780 this.error(message, { code: 'commander.excessArguments' });1781 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1782–1789why, one step back17821783 /**1784 * Unknown command.1785 *1786 * @api private1787 */17881789 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1790–1803why, one step back1790 const unknownName = this.args[0];1791 let suggestion = '';17921793 if (this._showSuggestionAfterError) {1794 const candidateNames = [];1795 this.createHelp().visibleCommands(this).forEach((command) => {1796 candidateNames.push(command.name());1797 // just visible alias1798 if (command.alias()) candidateNames.push(command.alias());1799 });1800 suggestion = suggestSimilar(unknownName, candidateNames);1801 }18021803 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1804–1805why, one step back1804 this.error(message, { code: 'commander.unknownCommand' });1805 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1806–1814why, one step back18061807 /**1808 * Set the program version to `str`.1809 *1810 * This method auto-registers the "-V, --version" flag1811 * which will print the version number when passed.1812 *1813 * You can optionally supply the flags and description to override the defaults.1814 *Revert "Fix version() parameter type"Wee Bitbefore adoptionf3431d1
line 1815why, one step back1815 * @param {string} strRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1816–1833why, one step back1816 * @param {string} [flags]1817 * @param {string} [description]1818 * @return {this | string} `this` command for chaining, or version string if no arguments1819 */18201821 version(str, flags, description) {1822 if (str === undefined) return this._version;1823 this._version = str;1824 flags = flags || '-V, --version';1825 description = description || 'output the version number';1826 const versionOption = this.createOption(flags, description);1827 this._versionOptionName = versionOption.attributeName();1828 this.options.push(versionOption);1829 this.on('option:' + versionOption.name(), () => {1830 this._outputConfiguration.writeOut(`${str}\n`);1831 this._exit(0, 'commander.version', str);1832 });1833 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1834why, one step back1834 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1835–1836why, one step back18351836 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1837why, one step back1837 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1838–1848why, one step back1838 *1839 * @param {string} [str]1840 * @param {Object} [argsDescription]1841 * @return {string|Command}1842 */1843 description(str, argsDescription) {1844 if (str === undefined && argsDescription === undefined) return this._description;1845 this._description = str;1846 if (argsDescription) {1847 this._argsDescription = argsDescription;1848 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1849–1860why, one step back1849 return this;1850 }18511852 /**1853 * Set the summary. Used when listed as subcommand of parent.1854 *1855 * @param {string} [str]1856 * @return {string|Command}1857 */1858 summary(str) {1859 if (str === undefined) return this._summary;1860 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1861why, one step back1861 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1862why, one step back1862 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1863–1875why, one step back18631864 /**1865 * Set an alias for the command.1866 *1867 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1868 *1869 * @param {string} [alias]1870 * @return {string|Command}1871 */18721873 alias(alias) {1874 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1875Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1876why, one step back1876 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1877–1886why, one step back1877 let command = this;1878 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1879 // assume adding alias for last added executable subcommand, rather than this1880 command = this.commands[this.commands.length - 1];1881 }18821883 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18841885 command._aliases.push(alias);1886 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1887why, one step back1887 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1888–1903why, one step back18881889 /**1890 * Set aliases for the command.1891 *1892 * Only the first alias is shown in the auto-generated help.1893 *1894 * @param {string[]} [aliases]1895 * @return {string[]|Command}1896 */18971898 aliases(aliases) {1899 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1900 if (aliases === undefined) return this._aliases;19011902 aliases.forEach((alias) => this.alias(alias));1903 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1904why, one step back1904 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1905–1928why, one step back19051906 /**1907 * Set / get the command usage `str`.1908 *1909 * @param {string} [str]1910 * @return {String|Command}1911 */19121913 usage(str) {1914 if (str === undefined) {1915 if (this._usage) return this._usage;19161917 const args = this._args.map((arg) => {1918 return humanReadableArgName(arg);1919 });1920 return [].concat(1921 (this.options.length || this._hasHelpOption ? '[options]' : []),1922 (this.commands.length ? '[command]' : []),1923 (this._args.length ? args : [])1924 ).join(' ');1925 }19261927 this._usage = str;1928 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1929why, one step back1929 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1930–1931why, one step back19301931 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1932why, one step back1932 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1933–1941why, one step back1933 *1934 * @param {string} [str]1935 * @return {string|Command}1936 */19371938 name(str) {1939 if (str === undefined) return this._name;1940 this._name = str;1941 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1942why, one step back1942 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1943–1944why, one step back19431944 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1945–1971why, one step back1945 * Set the name of the command from script filename, such as process.argv[1],1946 * or require.main.filename, or __filename.1947 *1948 * (Used internally and public although not documented in README.)1949 *1950 * @example1951 * program.nameFromFilename(require.main.filename);1952 *1953 * @param {string} filename1954 * @return {Command}1955 */19561957 nameFromFilename(filename) {1958 this._name = path.basename(filename, path.extname(filename));19591960 return this;1961 }19621963 /**1964 * Get or set the directory for searching for executable subcommands of this command.1965 *1966 * @example1967 * program.executableDir(__dirname);1968 * // or1969 * program.executableDir('subcommands');1970 *1971 * @param {string} [path]Fix executableDir() return typeWee Bitbefore adoption68a4276
line 1972why, one step back1972 * @return {string|null|Command}Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1973–1981why, one step back1973 */19741975 executableDir(path) {1976 if (path === undefined) return this._executableDir;1977 this._executableDir = path;1978 return this;1979 }19801981 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1982–1993why, one step back1982 * Return program help documentation.1983 *1984 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1985 * @return {string}1986 */19871988 helpInformation(contextOptions) {1989 const helper = this.createHelp();1990 if (helper.helpWidth === undefined) {1991 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1992 }1993 return helper.formatHelp(this, helper);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1994why, one step back1994 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1995–2029why, one step back19951996 /**1997 * @api private1998 */19992000 _getHelpContext(contextOptions) {The first 2,000 of 2,203 lines.