command.js
This file
Path
lib/command.js
2,218 lines · 69.4 KiB · JavaScript
Last changed by
Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
History of this fileTake it
Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1–4why, one step back1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');Follow best practice and require process rather than use global (#1685)John Geebefore adoption47e8b20
line 5why, one step back5const process = require('process');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 6–9why, one step back67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');Add Option.implies() (#1724)John Geebefore adoptiond660967
line 10why, one step back10const { Option, splitOptionFlags, DualOptions } = require('./option.js');Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 11why, one step back11const { suggestSimilar } = require('./suggestSimilar');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 12–23why, one step back1213// @ts-check1415class Command extends EventEmitter {16 /**17 * Initialize a new `Command`.18 *19 * @param {string} [name]20 */2122 constructor(name) {23 super();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 24why, one step back24 /** @type {Command[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 25why, one step back25 this.commands = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 26why, one step back26 /** @type {Option[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 27–30why, one step back27 this.options = [];28 this.parent = null;29 this._allowUnknownOption = false;30 this._allowExcessArguments = true;Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 31why, one step back31 /** @type {Argument[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 32why, one step back32 this._args = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 33–36why, one step back33 /** @type {string[]} */34 this.args = []; // cli args with options removed35 this.rawArgs = [];36 this.processedArgs = []; // like .args but after custom processing and collecting variadicRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 37–39why, one step back37 this._scriptPath = null;38 this._name = name || '';39 this._optionValues = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 40why, one step back40 this._optionValueSources = {}; // default, env, cli etcRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 41–44why, one step back41 this._storeOptionsAsProperties = false;42 this._actionHandler = null;43 this._executableHandler = false;44 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 45why, one step back45 this._executableDir = null; // custom search directory for subcommandsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 46–50why, one step back46 this._defaultCommandName = null;47 this._exitCallback = null;48 this._aliases = [];49 this._combineFlagAndOptionalValue = true;50 this._description = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 51why, one step back51 this._summary = '';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 52–55why, one step back52 this._argsDescription = undefined; // legacy53 this._enablePositionalOptions = false;54 this._passThroughOptions = false;55 this._lifeCycleHooks = {}; // a hash of arraysAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 56–57why, one step back56 /** @type {boolean | string} */57 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 58why, one step back58 this._showSuggestionAfterError = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 59–82why, one step back5960 // see .configureOutput() for docs61 this._outputConfiguration = {62 writeOut: (str) => process.stdout.write(str),63 writeErr: (str) => process.stderr.write(str),64 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,65 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,66 outputError: (str, write) => write(str)67 };6869 this._hidden = false;70 this._hasHelpOption = true;71 this._helpFlags = '-h, --help';72 this._helpDescription = 'display help for command';73 this._helpShortFlag = '-h';74 this._helpLongFlag = '--help';75 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false76 this._helpCommandName = 'help';77 this._helpCommandnameAndArgs = 'help [command]';78 this._helpCommandDescription = 'display help for command';79 this._helpConfiguration = {};80 }8182 /**Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 83–87why, one step back83 * Copy settings that are useful to have in common across root command and subcommands.84 *85 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)86 *87 * @param {Command} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 88why, one step back88 * @return {Command} `this` command for chainingAdd copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 89–106why, one step back89 */90 copyInheritedSettings(sourceCommand) {91 this._outputConfiguration = sourceCommand._outputConfiguration;92 this._hasHelpOption = sourceCommand._hasHelpOption;93 this._helpFlags = sourceCommand._helpFlags;94 this._helpDescription = sourceCommand._helpDescription;95 this._helpShortFlag = sourceCommand._helpShortFlag;96 this._helpLongFlag = sourceCommand._helpLongFlag;97 this._helpCommandName = sourceCommand._helpCommandName;98 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;99 this._helpCommandDescription = sourceCommand._helpCommandDescription;100 this._helpConfiguration = sourceCommand._helpConfiguration;101 this._exitCallback = sourceCommand._exitCallback;102 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;103 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;104 this._allowExcessArguments = sourceCommand._allowExcessArguments;105 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;106 this._showHelpAfterError = sourceCommand._showHelpAfterError;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 107why, one step back107 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 108–112why, one step back108109 return this;110 }111112 /**Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 113–125why, one step back113 * @returns {Command[]}114 * @api private115 */116117 _getCommandAndAncestors() {118 const result = [];119 for (let command = this; command; command = command.parent) {120 result.push(command);121 }122 return result;123 }124125 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 126–129why, one step back126 * Define a command.127 *128 * There are two styles of command: pay attention to where to put the description.129 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 130–137why, one step back130 * @example131 * // Command implemented using action handler (description is supplied separately to `.command`)132 * program133 * .command('clone <source> [destination]')134 * .description('clone a repository into a newly created directory')135 * .action((source, destination) => {136 * console.log('clone command called');137 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 138why, one step back138 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 139–142why, one step back139 * // Command implemented using separate executable file (description is second parameter to `.command`)140 * program141 * .command('start <service>', 'start named service')142 * .command('stop [service]', 'stop named service, or all if no name supplied');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 143–159why, one step back143 *144 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`145 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)146 * @param {Object} [execOpts] - configuration options (for executable)147 * @return {Command} returns new command for action handler, or `this` for executable command148 */149150 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {151 let desc = actionOptsOrExecDesc;152 let opts = execOpts;153 if (typeof desc === 'object' && desc !== null) {154 opts = desc;155 desc = null;156 }157 opts = opts || {};158 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);159Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 160why, one step back160 const cmd = this.createCommand(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 161–170why, one step back161 if (desc) {162 cmd.description(desc);163 cmd._executableHandler = true;164 }165 if (opts.isDefault) this._defaultCommandName = cmd._name;166 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden167 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor168 if (args) cmd.arguments(args);169 this.commands.push(cmd);170 cmd.parent = this;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 171why, one step back171 cmd.copyInheritedSettings(this);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 172–174why, one step back172173 if (desc) return this;174 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 175why, one step back175 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 176–188why, one step back176177 /**178 * Factory routine to create a new unattached command.179 *180 * See .command() for creating an attached subcommand, which uses this routine to181 * create the command. You can override createCommand to customise subcommands.182 *183 * @param {string} [name]184 * @return {Command} new command185 */186187 createCommand(name) {188 return new Command(name);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 189why, one step back189 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 190–199why, one step back190191 /**192 * You can customise the help with a subclass of Help by overriding createHelp,193 * or by overriding Help properties using configureHelp().194 *195 * @return {Help}196 */197198 createHelp() {199 return Object.assign(new Help(), this.configureHelp());Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 200why, one step back200 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 201–222why, one step back201202 /**203 * You can customise the help by overriding Help properties using configureHelp(),204 * or with a subclass of Help by overriding createHelp().205 *206 * @param {Object} [configuration] - configuration options207 * @return {Command|Object} `this` command for chaining, or stored configuration208 */209210 configureHelp(configuration) {211 if (configuration === undefined) return this._helpConfiguration;212213 this._helpConfiguration = configuration;214 return this;215 }216217 /**218 * The default output goes to stdout and stderr. You can customise this for special219 * applications. You can also customise the display of errors by overriding outputError.220 *221 * The configuration properties are all functions:222 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 223–230why, one step back223 * // functions to change where being written, stdout and stderr224 * writeOut(str)225 * writeErr(str)226 * // matching functions to specify width for wrapping help227 * getOutHelpWidth()228 * getErrHelpWidth()229 * // functions based on what is being written out230 * outputError(str, write) // used for displaying errors, and not used for displaying helpRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 231–243why, one step back231 *232 * @param {Object} [configuration] - configuration options233 * @return {Command|Object} `this` command for chaining, or stored configuration234 */235236 configureOutput(configuration) {237 if (configuration === undefined) return this._outputConfiguration;238239 Object.assign(this._outputConfiguration, configuration);240 return this;241 }242243 /**Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 244–255why, one step back244 * Display the help or a custom message after an error occurs.245 *246 * @param {boolean|string} [displayHelp]247 * @return {Command} `this` command for chaining248 */249 showHelpAfterError(displayHelp = true) {250 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;251 this._showHelpAfterError = displayHelp;252 return this;253 }254255 /**Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 256–266why, one step back256 * Display suggestion of similar commands for unknown commands, or options for unknown options.257 *258 * @param {boolean} [displaySuggestion]259 * @return {Command} `this` command for chaining260 */261 showSuggestionAfterError(displaySuggestion = true) {262 this._showSuggestionAfterError = !!displaySuggestion;263 return this;264 }265266 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 267–276why, one step back267 * Add a prepared subcommand.268 *269 * See .command() for creating an attached subcommand which inherits settings from its parent.270 *271 * @param {Command} cmd - new subcommand272 * @param {Object} [opts] - configuration options273 * @return {Command} `this` command for chaining274 */275276 addCommand(cmd, opts) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 277–279why, one step back277 if (!cmd._name) {278 throw new Error(`Command passed to .addCommand() must have a name279- specify the name in Command constructor or using .name()`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 280–287why, one step back280 }281282 opts = opts || {};283 if (opts.isDefault) this._defaultCommandName = cmd._name;284 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation285286 this.commands.push(cmd);287 cmd.parent = this;Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
line 288why, one step back288 cmd._checkForBrokenPassThrough();Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
line 289why, one step back289Refactor classes into files (#1522)John Geebefore adoption08245cc
line 290why, one step back290 return this;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–305why, one step back292293 /**294 * Factory routine to create a new unattached argument.295 *296 * See .argument() for creating an attached argument, which uses this routine to297 * create the argument. You can override createArgument to return a custom argument.298 *299 * @param {string} name300 * @param {string} [description]301 * @return {Argument} new argument302 */303304 createArgument(name, description) {305 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 306why, one step back306 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 307–314why, one step back307308 /**309 * Define argument syntax for command.310 *311 * The default is that the argument is required, and you can explicitly312 * indicate this with <> around the name. Put [] around the name for an optional argument.313 *314 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 315–316why, one step back315 * program.argument('<input-file>');316 * program.argument('[output-file]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 317–340why, one step back317 *318 * @param {string} name319 * @param {string} [description]320 * @param {Function|*} [fn] - custom argument processing function321 * @param {*} [defaultValue]322 * @return {Command} `this` command for chaining323 */324 argument(name, description, fn, defaultValue) {325 const argument = this.createArgument(name, description);326 if (typeof fn === 'function') {327 argument.default(defaultValue).argParser(fn);328 } else {329 argument.default(fn);330 }331 this.addArgument(argument);332 return this;333 }334335 /**336 * Define argument syntax for command, adding multiple at once (without descriptions).337 *338 * See also .argument().339 *340 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 341why, one step back341 * program.arguments('<cmd> [env]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 342–347why, one step back342 *343 * @param {string} names344 * @return {Command} `this` command for chaining345 */346347 arguments(names) {trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a
line 348why, one step back348 names.trim().split(/ +/).forEach((detail) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 349–351why, one step back349 this.argument(detail);350 });351 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 352why, one step back352 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 353–393why, one step back353354 /**355 * Define argument syntax for command, adding a prepared argument.356 *357 * @param {Argument} argument358 * @return {Command} `this` command for chaining359 */360 addArgument(argument) {361 const previousArgument = this._args.slice(-1)[0];362 if (previousArgument && previousArgument.variadic) {363 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);364 }365 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {366 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);367 }368 this._args.push(argument);369 return this;370 }371372 /**373 * Override default decision whether to add implicit help command.374 *375 * addHelpCommand() // force on376 * addHelpCommand(false); // force off377 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details378 *379 * @return {Command} `this` command for chaining380 */381382 addHelpCommand(enableOrNameAndArgs, description) {383 if (enableOrNameAndArgs === false) {384 this._addImplicitHelpCommand = false;385 } else {386 this._addImplicitHelpCommand = true;387 if (typeof enableOrNameAndArgs === 'string') {388 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];389 this._helpCommandnameAndArgs = enableOrNameAndArgs;390 }391 this._helpCommandDescription = description || this._helpCommandDescription;392 }393 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 394why, one step back394 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 395–405why, one step back395396 /**397 * @return {boolean}398 * @api private399 */400401 _hasImplicitHelpCommand() {402 if (this._addImplicitHelpCommand === undefined) {403 return this.commands.length && !this._actionHandler && !this._findCommand('help');404 }405 return this._addImplicitHelpCommand;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 406why, one step back406 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 407–416why, one step back407408 /**409 * Add hook for life cycle event.410 *411 * @param {string} event412 * @param {Function} listener413 * @return {Command} `this` command for chaining414 */415416 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 417why, one step back417 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 418–449why, one step back418 if (!allowedValues.includes(event)) {419 throw new Error(`Unexpected value for event passed to hook : '${event}'.420Expecting one of '${allowedValues.join("', '")}'`);421 }422 if (this._lifeCycleHooks[event]) {423 this._lifeCycleHooks[event].push(listener);424 } else {425 this._lifeCycleHooks[event] = [listener];426 }427 return this;428 }429430 /**431 * Register callback to use as replacement for calling process.exit.432 *433 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing434 * @return {Command} `this` command for chaining435 */436437 exitOverride(fn) {438 if (fn) {439 this._exitCallback = fn;440 } else {441 this._exitCallback = (err) => {442 if (err.code !== 'commander.executeSubCommandAsync') {443 throw err;444 } else {445 // Async callback from spawn events, not useful to throw.446 }447 };448 }449 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 450why, one step back450 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 451–467why, one step back451452 /**453 * Call process.exit, and _exitCallback if defined.454 *455 * @param {number} exitCode exit code for using with process.exit456 * @param {string} code an id string representing the error457 * @param {string} message human-readable description of the error458 * @return never459 * @api private460 */461462 _exit(exitCode, code, message) {463 if (this._exitCallback) {464 this._exitCallback(new CommanderError(exitCode, code, message));465 // Expecting this line is not reached.466 }467 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 468why, one step back468 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 469–472why, one step back469470 /**471 * Register callback `fn` for the command.472 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 473–474why, one step back473 * @example474 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 475–476why, one step back475 * .command('serve')476 * .description('start service')Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 477why, one step back477 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 478why, one step back478 * // do work hereFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 479why, one step back479 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 480–500why, one step back480 *481 * @param {Function} fn482 * @return {Command} `this` command for chaining483 */484485 action(fn) {486 const listener = (args) => {487 // The .action callback takes an extra parameter which is the command or options.488 const expectedArgsCount = this._args.length;489 const actionArgs = args.slice(0, expectedArgsCount);490 if (this._storeOptionsAsProperties) {491 actionArgs[expectedArgsCount] = this; // backwards compatible "options"492 } else {493 actionArgs[expectedArgsCount] = this.opts();494 }495 actionArgs.push(this);496497 return fn.apply(this, actionArgs);498 };499 this._actionHandler = listener;500 return this;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–515why, one step back502503 /**504 * Factory routine to create a new unattached option.505 *506 * See .option() for creating an attached option, which uses this routine to507 * create the option. You can override createOption to return a custom option.508 *509 * @param {string} flags510 * @param {string} [description]511 * @return {Option} new option512 */513514 createOption(flags, description) {515 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 516why, one step back516 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 517–518why, one step back517518 /**Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
lines 519–540why, one step back519 * Wrap parseArgs to catch 'commander.invalidArgument'.520 *521 * @param {Option | Argument} target522 * @param {string} value523 * @param {any} previous524 * @param {string} invalidArgumentMessage525 * @api private526 */527528 _callParseArg(target, value, previous, invalidArgumentMessage) {529 try {530 return target.parseArg(value, previous);531 } catch (err) {532 if (err.code === 'commander.invalidArgument') {533 const message = `${invalidArgumentMessage} ${err.message}`;534 this.error(message, { exitCode: err.exitCode, code: err.code });535 }536 throw err;537 }538 }539540 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 541–549why, one step back541 * Add an option.542 *543 * @param {Option} option544 * @return {Command} `this` command for chaining545 */546 addOption(option) {547 const oname = option.name();548 const name = option.attributeName();549Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 550–555why, one step back550 // store default value551 if (option.negate) {552 // --no-foo is special and defaults foo to true, unless a --foo option is already defined553 const positiveLongFlag = option.long.replace(/^--no-/, '--');554 if (!this._findOption(positiveLongFlag)) {555 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 556why, one step back556 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 557–558why, one step back557 } else if (option.defaultValue !== undefined) {558 this.setOptionValueWithSource(name, option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 559–563why, one step back559 }560561 // register the option562 this.options.push(option);563Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 564–565why, one step back564 // handler for cli and env supplied values565 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 566–570why, one step back566 // val is null for optional option used without an optional-argument.567 // val is undefined for boolean and negated option.568 if (val == null && option.presetArg !== undefined) {569 val = option.presetArg;570 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 571–572why, one step back571572 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 573why, one step back573 const oldValue = this.getOptionValue(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 574why, one step back574 if (val !== null && option.parseArg) {Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 575why, one step back575 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 576–579why, one step back576 } else if (val !== null && option.variadic) {577 val = option._concatValue(val, oldValue);578 }579Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 580–585why, one step back580 // Fill-in appropriate missing values. Long winded but easy to follow.581 if (val == null) {582 if (option.negate) {583 val = false;584 } else if (option.isBoolean() || option.optional) {585 val = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 586why, one step back586 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 587why, one step back587 val = ''; // not normal, parseArg might have failed or be a mock function for testingRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 588–589why, one step back588 }589 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 590why, one step back590 this.setOptionValueWithSource(name, val, valueSource);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 591–595why, one step back591 };592593 this.on('option:' + oname, (val) => {594 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;595 handleOptionValue(val, invalidValueMessage, 'cli');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 596–597why, one step back596 });597Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 598–604why, one step back598 if (option.envVar) {599 this.on('optionEnv:' + oname, (val) => {600 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;601 handleOptionValue(val, invalidValueMessage, 'env');602 });603 }604Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 605–613why, one step back605 return this;606 }607608 /**609 * Internal implementation shared by .option() and .requiredOption()610 *611 * @api private612 */613 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 614–616why, one step back614 if (typeof flags === 'object' && flags instanceof Option) {615 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');616 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 617–643why, one step back617 const option = this.createOption(flags, description);618 option.makeOptionMandatory(!!config.mandatory);619 if (typeof fn === 'function') {620 option.default(defaultValue).argParser(fn);621 } else if (fn instanceof RegExp) {622 // deprecated623 const regex = fn;624 fn = (val, def) => {625 const m = regex.exec(val);626 return m ? m[0] : def;627 };628 option.default(defaultValue).argParser(fn);629 } else {630 option.default(fn);631 }632633 return this.addOption(option);634 }635636 /**637 * Define option with `flags`, `description` and optional638 * coercion `fn`.639 *640 * The `flags` string contains the short and/or long flags,641 * separated by comma, a pipe or space. The following are all valid642 * all will output this way when `--help` is used.643 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 644–646why, one step back644 * "-p, --pepper"645 * "-p|--pepper"646 * "-p --pepper"Refactor classes into files (#1522)John Geebefore adoption08245cc
line 647why, one step back647 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 648–650why, one step back648 * @example649 * // simple boolean defaulting to undefined650 * program.option('-p, --pepper', 'add pepper');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 651why, one step back651 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 652–653why, one step back652 * program.pepper653 * // => undefinedRefactor classes into files (#1522)John Geebefore adoption08245cc
line 654why, one step back654 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 655–657why, one step back655 * --pepper656 * program.pepper657 * // => trueRefactor classes into files (#1522)John Geebefore adoption08245cc
line 658why, one step back658 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 659–660why, one step back659 * // simple boolean defaulting to true (unless non-negated option is also defined)660 * program.option('-C, --no-cheese', 'remove cheese');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 661why, one step back661 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 662–663why, one step back662 * program.cheese663 * // => trueRefactor classes into files (#1522)John Geebefore adoption08245cc
line 664why, one step back664 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 665–667why, one step back665 * --no-cheese666 * program.cheese667 * // => falseRefactor classes into files (#1522)John Geebefore adoption08245cc
line 668why, one step back668 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 669–670why, one step back669 * // required argument670 * program.option('-C, --chdir <path>', 'change the working directory');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 671why, one step back671 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 672–674why, one step back672 * --chdir /tmp673 * program.chdir674 * // => "/tmp"Refactor classes into files (#1522)John Geebefore adoption08245cc
line 675why, one step back675 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 676–677why, one step back676 * // optional argument677 * program.option('-c, --cheese [type]', 'add cheese [marble]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 678–687why, one step back678 *679 * @param {string} flags680 * @param {string} [description]681 * @param {Function|*} [fn] - custom option processing function or default value682 * @param {*} [defaultValue]683 * @return {Command} `this` command for chaining684 */685686 option(flags, description, fn, defaultValue) {687 return this._optionEx({}, flags, description, fn, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 688why, one step back688 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 689–704why, one step back689690 /**691 * Add a required option which must have a value after parsing. This usually means692 * the option must be specified on the command line. (Otherwise the same as .option().)693 *694 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.695 *696 * @param {string} flags697 * @param {string} [description]698 * @param {Function|*} [fn] - custom option processing function or default value699 * @param {*} [defaultValue]700 * @return {Command} `this` command for chaining701 */702703 requiredOption(flags, description, fn, defaultValue) {704 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 705why, one step back705 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 706–709why, one step back706707 /**708 * Alter parsing of short flags with optional values.709 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 710–713why, one step back710 * @example711 * // for `.option('-f,--flag [value]'):712 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour713 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 714–719why, one step back714 *715 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.716 */717 combineFlagAndOptionalValue(combine = true) {718 this._combineFlagAndOptionalValue = !!combine;719 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 720why, one step back720 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 721–730why, one step back721722 /**723 * Allow unknown options on the command line.724 *725 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown726 * for unknown options.727 */728 allowUnknownOption(allowUnknown = true) {729 this._allowUnknownOption = !!allowUnknown;730 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 731why, one step back731 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 732–741why, one step back732733 /**734 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.735 *736 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown737 * for excess arguments.738 */739 allowExcessArguments(allowExcess = true) {740 this._allowExcessArguments = !!allowExcess;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–753why, one step back743744 /**745 * Enable positional options. Positional means global options are specified before subcommands which lets746 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.747 * The default behaviour is non-positional and global options may appear anywhere on the command line.748 *749 * @param {Boolean} [positional=true]750 */751 enablePositionalOptions(positional = true) {752 this._enablePositionalOptions = !!positional;753 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 754why, one step back754 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 755–766why, one step back755756 /**757 * Pass through options that come after command-arguments rather than treat them as command-options,758 * so actual command-options come before command-arguments. Turning this on for a subcommand requires759 * positional options to have been enabled on the program (parent commands).760 * The default behaviour is non-positional and options may appear before or after command-arguments.761 *762 * @param {Boolean} [passThrough=true]763 * for unknown options.764 */765 passThroughOptions(passThrough = true) {766 this._passThroughOptions = !!passThrough;Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
line 767why, one step back767 this._checkForBrokenPassThrough();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 768why, one step back768 return this;Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
lines 769–774why, one step back769 }770771 /**772 * @api private773 */774Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
lines 775–777why, one step back775 _checkForBrokenPassThrough() {776 if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {777 throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
line 778why, one step back778 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 779why, one step back779 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 780–792why, one step back780781 /**782 * Whether to store option values as properties on command object,783 * or store separately (specify false). In both cases the option values can be accessed using .opts().784 *785 * @param {boolean} [storeAsProperties=true]786 * @return {Command} `this` command for chaining787 */788789 storeOptionsAsProperties(storeAsProperties = true) {790 if (this.options.length) {791 throw new Error('call .storeOptionsAsProperties() before adding options');792 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 793–796why, one step back793 if (Object.keys(this._optionValues).length) {794 throw new Error('call .storeOptionsAsProperties() before setting option values');795 }796 this._storeOptionsAsProperties = !!storeAsProperties;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 797why, one step back797 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 798why, one step back798 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 799–811why, one step back799800 /**801 * Retrieve option value.802 *803 * @param {string} key804 * @return {Object} value805 */806807 getOptionValue(key) {808 if (this._storeOptionsAsProperties) {809 return this[key];810 }811 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 812why, one step back812 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 813–822why, one step back813814 /**815 * Store option value.816 *817 * @param {string} key818 * @param {Object} value819 * @return {Command} `this` command for chaining820 */821822 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 823why, one step back823 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 824why, one step back824 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 825–826why, one step back825826 /**Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 827why, one step back827 * Store option value and where the value came from.Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 828–830why, one step back828 *829 * @param {string} key830 * @param {Object} valueAdd implied to option value sources (#1794)John Geebefore adoption72be61c
line 831why, one step back831 * @param {string} source - expected values are default/config/env/cli/impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 832–835why, one step back832 * @return {Command} `this` command for chaining833 */834835 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 836–840why, one step back836 if (this._storeOptionsAsProperties) {837 this[key] = value;838 } else {839 this._optionValues[key] = value;840 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 841why, one step back841 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 842why, one step back842 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 843–845why, one step back843 }844845 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 846why, one step back846 * Get source of option value.Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 847why, one step back847 * Expected values are default | config | env | cli | impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 848–854why, one step back848 *849 * @param {string} key850 * @return {string}851 */852853 getOptionValueSource(key) {854 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 855why, one step back855 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 856–857why, one step back856857 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 858–867why, one step back858 * Get source of option value. See also .optsWithGlobals().859 * Expected values are default | config | env | cli | implied860 *861 * @param {string} key862 * @return {string}863 */864865 getOptionValueSourceWithGlobals(key) {866 // global overwrites local, like optsWithGlobals867 let source;Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 868why, one step back868 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 869–876why, one step back869 if (cmd.getOptionValueSource(key) !== undefined) {870 source = cmd.getOptionValueSource(key);871 }872 });873 return source;874 }875876 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 877–878why, one step back877 * Get user arguments from implied or explicit arguments.878 * 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 879–922why, one step back879 *880 * @api private881 */882883 _prepareUserArgs(argv, parseOptions) {884 if (argv !== undefined && !Array.isArray(argv)) {885 throw new Error('first parameter to parse must be array or undefined');886 }887 parseOptions = parseOptions || {};888889 // Default to using process.argv890 if (argv === undefined) {891 argv = process.argv;892 // @ts-ignore: unknown property893 if (process.versions && process.versions.electron) {894 parseOptions.from = 'electron';895 }896 }897 this.rawArgs = argv.slice();898899 // make it a little easier for callers by supporting various argv conventions900 let userArgs;901 switch (parseOptions.from) {902 case undefined:903 case 'node':904 this._scriptPath = argv[1];905 userArgs = argv.slice(2);906 break;907 case 'electron':908 // @ts-ignore: unknown property909 if (process.defaultApp) {910 this._scriptPath = argv[1];911 userArgs = argv.slice(2);912 } else {913 userArgs = argv.slice(1);914 }915 break;916 case 'user':917 userArgs = argv.slice(0);918 break;919 default:920 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);921 }922Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 923–925why, one step back923 // Find default name for program from arguments.924 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);925 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 926–935why, one step back926927 return userArgs;928 }929930 /**931 * Parse `argv`, setting options and invoking commands when defined.932 *933 * The default expectation is that the arguments are from node and have the application as argv[0]934 * and the script being run in argv[1], with user parameters after that.935 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 936–939why, one step back936 * @example937 * program.parse(process.argv);938 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions939 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 940–951why, one step back940 *941 * @param {string[]} [argv] - optional, defaults to process.argv942 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron943 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'944 * @return {Command} `this` command for chaining945 */946947 parse(argv, parseOptions) {948 const userArgs = this._prepareUserArgs(argv, parseOptions);949 this._parseCommand([], userArgs);950951 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 952why, one step back952 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 953–961why, one step back953954 /**955 * Parse `argv`, setting options and invoking commands when defined.956 *957 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.958 *959 * The default expectation is that the arguments are from node and have the application as argv[0]960 * and the script being run in argv[1], with user parameters after that.961 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 962–965why, one step back962 * @example963 * await program.parseAsync(process.argv);964 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions965 * 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 966–977why, one step back966 *967 * @param {string[]} [argv]968 * @param {Object} [parseOptions]969 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'970 * @return {Promise}971 */972973 async parseAsync(argv, parseOptions) {974 const userArgs = this._prepareUserArgs(argv, parseOptions);975 await this._parseCommand([], userArgs);976977 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 978why, one step back978 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 979–990why, one step back979980 /**981 * Execute a sub-command executable.982 *983 * @api private984 */985986 _executeSubCommand(subcommand, args) {987 args = args.slice();988 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.989 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];990Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 991–994why, one step back991 function findFile(baseDir, baseName) {992 // Look for specified file993 const localBin = path.resolve(baseDir, baseName);994 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 995why, one step back995Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 996–997why, one step back996 // Stop looking if candidate already has an expected extension.997 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 998why, one step back998Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 999–1003why, one step back999 // Try all the extensions.1000 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));1001 if (foundExt) return `${localBin}${foundExt}`;10021003 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1004–1005why, one step back1004 }1005Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1006–1007why, one step back1006 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1007 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1008why, one step back1008 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1009–1020why, one step back10091010 // executableFile and executableDir might be full path, or just a name1011 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1012 let executableDir = this._executableDir || '';1013 if (this._scriptPath) {1014 let resolvedScriptPath; // resolve possible symlink for installed npm binary1015 try {1016 resolvedScriptPath = fs.realpathSync(this._scriptPath);1017 } catch (err) {1018 resolvedScriptPath = this._scriptPath;1019 }1020 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1021–1022why, one step back1021 }1022Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1023–1031why, one step back1023 // Look for a local file in preference to a command in PATH.1024 if (executableDir) {1025 let localFile = findFile(executableDir, executableFile);10261027 // Legacy search using prefix of script name instead of command name1028 if (!localFile && !subcommand._executableFile && this._scriptPath) {1029 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1030 if (legacyName !== this._name) {1031 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1032why, one step back1032 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1033–1034why, one step back1033 }1034 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1035–1036why, one step back1035 }1036Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1037–1038why, one step back1037 launchWithNode = sourceExt.includes(path.extname(executableFile));1038Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1039–1041why, one step back1039 let proc;1040 if (process.platform !== 'win32') {1041 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1042why, one step back1042 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1043–1047why, one step back1043 // add executable arguments to spawn1044 args = incrementNodeInspectorPort(process.execArgv).concat(args);10451046 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1047 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1048why, one step back1048 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1049–1050why, one step back1049 }1050 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1051why, one step back1051 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1052–1056why, one step back1052 // add executable arguments to spawn1053 args = incrementNodeInspectorPort(process.execArgv).concat(args);1054 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1055 }1056Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1057–1065why, one step back1057 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1058 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1059 signals.forEach((signal) => {1060 // @ts-ignore1061 process.on(signal, () => {1062 if (proc.killed === false && proc.exitCode === null) {1063 proc.kill(signal);1064 }1065 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1066why, one step back1066 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1067why, one step back1067 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1068–1081why, one step back10681069 // By default terminate process when spawned process terminates.1070 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1071 const exitCallback = this._exitCallback;1072 if (!exitCallback) {1073 proc.on('close', process.exit.bind(process));1074 } else {1075 proc.on('close', () => {1076 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1077 });1078 }1079 proc.on('error', (err) => {1080 // @ts-ignore1081 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1082–1085why, one step back1082 const executableDirMessage = executableDir1083 ? `searched for local subcommand relative to directory '${executableDir}'`1084 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1085 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1086why, one step back1086 - 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 1087–1088why, one step back1087 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1088 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1089–1091why, one step back1089 throw new Error(executableMissing);1090 // @ts-ignore1091 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1092why, one step back1092 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1093–1104why, one step back1093 }1094 if (!exitCallback) {1095 process.exit(1);1096 } else {1097 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1098 wrappedError.nestedError = err;1099 exitCallback(wrappedError);1100 }1101 });11021103 // Store the reference to the child process1104 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1105why, one step back1105 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1106–1114why, one step back11061107 /**1108 * @api private1109 */11101111 _dispatchSubcommand(commandName, operands, unknown) {1112 const subCommand = this._findCommand(commandName);1113 if (!subCommand) this.help({ error: true });1114Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1115–1117why, one step back1115 let promiseChain;1116 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1117 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1118–1123why, one step back1118 if (subCommand._executableHandler) {1119 this._executeSubCommand(subCommand, operands.concat(unknown));1120 } else {1121 return subCommand._parseCommand(operands, unknown);1122 }1123 });Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1124why, one step back1124 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1125why, one step back1125 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1126–1127why, one step back11261127 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1128–1143why, one step back1128 * Invoke help directly if possible, or dispatch if necessary.1129 * e.g. help foo1130 *1131 * @api private1132 */11331134 _dispatchHelpCommand(subcommandName) {1135 if (!subcommandName) {1136 this.help();1137 }1138 const subCommand = this._findCommand(subcommandName);1139 if (subCommand && !subCommand._executableHandler) {1140 subCommand.help();1141 }11421143 // Fallback to parsing the help flag to invoke the help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1144–1146why, one step back1144 return this._dispatchSubcommand(subcommandName, [], [1145 this._helpLongFlag || this._helpShortFlag1146 ]);Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1147–1149why, one step back1147 }11481149 /**Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1150why, one step back1150 * Check this.args against expected this._args.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1151–1154why, one step back1151 *1152 * @api private1153 */1154Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1155–1168why, one step back1155 _checkNumberOfArguments() {1156 // too few1157 this._args.forEach((arg, i) => {1158 if (arg.required && this.args[i] == null) {1159 this.missingArgument(arg.name());1160 }1161 });1162 // too many1163 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1164 return;1165 }1166 if (this.args.length > this._args.length) {1167 this._excessArguments(this.args);1168 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1169why, one step back1169 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1170–1177why, one step back11701171 /**1172 * Process this.args using this._args and save as this.processedArgs!1173 *1174 * @api private1175 */11761177 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1178–1181why, one step back1178 const myParseArg = (argument, value, previous) => {1179 // Extra processing for nice error message on parsing failure.1180 let parsedValue = value;1181 if (value !== null && argument.parseArg) {Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
lines 1182–1183why, one step back1182 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1183 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1184–1187why, one step back1184 }1185 return parsedValue;1186 };1187Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1188–1190why, one step back1188 this._checkNumberOfArguments();11891190 const processedArgs = [];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1191–1210why, one step back1191 this._args.forEach((declaredArg, index) => {1192 let value = declaredArg.defaultValue;1193 if (declaredArg.variadic) {1194 // Collect together remaining arguments for passing together as an array.1195 if (index < this.args.length) {1196 value = this.args.slice(index);1197 if (declaredArg.parseArg) {1198 value = value.reduce((processed, v) => {1199 return myParseArg(declaredArg, v, processed);1200 }, declaredArg.defaultValue);1201 }1202 } else if (value === undefined) {1203 value = [];1204 }1205 } else if (index < this.args.length) {1206 value = this.args[index];1207 if (declaredArg.parseArg) {1208 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1209 }1210 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1211why, one step back1211 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1212why, one step back1212 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1213why, one step back1213 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1214–1221why, one step back1214 }12151216 /**1217 * Once we have a promise we chain, but call synchronously until then.1218 *1219 * @param {Promise|undefined} promise1220 * @param {Function} fn1221 * @return {Promise|undefined}Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1222why, one step back1222 * @api privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1223–1245why, one step back1223 */12241225 _chainOrCall(promise, fn) {1226 // thenable1227 if (promise && promise.then && typeof promise.then === 'function') {1228 // already have a promise, chain callback1229 return promise.then(() => fn());1230 }1231 // callback might return a promise1232 return fn();1233 }12341235 /**1236 *1237 * @param {Promise|undefined} promise1238 * @param {string} event1239 * @return {Promise|undefined}1240 * @api private1241 */12421243 _chainOrCallHooks(promise, event) {1244 let result = promise;1245 const hooks = [];Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1246why, one step back1246 this._getCommandAndAncestors()Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1247–1262why, one step back1247 .reverse()1248 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1249 .forEach(hookedCommand => {1250 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1251 hooks.push({ hookedCommand, callback });1252 });1253 });1254 if (event === 'postAction') {1255 hooks.reverse();1256 }12571258 hooks.forEach((hookDetail) => {1259 result = this._chainOrCall(result, () => {1260 return hookDetail.callback(hookDetail.hookedCommand, this);1261 });1262 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1263–1283why, one step back1263 return result;1264 }12651266 /**1267 *1268 * @param {Promise|undefined} promise1269 * @param {Command} subCommand1270 * @param {string} event1271 * @return {Promise|undefined}1272 * @api private1273 */12741275 _chainOrCallSubCommandHook(promise, subCommand, event) {1276 let result = promise;1277 if (this._lifeCycleHooks[event] !== undefined) {1278 this._lifeCycleHooks[event].forEach((hook) => {1279 result = this._chainOrCall(result, () => {1280 return hook(this, subCommand);1281 });1282 });1283 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1284–1295why, one step back1284 return result;1285 }12861287 /**1288 * Process arguments in context of this command.1289 * Returns action result, in case it is a promise.1290 *1291 * @api private1292 */12931294 _parseCommand(operands, unknown) {1295 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1296why, one step back1296 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1297why, one step back1297 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1298–1305why, one step back1298 operands = operands.concat(parsed.operands);1299 unknown = parsed.unknown;1300 this.args = operands.concat(unknown);13011302 if (operands && this._findCommand(operands[0])) {1303 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1304 }1305 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1306why, one step back1306 return this._dispatchHelpCommand(operands[1]);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1307–1318why, one step back1307 }1308 if (this._defaultCommandName) {1309 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1310 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1311 }1312 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1313 // probably missing subcommand and no handler, user needs help (and exit)1314 this.help({ error: true });1315 }13161317 outputHelpIfRequested(this, parsed.unknown);1318 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1319why, one step back1319 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1320–1330why, one step back13201321 // We do not always call this check to avoid masking a "better" error, like unknown command.1322 const checkForUnknownOptions = () => {1323 if (parsed.unknown.length > 0) {1324 this.unknownOption(parsed.unknown[0]);1325 }1326 };13271328 const commandEvent = `command:${this.name()}`;1329 if (this._actionHandler) {1330 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1331why, one step back1331 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1332why, one step back1332Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1333–1335why, one step back1333 let promiseChain;1334 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1335 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1336why, one step back1336 if (this.parent) {Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1337why, one step back1337 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1338–1340why, one step back1338 this.parent.emit(commandEvent, operands, unknown); // legacy1339 });1340 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1341–1342why, one step back1341 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1342 return promiseChain;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1343–1345why, one step back1343 }1344 if (this.parent && this.parent.listenerCount(commandEvent)) {1345 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1346why, one step back1346 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1347–1358why, one step back1347 this.parent.emit(commandEvent, operands, unknown); // legacy1348 } else if (operands.length) {1349 if (this._findCommand('*')) { // legacy default command1350 return this._dispatchSubcommand('*', operands, unknown);1351 }1352 if (this.listenerCount('command:*')) {1353 // skip option check, emit event for possible misspelling suggestion1354 this.emit('command:*', operands, unknown);1355 } else if (this.commands.length) {1356 this.unknownCommand();1357 } else {1358 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1359why, one step back1359 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1360–1361why, one step back1360 }1361 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1362why, one step back1362 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1363–1366why, one step back1363 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1364 this.help({ error: true });1365 } else {1366 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1367why, one step back1367 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1368–1369why, one step back1368 // fall through for caller to handle after calling .parse()1369 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1370why, one step back1370 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1371–1379why, one step back13711372 /**1373 * Find matching command.1374 *1375 * @api private1376 */1377 _findCommand(name) {1378 if (!name) return undefined;1379 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1380why, one step back1380 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1381–1391why, one step back13811382 /**1383 * Return an option matching `arg` if any.1384 *1385 * @param {string} arg1386 * @return {Option}1387 * @api private1388 */13891390 _findOption(arg) {1391 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1392why, one step back1392 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1393–1395why, one step back13931394 /**1395 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1396why, one step back1396 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1397–1402why, one step back1397 *1398 * @api private1399 */14001401 _checkForMissingMandatoryOptions() {1402 // Walk up hierarchy so can call in subcommand after checking for displaying help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1403why, one step back1403 this._getCommandAndAncestors().forEach((cmd) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1404–1408why, one step back1404 cmd.options.forEach((anOption) => {1405 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1406 cmd.missingMandatoryOptionValue(anOption);1407 }1408 });Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1409why, one step back1409 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1410why, one step back1410 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1411–1412why, one step back14111412 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1413why, one step back1413 * 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 1414–1416why, one step back1414 *1415 * @api private1416 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1417why, one step back1417 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1418–1439why, one step back1418 const definedNonDefaultOptions = this.options.filter(1419 (option) => {1420 const optionKey = option.attributeName();1421 if (this.getOptionValue(optionKey) === undefined) {1422 return false;1423 }1424 return this.getOptionValueSource(optionKey) !== 'default';1425 }1426 );14271428 const optionsWithConflicting = definedNonDefaultOptions.filter(1429 (option) => option.conflictsWith.length > 01430 );14311432 optionsWithConflicting.forEach((option) => {1433 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1434 option.conflictsWith.includes(defined.attributeName())1435 );1436 if (conflictingAndDefined) {1437 this._conflictingOption(option, conflictingAndDefined);1438 }1439 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1440–1449why, one step back1440 }14411442 /**1443 * Display an error message if conflicting options are used together.1444 * Called after checking for help flags in leaf subcommand.1445 *1446 * @api private1447 */1448 _checkForConflictingOptions() {1449 // Walk up hierarchy so can call in subcommand after checking for displaying help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1450why, one step back1450 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1451why, one step back1451 cmd._checkForConflictingLocalOptions();Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1452why, one step back1452 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1453–1455why, one step back1453 }14541455 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1456–1460why, one step back1456 * Parse options from `argv` removing known options,1457 * and return argv split into operands and unknown arguments.1458 *1459 * Examples:1460 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1461–1465why, one step back1461 * argv => operands, unknown1462 * --known kkk op => [op], []1463 * op --known kkk => [op], []1464 * sub --unknown uuu op => [sub], [--unknown uuu op]1465 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1466–1584why, one step back1466 *1467 * @param {String[]} argv1468 * @return {{operands: String[], unknown: String[]}}1469 */14701471 parseOptions(argv) {1472 const operands = []; // operands, not options or values1473 const unknown = []; // first unknown option and remaining unknown args1474 let dest = operands;1475 const args = argv.slice();14761477 function maybeOption(arg) {1478 return arg.length > 1 && arg[0] === '-';1479 }14801481 // parse options1482 let activeVariadicOption = null;1483 while (args.length) {1484 const arg = args.shift();14851486 // literal1487 if (arg === '--') {1488 if (dest === unknown) dest.push(arg);1489 dest.push(...args);1490 break;1491 }14921493 if (activeVariadicOption && !maybeOption(arg)) {1494 this.emit(`option:${activeVariadicOption.name()}`, arg);1495 continue;1496 }1497 activeVariadicOption = null;14981499 if (maybeOption(arg)) {1500 const option = this._findOption(arg);1501 // recognised option, call listener to assign value with possible custom processing1502 if (option) {1503 if (option.required) {1504 const value = args.shift();1505 if (value === undefined) this.optionMissingArgument(option);1506 this.emit(`option:${option.name()}`, value);1507 } else if (option.optional) {1508 let value = null;1509 // historical behaviour is optional value is following arg unless an option1510 if (args.length > 0 && !maybeOption(args[0])) {1511 value = args.shift();1512 }1513 this.emit(`option:${option.name()}`, value);1514 } else { // boolean flag1515 this.emit(`option:${option.name()}`);1516 }1517 activeVariadicOption = option.variadic ? option : null;1518 continue;1519 }1520 }15211522 // Look for combo options following single dash, eat first one if known.1523 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1524 const option = this._findOption(`-${arg[1]}`);1525 if (option) {1526 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1527 // option with value following in same argument1528 this.emit(`option:${option.name()}`, arg.slice(2));1529 } else {1530 // boolean option, emit and put back remainder of arg for further processing1531 this.emit(`option:${option.name()}`);1532 args.unshift(`-${arg.slice(2)}`);1533 }1534 continue;1535 }1536 }15371538 // Look for known long flag with value, like --foo=bar1539 if (/^--[^=]+=/.test(arg)) {1540 const index = arg.indexOf('=');1541 const option = this._findOption(arg.slice(0, index));1542 if (option && (option.required || option.optional)) {1543 this.emit(`option:${option.name()}`, arg.slice(index + 1));1544 continue;1545 }1546 }15471548 // Not a recognised option by this command.1549 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15501551 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1552 if (maybeOption(arg)) {1553 dest = unknown;1554 }15551556 // If using positionalOptions, stop processing our options at subcommand.1557 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1558 if (this._findCommand(arg)) {1559 operands.push(arg);1560 if (args.length > 0) unknown.push(...args);1561 break;1562 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1563 operands.push(arg);1564 if (args.length > 0) operands.push(...args);1565 break;1566 } else if (this._defaultCommandName) {1567 unknown.push(arg);1568 if (args.length > 0) unknown.push(...args);1569 break;1570 }1571 }15721573 // If using passThroughOptions, stop processing options at first command-argument.1574 if (this._passThroughOptions) {1575 dest.push(arg);1576 if (args.length > 0) dest.push(...args);1577 break;1578 }15791580 // add arg1581 dest.push(arg);1582 }15831584 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1585why, one step back1585 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1586–1587why, one step back15861587 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1588why, one step back1588 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1589–1605why, one step back1589 *1590 * @return {Object}1591 */1592 opts() {1593 if (this._storeOptionsAsProperties) {1594 // Preserve original behaviour so backwards compatible when still using properties1595 const result = {};1596 const len = this.options.length;15971598 for (let i = 0; i < len; i++) {1599 const key = this.options[i].attributeName();1600 result[key] = key === this._versionOptionName ? this._version : this[key];1601 }1602 return result;1603 }16041605 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1606why, one step back1606 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1607–1608why, one step back16071608 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1609why, one step back1609 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1610why, one step back1610 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1611why, one step back1611 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1612why, one step back1612 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1613–1614why, one step back1613 optsWithGlobals() {1614 // globals overwrite localsMerge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1615why, one step back1615 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1616–1630why, one step back1616 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1617 {}1618 );1619 }16201621 /**1622 * Display error message and exit (or call exitOverride).1623 *1624 * @param {string} message1625 * @param {Object} [errorOptions]1626 * @param {string} [errorOptions.code] - an id string representing the error1627 * @param {number} [errorOptions.exitCode] - used with process.exit1628 */1629 error(message, errorOptions) {1630 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1631why, one step back1631 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1632–1637why, one step back1632 if (typeof this._showHelpAfterError === 'string') {1633 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1634 } else if (this._showHelpAfterError) {1635 this._outputConfiguration.writeErr('\n');1636 this.outputHelp({ error: true });1637 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1638–1642why, one step back16381639 // exit handling1640 const config = errorOptions || {};1641 const exitCode = config.exitCode || 1;1642 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1643why, one step back1643 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1644–1655why, one step back1644 }16451646 /**1647 * Apply any option related environment variables, if option does1648 * not have a value from cli or client code.1649 *1650 * @api private1651 */1652 _parseOptionsEnv() {1653 this.options.forEach((option) => {1654 if (option.envVar && option.envVar in process.env) {1655 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1656–1657why, one step back1656 // Priority check. Do not overwrite cli or options from unknown source (client-code).1657 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 1658–1667why, one step back1658 if (option.required || option.optional) { // option can take a value1659 // keep very simple, optional always takes value1660 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1661 } else { // boolean1662 // keep very simple, only care that envVar defined and not the value1663 this.emit(`optionEnv:${option.name()}`);1664 }1665 }1666 }1667 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1668–1690why, one step back1668 }16691670 /**1671 * Apply any implied option values, if option is undefined or default value.1672 *1673 * @api private1674 */1675 _parseOptionsImplied() {1676 const dualHelper = new DualOptions(this.options);1677 const hasCustomOptionValue = (optionKey) => {1678 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1679 };1680 this.options1681 .filter(option => (option.implied !== undefined) &&1682 hasCustomOptionValue(option.attributeName()) &&1683 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1684 .forEach((option) => {1685 Object.keys(option.implied)1686 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1687 .forEach(impliedKey => {1688 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1689 });1690 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1691–1701why, one step back1691 }16921693 /**1694 * Argument `name` is missing.1695 *1696 * @param {string} name1697 * @api private1698 */16991700 missingArgument(name) {1701 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1702–1703why, one step back1702 this.error(message, { code: 'commander.missingArgument' });1703 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1704–1713why, one step back17041705 /**1706 * `Option` is missing an argument.1707 *1708 * @param {Option} option1709 * @api private1710 */17111712 optionMissingArgument(option) {1713 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1714–1715why, one step back1714 this.error(message, { code: 'commander.optionMissingArgument' });1715 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1716–1725why, one step back17161717 /**1718 * `Option` does not have a value, and is a mandatory option.1719 *1720 * @param {Option} option1721 * @api private1722 */17231724 missingMandatoryOptionValue(option) {1725 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1726why, one step back1726 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1727–1764why, one step back1727 }17281729 /**1730 * `Option` conflicts with another option.1731 *1732 * @param {Option} option1733 * @param {Option} conflictingOption1734 * @api private1735 */1736 _conflictingOption(option, conflictingOption) {1737 // The calling code does not know whether a negated option is the source of the1738 // value, so do some work to take an educated guess.1739 const findBestOptionFromValue = (option) => {1740 const optionKey = option.attributeName();1741 const optionValue = this.getOptionValue(optionKey);1742 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1743 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1744 if (negativeOption && (1745 (negativeOption.presetArg === undefined && optionValue === false) ||1746 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1747 )) {1748 return negativeOption;1749 }1750 return positiveOption || option;1751 };17521753 const getErrorMessage = (option) => {1754 const bestOption = findBestOptionFromValue(option);1755 const optionKey = bestOption.attributeName();1756 const source = this.getOptionValueSource(optionKey);1757 if (source === 'env') {1758 return `environment variable '${bestOption.envVar}'`;1759 }1760 return `option '${bestOption.flags}'`;1761 };17621763 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1764 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1765why, one step back1765 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1766–1775why, one step back17661767 /**1768 * Unknown option `flag`.1769 *1770 * @param {string} flag1771 * @api private1772 */17731774 unknownOption(flag) {1775 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1776–1792why, one step back1776 let suggestion = '';17771778 if (flag.startsWith('--') && this._showSuggestionAfterError) {1779 // Looping to pick up the global options too1780 let candidateFlags = [];1781 let command = this;1782 do {1783 const moreFlags = command.createHelp().visibleOptions(command)1784 .filter(option => option.long)1785 .map(option => option.long);1786 candidateFlags = candidateFlags.concat(moreFlags);1787 command = command.parent;1788 } while (command && !command._enablePositionalOptions);1789 suggestion = suggestSimilar(flag, candidateFlags);1790 }17911792 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1793–1794why, one step back1793 this.error(message, { code: 'commander.unknownOption' });1794 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1795–1809why, one step back17951796 /**1797 * Excess arguments, more than expected.1798 *1799 * @param {string[]} receivedArgs1800 * @api private1801 */18021803 _excessArguments(receivedArgs) {1804 if (this._allowExcessArguments) return;18051806 const expected = this._args.length;1807 const s = (expected === 1) ? '' : 's';1808 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1809 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 1810–1811why, one step back1810 this.error(message, { code: 'commander.excessArguments' });1811 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1812–1819why, one step back18121813 /**1814 * Unknown command.1815 *1816 * @api private1817 */18181819 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1820–1833why, one step back1820 const unknownName = this.args[0];1821 let suggestion = '';18221823 if (this._showSuggestionAfterError) {1824 const candidateNames = [];1825 this.createHelp().visibleCommands(this).forEach((command) => {1826 candidateNames.push(command.name());1827 // just visible alias1828 if (command.alias()) candidateNames.push(command.alias());1829 });1830 suggestion = suggestSimilar(unknownName, candidateNames);1831 }18321833 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1834–1835why, one step back1834 this.error(message, { code: 'commander.unknownCommand' });1835 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1836–1837why, one step back18361837 /**Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1838why, one step back1838 * Get or set the program version.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1839why, one step back1839 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1840why, one step back1840 * This method auto-registers the "-V, --version" option which will print the version number.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1841why, one step back1841 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1842why, one step back1842 * You can optionally supply the flags and description to override the defaults.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1843why, one step back1843 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1844why, one step back1844 * @param {string} [str]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1845–1846why, one step back1845 * @param {string} [flags]1846 * @param {string} [description]Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1847why, one step back1847 * @return {this | string | undefined} `this` command for chaining, or version string if no argumentsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1848–1855why, one step back1848 */18491850 version(str, flags, description) {1851 if (str === undefined) return this._version;1852 this._version = str;1853 flags = flags || '-V, --version';1854 description = description || 'output the version number';1855 const versionOption = this.createOption(flags, description);Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1856why, one step back1856 this._versionOptionName = versionOption.attributeName(); // [sic] not defined in constructor, partly legacy, partly only needed at rootRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1857–1862why, one step back1857 this.options.push(versionOption);1858 this.on('option:' + versionOption.name(), () => {1859 this._outputConfiguration.writeOut(`${str}\n`);1860 this._exit(0, 'commander.version', str);1861 });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 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1866why, one step back1866 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1867–1877why, one step back1867 *1868 * @param {string} [str]1869 * @param {Object} [argsDescription]1870 * @return {string|Command}1871 */1872 description(str, argsDescription) {1873 if (str === undefined && argsDescription === undefined) return this._description;1874 this._description = str;1875 if (argsDescription) {1876 this._argsDescription = argsDescription;1877 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1878–1889why, one step back1878 return this;1879 }18801881 /**1882 * Set the summary. Used when listed as subcommand of parent.1883 *1884 * @param {string} [str]1885 * @return {string|Command}1886 */1887 summary(str) {1888 if (str === undefined) return this._summary;1889 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1890why, one step back1890 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1891why, one step back1891 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1892–1904why, one step back18921893 /**1894 * Set an alias for the command.1895 *1896 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1897 *1898 * @param {string} [alias]1899 * @return {string|Command}1900 */19011902 alias(alias) {1903 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1904Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1905why, one step back1905 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1906–1915why, one step back1906 let command = this;1907 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1908 // assume adding alias for last added executable subcommand, rather than this1909 command = this.commands[this.commands.length - 1];1910 }19111912 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');19131914 command._aliases.push(alias);1915 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1916why, one step back1916 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1917–1932why, one step back19171918 /**1919 * Set aliases for the command.1920 *1921 * Only the first alias is shown in the auto-generated help.1922 *1923 * @param {string[]} [aliases]1924 * @return {string[]|Command}1925 */19261927 aliases(aliases) {1928 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1929 if (aliases === undefined) return this._aliases;19301931 aliases.forEach((alias) => this.alias(alias));1932 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1933why, one step back1933 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1934–1957why, one step back19341935 /**1936 * Set / get the command usage `str`.1937 *1938 * @param {string} [str]1939 * @return {String|Command}1940 */19411942 usage(str) {1943 if (str === undefined) {1944 if (this._usage) return this._usage;19451946 const args = this._args.map((arg) => {1947 return humanReadableArgName(arg);1948 });1949 return [].concat(1950 (this.options.length || this._hasHelpOption ? '[options]' : []),1951 (this.commands.length ? '[command]' : []),1952 (this._args.length ? args : [])1953 ).join(' ');1954 }19551956 this._usage = str;1957 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1958why, one step back1958 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1959–1960why, one step back19591960 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1961why, one step back1961 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1962–1970why, one step back1962 *1963 * @param {string} [str]1964 * @return {string|Command}1965 */19661967 name(str) {1968 if (str === undefined) return this._name;1969 this._name = str;1970 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1971why, one step back1971 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1972–1973why, one step back19721973 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1974–2000why, one step back1974 * Set the name of the command from script filename, such as process.argv[1],1975 * or require.main.filename, or __filename.1976 *1977 * (Used internally and public although not documented in README.)1978 *1979 * @example1980 * program.nameFromFilename(require.main.filename);1981 *1982 * @param {string} filename1983 * @return {Command}1984 */19851986 nameFromFilename(filename) {1987 this._name = path.basename(filename, path.extname(filename));19881989 return this;1990 }19911992 /**1993 * Get or set the directory for searching for executable subcommands of this command.1994 *1995 * @example1996 * program.executableDir(__dirname);1997 * // or1998 * program.executableDir('subcommands');1999 *2000 * @param {string} [path]The first 2,000 of 2,218 lines.