command.js
This file
Path
lib/command.js
2,135 lines · 67.2 KiB · JavaScript
Last changed by
Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
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 setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 40why, one step back40 this._optionValueSources = {}; // default < config < env < cliRefactor 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–336why, one step back327 *328 * @param {string} names329 * @return {Command} `this` command for chaining330 */331332 arguments(names) {333 names.split(/ +/).forEach((detail) => {334 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–434why, 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) {402 const allowedValues = ['preAction', 'postAction'];403 if (!allowedValues.includes(event)) {404 throw new Error(`Unexpected value for event passed to hook : '${event}'.405Expecting one of '${allowedValues.join("', '")}'`);406 }407 if (this._lifeCycleHooks[event]) {408 this._lifeCycleHooks[event].push(listener);409 } else {410 this._lifeCycleHooks[event] = [listener];411 }412 return this;413 }414415 /**416 * Register callback to use as replacement for calling process.exit.417 *418 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing419 * @return {Command} `this` command for chaining420 */421422 exitOverride(fn) {423 if (fn) {424 this._exitCallback = fn;425 } else {426 this._exitCallback = (err) => {427 if (err.code !== 'commander.executeSubCommandAsync') {428 throw err;429 } else {430 // Async callback from spawn events, not useful to throw.431 }432 };433 }434 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 435why, one step 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–757why, 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 this._storeOptionsAsProperties = !!storeAsProperties;754 if (this.options.length) {755 throw new Error('call .storeOptionsAsProperties() before adding options');756 }757 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 758why, one step back758 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 759–771why, one step back759760 /**761 * Retrieve option value.762 *763 * @param {string} key764 * @return {Object} value765 */766767 getOptionValue(key) {768 if (this._storeOptionsAsProperties) {769 return this[key];770 }771 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 772why, one step back772 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 773–788why, one step back773774 /**775 * Store option value.776 *777 * @param {string} key778 * @param {Object} value779 * @return {Command} `this` command for chaining780 */781782 setOptionValue(key, value) {783 if (this._storeOptionsAsProperties) {784 this[key] = value;785 } else {786 this._optionValues[key] = value;787 }788 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 789why, one step back789 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 790–791why, one step back790791 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 792–800why, one step back792 * Store option value and where the value came from.793 *794 * @param {string} key795 * @param {Object} value796 * @param {string} source - expected values are default/config/env/cli797 * @return {Command} `this` command for chaining798 */799800 setOptionValueWithSource(key, value, source) {Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 801–802why, one step back801 this.setOptionValue(key, value);802 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 803why, one step back803 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 804–806why, one step back804 }805806 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 807–815why, one step back807 * Get source of option value.808 * Expected values are default | config | env | cli809 *810 * @param {string} key811 * @return {string}812 */813814 getOptionValueSource(key) {815 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 816why, one step back816 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 817–818why, one step back817818 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 819–820why, one step back819 * Get user arguments from implied or explicit arguments.820 * 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 821–864why, one step back821 *822 * @api private823 */824825 _prepareUserArgs(argv, parseOptions) {826 if (argv !== undefined && !Array.isArray(argv)) {827 throw new Error('first parameter to parse must be array or undefined');828 }829 parseOptions = parseOptions || {};830831 // Default to using process.argv832 if (argv === undefined) {833 argv = process.argv;834 // @ts-ignore: unknown property835 if (process.versions && process.versions.electron) {836 parseOptions.from = 'electron';837 }838 }839 this.rawArgs = argv.slice();840841 // make it a little easier for callers by supporting various argv conventions842 let userArgs;843 switch (parseOptions.from) {844 case undefined:845 case 'node':846 this._scriptPath = argv[1];847 userArgs = argv.slice(2);848 break;849 case 'electron':850 // @ts-ignore: unknown property851 if (process.defaultApp) {852 this._scriptPath = argv[1];853 userArgs = argv.slice(2);854 } else {855 userArgs = argv.slice(1);856 }857 break;858 case 'user':859 userArgs = argv.slice(0);860 break;861 default:862 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);863 }864Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 865–867why, one step back865 // Find default name for program from arguments.866 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);867 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 868–877why, one step back868869 return userArgs;870 }871872 /**873 * Parse `argv`, setting options and invoking commands when defined.874 *875 * The default expectation is that the arguments are from node and have the application as argv[0]876 * and the script being run in argv[1], with user parameters after that.877 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 878–881why, one step back878 * @example879 * program.parse(process.argv);880 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions881 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 882–893why, one step back882 *883 * @param {string[]} [argv] - optional, defaults to process.argv884 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron885 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'886 * @return {Command} `this` command for chaining887 */888889 parse(argv, parseOptions) {890 const userArgs = this._prepareUserArgs(argv, parseOptions);891 this._parseCommand([], userArgs);892893 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 894why, one step back894 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 895–903why, one step back895896 /**897 * Parse `argv`, setting options and invoking commands when defined.898 *899 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.900 *901 * The default expectation is that the arguments are from node and have the application as argv[0]902 * and the script being run in argv[1], with user parameters after that.903 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 904–907why, one step back904 * @example905 * await program.parseAsync(process.argv);906 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions907 * 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 908–919why, one step back908 *909 * @param {string[]} [argv]910 * @param {Object} [parseOptions]911 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'912 * @return {Promise}913 */914915 async parseAsync(argv, parseOptions) {916 const userArgs = this._prepareUserArgs(argv, parseOptions);917 await this._parseCommand([], userArgs);918919 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 920why, one step back920 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 921–932why, one step back921922 /**923 * Execute a sub-command executable.924 *925 * @api private926 */927928 _executeSubCommand(subcommand, args) {929 args = args.slice();930 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.931 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];932Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 933–936why, one step back933 function findFile(baseDir, baseName) {934 // Look for specified file935 const localBin = path.resolve(baseDir, baseName);936 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 937why, one step back937Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 938–939why, one step back938 // Stop looking if candidate already has an expected extension.939 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 940why, one step back940Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 941–945why, one step back941 // Try all the extensions.942 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));943 if (foundExt) return `${localBin}${foundExt}`;944945 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 946–947why, one step back946 }947Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 948–949why, one step back948 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.949 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 950why, one step back950 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 951–962why, one step back951952 // executableFile and executableDir might be full path, or just a name953 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;954 let executableDir = this._executableDir || '';955 if (this._scriptPath) {956 let resolvedScriptPath; // resolve possible symlink for installed npm binary957 try {958 resolvedScriptPath = fs.realpathSync(this._scriptPath);959 } catch (err) {960 resolvedScriptPath = this._scriptPath;961 }962 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 963–964why, one step back963 }964Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 965–973why, one step back965 // Look for a local file in preference to a command in PATH.966 if (executableDir) {967 let localFile = findFile(executableDir, executableFile);968969 // Legacy search using prefix of script name instead of command name970 if (!localFile && !subcommand._executableFile && this._scriptPath) {971 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));972 if (legacyName !== this._name) {973 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 974why, one step back974 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 975–976why, one step back975 }976 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 977–978why, one step back977 }978Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 979–980why, one step back979 launchWithNode = sourceExt.includes(path.extname(executableFile));980Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 981–983why, one step back981 let proc;982 if (process.platform !== 'win32') {983 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 984why, one step back984 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 985–989why, one step back985 // add executable arguments to spawn986 args = incrementNodeInspectorPort(process.execArgv).concat(args);987988 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });989 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 990why, one step back990 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 991–992why, one step back991 }992 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 993why, one step back993 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 994–998why, one step back994 // add executable arguments to spawn995 args = incrementNodeInspectorPort(process.execArgv).concat(args);996 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });997 }998Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 999–1007why, one step back999 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1000 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1001 signals.forEach((signal) => {1002 // @ts-ignore1003 process.on(signal, () => {1004 if (proc.killed === false && proc.exitCode === null) {1005 proc.kill(signal);1006 }1007 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1008why, one step back1008 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1009why, one step back1009 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1010–1023why, one step back10101011 // By default terminate process when spawned process terminates.1012 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1013 const exitCallback = this._exitCallback;1014 if (!exitCallback) {1015 proc.on('close', process.exit.bind(process));1016 } else {1017 proc.on('close', () => {1018 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1019 });1020 }1021 proc.on('error', (err) => {1022 // @ts-ignore1023 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1024–1027why, one step back1024 const executableDirMessage = executableDir1025 ? `searched for local subcommand relative to directory '${executableDir}'`1026 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1027 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1028why, one step back1028 - 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 1029–1030why, one step back1029 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1030 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1031–1033why, one step back1031 throw new Error(executableMissing);1032 // @ts-ignore1033 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1034why, one step back1034 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1035–1046why, one step back1035 }1036 if (!exitCallback) {1037 process.exit(1);1038 } else {1039 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1040 wrappedError.nestedError = err;1041 exitCallback(wrappedError);1042 }1043 });10441045 // Store the reference to the child process1046 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1047why, one step back1047 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1048–1061why, one step back10481049 /**1050 * @api private1051 */10521053 _dispatchSubcommand(commandName, operands, unknown) {1054 const subCommand = this._findCommand(commandName);1055 if (!subCommand) this.help({ error: true });10561057 if (subCommand._executableHandler) {1058 this._executeSubCommand(subCommand, operands.concat(unknown));1059 } else {1060 return subCommand._parseCommand(operands, unknown);1061 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1062why, one step back1062 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1063–1064why, one step back10631064 /**Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1065why, one step back1065 * Check this.args against expected this._args.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1066–1069why, one step back1066 *1067 * @api private1068 */1069Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1070–1083why, one step back1070 _checkNumberOfArguments() {1071 // too few1072 this._args.forEach((arg, i) => {1073 if (arg.required && this.args[i] == null) {1074 this.missingArgument(arg.name());1075 }1076 });1077 // too many1078 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1079 return;1080 }1081 if (this.args.length > this._args.length) {1082 this._excessArguments(this.args);1083 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1084why, one step back1084 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1085–1092why, one step back10851086 /**1087 * Process this.args using this._args and save as this.processedArgs!1088 *1089 * @api private1090 */10911092 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1093–1101why, one step back1093 const myParseArg = (argument, value, previous) => {1094 // Extra processing for nice error message on parsing failure.1095 let parsedValue = value;1096 if (value !== null && argument.parseArg) {1097 try {1098 parsedValue = argument.parseArg(value, previous);1099 } catch (err) {1100 if (err.code === 'commander.invalidArgument') {1101 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 1102why, one step back1102 this.error(message, { exitCode: err.exitCode, code: err.code });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1103–1109why, one step back1103 }1104 throw err;1105 }1106 }1107 return parsedValue;1108 };1109Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1110–1112why, one step back1110 this._checkNumberOfArguments();11111112 const processedArgs = [];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1113–1132why, one step back1113 this._args.forEach((declaredArg, index) => {1114 let value = declaredArg.defaultValue;1115 if (declaredArg.variadic) {1116 // Collect together remaining arguments for passing together as an array.1117 if (index < this.args.length) {1118 value = this.args.slice(index);1119 if (declaredArg.parseArg) {1120 value = value.reduce((processed, v) => {1121 return myParseArg(declaredArg, v, processed);1122 }, declaredArg.defaultValue);1123 }1124 } else if (value === undefined) {1125 value = [];1126 }1127 } else if (index < this.args.length) {1128 value = this.args[index];1129 if (declaredArg.parseArg) {1130 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1131 }1132 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1133why, one step back1133 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1134why, one step back1134 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1135why, one step back1135 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1136–1143why, one step back1136 }11371138 /**1139 * Once we have a promise we chain, but call synchronously until then.1140 *1141 * @param {Promise|undefined} promise1142 * @param {Function} fn1143 * @return {Promise|undefined}Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1144why, one step back1144 * @api privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1145–1196why, one step back1145 */11461147 _chainOrCall(promise, fn) {1148 // thenable1149 if (promise && promise.then && typeof promise.then === 'function') {1150 // already have a promise, chain callback1151 return promise.then(() => fn());1152 }1153 // callback might return a promise1154 return fn();1155 }11561157 /**1158 *1159 * @param {Promise|undefined} promise1160 * @param {string} event1161 * @return {Promise|undefined}1162 * @api private1163 */11641165 _chainOrCallHooks(promise, event) {1166 let result = promise;1167 const hooks = [];1168 getCommandAndParents(this)1169 .reverse()1170 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1171 .forEach(hookedCommand => {1172 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1173 hooks.push({ hookedCommand, callback });1174 });1175 });1176 if (event === 'postAction') {1177 hooks.reverse();1178 }11791180 hooks.forEach((hookDetail) => {1181 result = this._chainOrCall(result, () => {1182 return hookDetail.callback(hookDetail.hookedCommand, this);1183 });1184 });1185 return result;1186 }11871188 /**1189 * Process arguments in context of this command.1190 * Returns action result, in case it is a promise.1191 *1192 * @api private1193 */11941195 _parseCommand(operands, unknown) {1196 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1197why, one step back1197 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1198why, one step back1198 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1199–1222why, one step back1199 operands = operands.concat(parsed.operands);1200 unknown = parsed.unknown;1201 this.args = operands.concat(unknown);12021203 if (operands && this._findCommand(operands[0])) {1204 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1205 }1206 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1207 if (operands.length === 1) {1208 this.help();1209 }1210 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1211 }1212 if (this._defaultCommandName) {1213 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1214 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1215 }1216 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1217 // probably missing subcommand and no handler, user needs help (and exit)1218 this.help({ error: true });1219 }12201221 outputHelpIfRequested(this, parsed.unknown);1222 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1223why, one step back1223 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1224–1234why, one step back12241225 // We do not always call this check to avoid masking a "better" error, like unknown command.1226 const checkForUnknownOptions = () => {1227 if (parsed.unknown.length > 0) {1228 this.unknownOption(parsed.unknown[0]);1229 }1230 };12311232 const commandEvent = `command:${this.name()}`;1233 if (this._actionHandler) {1234 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1235why, one step back1235 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1236–1238why, one step back12361237 let actionResult;1238 actionResult = this._chainOrCallHooks(actionResult, 'preAction');Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1239why, one step back1239 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1240–1244why, one step back1240 if (this.parent) {1241 actionResult = this._chainOrCall(actionResult, () => {1242 this.parent.emit(commandEvent, operands, unknown); // legacy1243 });1244 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1245–1249why, one step back1245 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1246 return actionResult;1247 }1248 if (this.parent && this.parent.listenerCount(commandEvent)) {1249 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1250why, one step back1250 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1251–1262why, one step back1251 this.parent.emit(commandEvent, operands, unknown); // legacy1252 } else if (operands.length) {1253 if (this._findCommand('*')) { // legacy default command1254 return this._dispatchSubcommand('*', operands, unknown);1255 }1256 if (this.listenerCount('command:*')) {1257 // skip option check, emit event for possible misspelling suggestion1258 this.emit('command:*', operands, unknown);1259 } else if (this.commands.length) {1260 this.unknownCommand();1261 } else {1262 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1263why, one step back1263 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1264–1265why, one step back1264 }1265 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1266why, one step back1266 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1267–1270why, one step back1267 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1268 this.help({ error: true });1269 } else {1270 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1271why, one step back1271 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1272–1273why, one step back1272 // fall through for caller to handle after calling .parse()1273 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1274why, one step back1274 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1275–1283why, one step back12751276 /**1277 * Find matching command.1278 *1279 * @api private1280 */1281 _findCommand(name) {1282 if (!name) return undefined;1283 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1284why, one step back1284 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1285–1295why, one step back12851286 /**1287 * Return an option matching `arg` if any.1288 *1289 * @param {string} arg1290 * @return {Option}1291 * @api private1292 */12931294 _findOption(arg) {1295 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1296why, one step back1296 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1297–1299why, one step back12971298 /**1299 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1300why, one step back1300 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1301–1313why, one step back1301 *1302 * @api private1303 */13041305 _checkForMissingMandatoryOptions() {1306 // Walk up hierarchy so can call in subcommand after checking for displaying help.1307 for (let cmd = this; cmd; cmd = cmd.parent) {1308 cmd.options.forEach((anOption) => {1309 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1310 cmd.missingMandatoryOptionValue(anOption);1311 }1312 });1313 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1314why, one step back1314 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1315–1316why, one step back13151316 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1317why, one step back1317 * 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 1318–1320why, one step back1318 *1319 * @api private1320 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1321why, one step back1321 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1322–1343why, one step back1322 const definedNonDefaultOptions = this.options.filter(1323 (option) => {1324 const optionKey = option.attributeName();1325 if (this.getOptionValue(optionKey) === undefined) {1326 return false;1327 }1328 return this.getOptionValueSource(optionKey) !== 'default';1329 }1330 );13311332 const optionsWithConflicting = definedNonDefaultOptions.filter(1333 (option) => option.conflictsWith.length > 01334 );13351336 optionsWithConflicting.forEach((option) => {1337 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1338 option.conflictsWith.includes(defined.attributeName())1339 );1340 if (conflictingAndDefined) {1341 this._conflictingOption(option, conflictingAndDefined);1342 }1343 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1344–1356why, one step back1344 }13451346 /**1347 * Display an error message if conflicting options are used together.1348 * Called after checking for help flags in leaf subcommand.1349 *1350 * @api private1351 */1352 _checkForConflictingOptions() {1353 // Walk up hierarchy so can call in subcommand after checking for displaying help.1354 for (let cmd = this; cmd; cmd = cmd.parent) {1355 cmd._checkForConflictingLocalOptions();1356 }feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1357–1359why, one step back1357 }13581359 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1360–1364why, one step back1360 * Parse options from `argv` removing known options,1361 * and return argv split into operands and unknown arguments.1362 *1363 * Examples:1364 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1365–1369why, one step back1365 * argv => operands, unknown1366 * --known kkk op => [op], []1367 * op --known kkk => [op], []1368 * sub --unknown uuu op => [sub], [--unknown uuu op]1369 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1370–1488why, one step back1370 *1371 * @param {String[]} argv1372 * @return {{operands: String[], unknown: String[]}}1373 */13741375 parseOptions(argv) {1376 const operands = []; // operands, not options or values1377 const unknown = []; // first unknown option and remaining unknown args1378 let dest = operands;1379 const args = argv.slice();13801381 function maybeOption(arg) {1382 return arg.length > 1 && arg[0] === '-';1383 }13841385 // parse options1386 let activeVariadicOption = null;1387 while (args.length) {1388 const arg = args.shift();13891390 // literal1391 if (arg === '--') {1392 if (dest === unknown) dest.push(arg);1393 dest.push(...args);1394 break;1395 }13961397 if (activeVariadicOption && !maybeOption(arg)) {1398 this.emit(`option:${activeVariadicOption.name()}`, arg);1399 continue;1400 }1401 activeVariadicOption = null;14021403 if (maybeOption(arg)) {1404 const option = this._findOption(arg);1405 // recognised option, call listener to assign value with possible custom processing1406 if (option) {1407 if (option.required) {1408 const value = args.shift();1409 if (value === undefined) this.optionMissingArgument(option);1410 this.emit(`option:${option.name()}`, value);1411 } else if (option.optional) {1412 let value = null;1413 // historical behaviour is optional value is following arg unless an option1414 if (args.length > 0 && !maybeOption(args[0])) {1415 value = args.shift();1416 }1417 this.emit(`option:${option.name()}`, value);1418 } else { // boolean flag1419 this.emit(`option:${option.name()}`);1420 }1421 activeVariadicOption = option.variadic ? option : null;1422 continue;1423 }1424 }14251426 // Look for combo options following single dash, eat first one if known.1427 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1428 const option = this._findOption(`-${arg[1]}`);1429 if (option) {1430 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1431 // option with value following in same argument1432 this.emit(`option:${option.name()}`, arg.slice(2));1433 } else {1434 // boolean option, emit and put back remainder of arg for further processing1435 this.emit(`option:${option.name()}`);1436 args.unshift(`-${arg.slice(2)}`);1437 }1438 continue;1439 }1440 }14411442 // Look for known long flag with value, like --foo=bar1443 if (/^--[^=]+=/.test(arg)) {1444 const index = arg.indexOf('=');1445 const option = this._findOption(arg.slice(0, index));1446 if (option && (option.required || option.optional)) {1447 this.emit(`option:${option.name()}`, arg.slice(index + 1));1448 continue;1449 }1450 }14511452 // Not a recognised option by this command.1453 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14541455 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1456 if (maybeOption(arg)) {1457 dest = unknown;1458 }14591460 // If using positionalOptions, stop processing our options at subcommand.1461 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1462 if (this._findCommand(arg)) {1463 operands.push(arg);1464 if (args.length > 0) unknown.push(...args);1465 break;1466 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1467 operands.push(arg);1468 if (args.length > 0) operands.push(...args);1469 break;1470 } else if (this._defaultCommandName) {1471 unknown.push(arg);1472 if (args.length > 0) unknown.push(...args);1473 break;1474 }1475 }14761477 // If using passThroughOptions, stop processing options at first command-argument.1478 if (this._passThroughOptions) {1479 dest.push(arg);1480 if (args.length > 0) dest.push(...args);1481 break;1482 }14831484 // add arg1485 dest.push(arg);1486 }14871488 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1489why, one step back1489 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1490–1491why, one step back14901491 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1492why, one step back1492 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1493–1509why, one step back1493 *1494 * @return {Object}1495 */1496 opts() {1497 if (this._storeOptionsAsProperties) {1498 // Preserve original behaviour so backwards compatible when still using properties1499 const result = {};1500 const len = this.options.length;15011502 for (let i = 0; i < len; i++) {1503 const key = this.options[i].attributeName();1504 result[key] = key === this._versionOptionName ? this._version : this[key];1505 }1506 return result;1507 }15081509 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1510why, one step back1510 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1511–1512why, one step back15111512 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1513why, one step back1513 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1514why, one step back1514 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1515why, one step back1515 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1516why, one step back1516 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1517–1534why, one step back1517 optsWithGlobals() {1518 // globals overwrite locals1519 return getCommandAndParents(this).reduce(1520 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1521 {}1522 );1523 }15241525 /**1526 * Display error message and exit (or call exitOverride).1527 *1528 * @param {string} message1529 * @param {Object} [errorOptions]1530 * @param {string} [errorOptions.code] - an id string representing the error1531 * @param {number} [errorOptions.exitCode] - used with process.exit1532 */1533 error(message, errorOptions) {1534 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1535why, one step back1535 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1536–1541why, one step back1536 if (typeof this._showHelpAfterError === 'string') {1537 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1538 } else if (this._showHelpAfterError) {1539 this._outputConfiguration.writeErr('\n');1540 this.outputHelp({ error: true });1541 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1542–1546why, one step back15421543 // exit handling1544 const config = errorOptions || {};1545 const exitCode = config.exitCode || 1;1546 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1547why, one step back1547 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1548–1559why, one step back1548 }15491550 /**1551 * Apply any option related environment variables, if option does1552 * not have a value from cli or client code.1553 *1554 * @api private1555 */1556 _parseOptionsEnv() {1557 this.options.forEach((option) => {1558 if (option.envVar && option.envVar in process.env) {1559 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1560–1561why, one step back1560 // Priority check. Do not overwrite cli or options from unknown source (client-code).1561 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 1562–1571why, one step back1562 if (option.required || option.optional) { // option can take a value1563 // keep very simple, optional always takes value1564 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1565 } else { // boolean1566 // keep very simple, only care that envVar defined and not the value1567 this.emit(`optionEnv:${option.name()}`);1568 }1569 }1570 }1571 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1572–1594why, one step back1572 }15731574 /**1575 * Apply any implied option values, if option is undefined or default value.1576 *1577 * @api private1578 */1579 _parseOptionsImplied() {1580 const dualHelper = new DualOptions(this.options);1581 const hasCustomOptionValue = (optionKey) => {1582 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1583 };1584 this.options1585 .filter(option => (option.implied !== undefined) &&1586 hasCustomOptionValue(option.attributeName()) &&1587 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1588 .forEach((option) => {1589 Object.keys(option.implied)1590 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1591 .forEach(impliedKey => {1592 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1593 });1594 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1595–1605why, one step back1595 }15961597 /**1598 * Argument `name` is missing.1599 *1600 * @param {string} name1601 * @api private1602 */16031604 missingArgument(name) {1605 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1606–1607why, one step back1606 this.error(message, { code: 'commander.missingArgument' });1607 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1608–1617why, one step back16081609 /**1610 * `Option` is missing an argument.1611 *1612 * @param {Option} option1613 * @api private1614 */16151616 optionMissingArgument(option) {1617 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1618–1619why, one step back1618 this.error(message, { code: 'commander.optionMissingArgument' });1619 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1620–1629why, one step back16201621 /**1622 * `Option` does not have a value, and is a mandatory option.1623 *1624 * @param {Option} option1625 * @api private1626 */16271628 missingMandatoryOptionValue(option) {1629 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1630why, one step back1630 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1631–1668why, one step back1631 }16321633 /**1634 * `Option` conflicts with another option.1635 *1636 * @param {Option} option1637 * @param {Option} conflictingOption1638 * @api private1639 */1640 _conflictingOption(option, conflictingOption) {1641 // The calling code does not know whether a negated option is the source of the1642 // value, so do some work to take an educated guess.1643 const findBestOptionFromValue = (option) => {1644 const optionKey = option.attributeName();1645 const optionValue = this.getOptionValue(optionKey);1646 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1647 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1648 if (negativeOption && (1649 (negativeOption.presetArg === undefined && optionValue === false) ||1650 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1651 )) {1652 return negativeOption;1653 }1654 return positiveOption || option;1655 };16561657 const getErrorMessage = (option) => {1658 const bestOption = findBestOptionFromValue(option);1659 const optionKey = bestOption.attributeName();1660 const source = this.getOptionValueSource(optionKey);1661 if (source === 'env') {1662 return `environment variable '${bestOption.envVar}'`;1663 }1664 return `option '${bestOption.flags}'`;1665 };16661667 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1668 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1669why, one step back1669 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1670–1679why, one step back16701671 /**1672 * Unknown option `flag`.1673 *1674 * @param {string} flag1675 * @api private1676 */16771678 unknownOption(flag) {1679 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1680–1696why, one step back1680 let suggestion = '';16811682 if (flag.startsWith('--') && this._showSuggestionAfterError) {1683 // Looping to pick up the global options too1684 let candidateFlags = [];1685 let command = this;1686 do {1687 const moreFlags = command.createHelp().visibleOptions(command)1688 .filter(option => option.long)1689 .map(option => option.long);1690 candidateFlags = candidateFlags.concat(moreFlags);1691 command = command.parent;1692 } while (command && !command._enablePositionalOptions);1693 suggestion = suggestSimilar(flag, candidateFlags);1694 }16951696 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1697–1698why, one step back1697 this.error(message, { code: 'commander.unknownOption' });1698 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1699–1713why, one step back16991700 /**1701 * Excess arguments, more than expected.1702 *1703 * @param {string[]} receivedArgs1704 * @api private1705 */17061707 _excessArguments(receivedArgs) {1708 if (this._allowExcessArguments) return;17091710 const expected = this._args.length;1711 const s = (expected === 1) ? '' : 's';1712 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1713 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 1714–1715why, one step back1714 this.error(message, { code: 'commander.excessArguments' });1715 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1716–1723why, one step back17161717 /**1718 * Unknown command.1719 *1720 * @api private1721 */17221723 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1724–1737why, one step back1724 const unknownName = this.args[0];1725 let suggestion = '';17261727 if (this._showSuggestionAfterError) {1728 const candidateNames = [];1729 this.createHelp().visibleCommands(this).forEach((command) => {1730 candidateNames.push(command.name());1731 // just visible alias1732 if (command.alias()) candidateNames.push(command.alias());1733 });1734 suggestion = suggestSimilar(unknownName, candidateNames);1735 }17361737 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1738–1739why, one step back1738 this.error(message, { code: 'commander.unknownCommand' });1739 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1740–1767why, one step back17401741 /**1742 * Set the program version to `str`.1743 *1744 * This method auto-registers the "-V, --version" flag1745 * which will print the version number when passed.1746 *1747 * You can optionally supply the flags and description to override the defaults.1748 *1749 * @param {string} str1750 * @param {string} [flags]1751 * @param {string} [description]1752 * @return {this | string} `this` command for chaining, or version string if no arguments1753 */17541755 version(str, flags, description) {1756 if (str === undefined) return this._version;1757 this._version = str;1758 flags = flags || '-V, --version';1759 description = description || 'output the version number';1760 const versionOption = this.createOption(flags, description);1761 this._versionOptionName = versionOption.attributeName();1762 this.options.push(versionOption);1763 this.on('option:' + versionOption.name(), () => {1764 this._outputConfiguration.writeOut(`${str}\n`);1765 this._exit(0, 'commander.version', str);1766 });1767 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1768why, one step back1768 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1769–1770why, one step back17691770 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1771why, one step back1771 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1772–1782why, one step back1772 *1773 * @param {string} [str]1774 * @param {Object} [argsDescription]1775 * @return {string|Command}1776 */1777 description(str, argsDescription) {1778 if (str === undefined && argsDescription === undefined) return this._description;1779 this._description = str;1780 if (argsDescription) {1781 this._argsDescription = argsDescription;1782 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1783–1794why, one step back1783 return this;1784 }17851786 /**1787 * Set the summary. Used when listed as subcommand of parent.1788 *1789 * @param {string} [str]1790 * @return {string|Command}1791 */1792 summary(str) {1793 if (str === undefined) return this._summary;1794 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1795why, one step back1795 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1796why, one step back1796 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1797–1809why, one step back17971798 /**1799 * Set an alias for the command.1800 *1801 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1802 *1803 * @param {string} [alias]1804 * @return {string|Command}1805 */18061807 alias(alias) {1808 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1809Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1810why, one step back1810 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1811–1820why, one step back1811 let command = this;1812 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1813 // assume adding alias for last added executable subcommand, rather than this1814 command = this.commands[this.commands.length - 1];1815 }18161817 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18181819 command._aliases.push(alias);1820 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1821why, one step back1821 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1822–1837why, one step back18221823 /**1824 * Set aliases for the command.1825 *1826 * Only the first alias is shown in the auto-generated help.1827 *1828 * @param {string[]} [aliases]1829 * @return {string[]|Command}1830 */18311832 aliases(aliases) {1833 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1834 if (aliases === undefined) return this._aliases;18351836 aliases.forEach((alias) => this.alias(alias));1837 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1838why, one step back1838 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1839–1862why, one step back18391840 /**1841 * Set / get the command usage `str`.1842 *1843 * @param {string} [str]1844 * @return {String|Command}1845 */18461847 usage(str) {1848 if (str === undefined) {1849 if (this._usage) return this._usage;18501851 const args = this._args.map((arg) => {1852 return humanReadableArgName(arg);1853 });1854 return [].concat(1855 (this.options.length || this._hasHelpOption ? '[options]' : []),1856 (this.commands.length ? '[command]' : []),1857 (this._args.length ? args : [])1858 ).join(' ');1859 }18601861 this._usage = str;1862 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1863why, one step back1863 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1864–1865why, one step back18641865 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1866why, one step back1866 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1867–1875why, one step back1867 *1868 * @param {string} [str]1869 * @return {string|Command}1870 */18711872 name(str) {1873 if (str === undefined) return this._name;1874 this._name = str;1875 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1876why, one step back1876 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1877–1878why, one step back18771878 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1879–1915why, one step back1879 * Set the name of the command from script filename, such as process.argv[1],1880 * or require.main.filename, or __filename.1881 *1882 * (Used internally and public although not documented in README.)1883 *1884 * @example1885 * program.nameFromFilename(require.main.filename);1886 *1887 * @param {string} filename1888 * @return {Command}1889 */18901891 nameFromFilename(filename) {1892 this._name = path.basename(filename, path.extname(filename));18931894 return this;1895 }18961897 /**1898 * Get or set the directory for searching for executable subcommands of this command.1899 *1900 * @example1901 * program.executableDir(__dirname);1902 * // or1903 * program.executableDir('subcommands');1904 *1905 * @param {string} [path]1906 * @return {string|Command}1907 */19081909 executableDir(path) {1910 if (path === undefined) return this._executableDir;1911 this._executableDir = path;1912 return this;1913 }19141915 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1916–1927why, one step back1916 * Return program help documentation.1917 *1918 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1919 * @return {string}1920 */19211922 helpInformation(contextOptions) {1923 const helper = this.createHelp();1924 if (helper.helpWidth === undefined) {1925 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1926 }1927 return helper.formatHelp(this, helper);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1928why, one step back1928 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1929–1963why, one step back19291930 /**1931 * @api private1932 */19331934 _getHelpContext(contextOptions) {1935 contextOptions = contextOptions || {};1936 const context = { error: !!contextOptions.error };1937 let write;1938 if (context.error) {1939 write = (arg) => this._outputConfiguration.writeErr(arg);1940 } else {1941 write = (arg) => this._outputConfiguration.writeOut(arg);1942 }1943 context.write = contextOptions.write || write;1944 context.command = this;1945 return context;1946 }19471948 /**1949 * Output help information for this command.1950 *1951 * Outputs built-in help, and custom text added using `.addHelpText()`.1952 *1953 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1954 */19551956 outputHelp(contextOptions) {1957 let deprecatedCallback;1958 if (typeof contextOptions === 'function') {1959 deprecatedCallback = contextOptions;1960 contextOptions = undefined;1961 }1962 const context = this._getHelpContext(contextOptions);1963Use getCommandAndParents for array of parents (#1566)John Geebefore adoption4be69f1
line 1964why, one step back1964 getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1965–1977why, one step back1965 this.emit('beforeHelp', context);19661967 let helpInformation = this.helpInformation(context);1968 if (deprecatedCallback) {1969 helpInformation = deprecatedCallback(helpInformation);1970 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1971 throw new Error('outputHelp callback must return a string or a Buffer');1972 }1973 }1974 context.write(helpInformation);19751976 this.emit(this._helpLongFlag); // deprecated1977 this.emit('afterHelp', context);Use getCommandAndParents for array of parents (#1566)John Geebefore adoption4be69f1
line 1978why, one step back1978 getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1979why, one step back1979 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1980–2003why, one step back19801981 /**1982 * You can pass in flags and a description to override the help1983 * flags and help description for your command. Pass in false to1984 * disable the built-in help option.1985 *1986 * @param {string | boolean} [flags]1987 * @param {string} [description]1988 * @return {Command} `this` command for chaining1989 */19901991 helpOption(flags, description) {1992 if (typeof flags === 'boolean') {1993 this._hasHelpOption = flags;1994 return this;1995 }1996 this._helpFlags = flags || this._helpFlags;1997 this._helpDescription = description || this._helpDescription;19981999 const helpFlags = splitOptionFlags(this._helpFlags);2000 this._helpShortFlag = helpFlags.shortFlag;The first 2,000 of 2,135 lines.