Skip to content
Myr

Refactor classes into files (#1522)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Factor out Argument class * Factor out error and option and utility * Add lib to run-scripts * Factor out Help * Factor out Command * Include lib in pack files

authored by John Gee · committed by GitHub · parent ff7658c · Browse files · 7 files+2539 added−2500 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+2539 added−2500 removed

  • other:+2539 added−2500 removed

7 files+2539 added−2500 removed

added:lib/argument.js+95 added
1// @ts-check23class Argument {4 /**5 * Initialize a new command argument with the given name and description.6 * The default is that the argument is required, and you can explicitly7 * indicate this with <> around the name. Put [] around the name for an optional argument.8 *9 * @param {string} name10 * @param {string} [description]11 */1213 constructor(name, description) {14 this.description = description || '';15 this.variadic = false;16 this.parseArg = undefined;17 this.defaultValue = undefined;18 this.defaultValueDescription = undefined;1920 switch (name[0]) {21 case '<': // e.g. <required>22 this.required = true;23 this._name = name.slice(1, -1);24 break;25 case '[': // e.g. [optional]26 this.required = false;27 this._name = name.slice(1, -1);28 break;29 default:30 this.required = true;31 this._name = name;32 break;33 }3435 if (this._name.length > 3 && this._name.slice(-3) === '...') {36 this.variadic = true;37 this._name = this._name.slice(0, -3);38 }39 }4041 /**42 * Return argument name.43 *44 * @return {string}45 */4647 name() {48 return this._name;49 };5051 /**52 * Set the default value, and optionally supply the description to be displayed in the help.53 *54 * @param {any} value55 * @param {string} [description]56 * @return {Argument}57 */5859 default(value, description) {60 this.defaultValue = value;61 this.defaultValueDescription = description;62 return this;63 };6465 /**66 * Set the custom handler for processing CLI command arguments into argument values.67 *68 * @param {Function} [fn]69 * @return {Argument}70 */7172 argParser(fn) {73 this.parseArg = fn;74 return this;75 };76}7778/**79 * Takes an argument and returns its human readable equivalent for help usage.80 *81 * @param {Argument} arg82 * @return {string}83 * @api private84 */8586function humanReadableArgName(arg) {87 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');8889 return arg.required90 ? '<' + nameOutput + '>'91 : '[' + nameOutput + ']';92}9394exports.Argument = Argument;95exports.humanReadableArgName = humanReadableArgName;
added:lib/command.js+1810 added
1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');56const { Argument, humanReadableArgName } = require('./argument.js');7const { CommanderError } = require('./error.js');8const { Help } = require('./help.js');9const { Option, splitOptionFlags } = require('./option.js');1011// @ts-check1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 this.commands = [];23 this.options = [];24 this.parent = null;25 this._allowUnknownOption = false;26 this._allowExcessArguments = true;27 this._args = [];28 this.rawArgs = null;29 this._scriptPath = null;30 this._name = name || '';31 this._optionValues = {};32 this._storeOptionsAsProperties = false;33 this._actionHandler = null;34 this._executableHandler = false;35 this._executableFile = null; // custom name for executable36 this._defaultCommandName = null;37 this._exitCallback = null;38 this._aliases = [];39 this._combineFlagAndOptionalValue = true;40 this._description = '';41 this._argsDescription = undefined; // legacy42 this._enablePositionalOptions = false;43 this._passThroughOptions = false;44 this._lifeCycleHooks = {}; // a hash of arrays4546 // see .configureOutput() for docs47 this._outputConfiguration = {48 writeOut: (str) => process.stdout.write(str),49 writeErr: (str) => process.stderr.write(str),50 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,51 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,52 outputError: (str, write) => write(str)53 };5455 this._hidden = false;56 this._hasHelpOption = true;57 this._helpFlags = '-h, --help';58 this._helpDescription = 'display help for command';59 this._helpShortFlag = '-h';60 this._helpLongFlag = '--help';61 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false62 this._helpCommandName = 'help';63 this._helpCommandnameAndArgs = 'help [command]';64 this._helpCommandDescription = 'display help for command';65 this._helpConfiguration = {};66 }6768 /**69 * Define a command.70 *71 * There are two styles of command: pay attention to where to put the description.72 *73 * Examples:74 *75 * // Command implemented using action handler (description is supplied separately to `.command`)76 * program77 * .command('clone <source> [destination]')78 * .description('clone a repository into a newly created directory')79 * .action((source, destination) => {80 * console.log('clone command called');81 * });82 *83 * // Command implemented using separate executable file (description is second parameter to `.command`)84 * program85 * .command('start <service>', 'start named service')86 * .command('stop [service]', 'stop named service, or all if no name supplied');87 *88 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`89 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)90 * @param {Object} [execOpts] - configuration options (for executable)91 * @return {Command} returns new command for action handler, or `this` for executable command92 */9394 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {95 let desc = actionOptsOrExecDesc;96 let opts = execOpts;97 if (typeof desc === 'object' && desc !== null) {98 opts = desc;99 desc = null;100 }101 opts = opts || {};102 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);103 const cmd = this.createCommand(name);104105 if (desc) {106 cmd.description(desc);107 cmd._executableHandler = true;108 }109 if (opts.isDefault) this._defaultCommandName = cmd._name;110111 cmd._outputConfiguration = this._outputConfiguration;112113 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden114 cmd._hasHelpOption = this._hasHelpOption;115 cmd._helpFlags = this._helpFlags;116 cmd._helpDescription = this._helpDescription;117 cmd._helpShortFlag = this._helpShortFlag;118 cmd._helpLongFlag = this._helpLongFlag;119 cmd._helpCommandName = this._helpCommandName;120 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;121 cmd._helpCommandDescription = this._helpCommandDescription;122 cmd._helpConfiguration = this._helpConfiguration;123 cmd._exitCallback = this._exitCallback;124 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;125 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;126 cmd._allowExcessArguments = this._allowExcessArguments;127 cmd._enablePositionalOptions = this._enablePositionalOptions;128129 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor130 if (args) cmd.arguments(args);131 this.commands.push(cmd);132 cmd.parent = this;133134 if (desc) return this;135 return cmd;136 };137138 /**139 * Factory routine to create a new unattached command.140 *141 * See .command() for creating an attached subcommand, which uses this routine to142 * create the command. You can override createCommand to customise subcommands.143 *144 * @param {string} [name]145 * @return {Command} new command146 */147148 createCommand(name) {149 return new Command(name);150 };151152 /**153 * You can customise the help with a subclass of Help by overriding createHelp,154 * or by overriding Help properties using configureHelp().155 *156 * @return {Help}157 */158159 createHelp() {160 return Object.assign(new Help(), this.configureHelp());161 };162163 /**164 * You can customise the help by overriding Help properties using configureHelp(),165 * or with a subclass of Help by overriding createHelp().166 *167 * @param {Object} [configuration] - configuration options168 * @return {Command|Object} `this` command for chaining, or stored configuration169 */170171 configureHelp(configuration) {172 if (configuration === undefined) return this._helpConfiguration;173174 this._helpConfiguration = configuration;175 return this;176 }177178 /**179 * The default output goes to stdout and stderr. You can customise this for special180 * applications. You can also customise the display of errors by overriding outputError.181 *182 * The configuration properties are all functions:183 *184 * // functions to change where being written, stdout and stderr185 * writeOut(str)186 * writeErr(str)187 * // matching functions to specify width for wrapping help188 * getOutHelpWidth()189 * getErrHelpWidth()190 * // functions based on what is being written out191 * outputError(str, write) // used for displaying errors, and not used for displaying help192 *193 * @param {Object} [configuration] - configuration options194 * @return {Command|Object} `this` command for chaining, or stored configuration195 */196197 configureOutput(configuration) {198 if (configuration === undefined) return this._outputConfiguration;199200 Object.assign(this._outputConfiguration, configuration);201 return this;202 }203204 /**205 * Add a prepared subcommand.206 *207 * See .command() for creating an attached subcommand which inherits settings from its parent.208 *209 * @param {Command} cmd - new subcommand210 * @param {Object} [opts] - configuration options211 * @return {Command} `this` command for chaining212 */213214 addCommand(cmd, opts) {215 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');216217 // To keep things simple, block automatic name generation for deeply nested executables.218 // Fail fast and detect when adding rather than later when parsing.219 function checkExplicitNames(commandArray) {220 commandArray.forEach((cmd) => {221 if (cmd._executableHandler && !cmd._executableFile) {222 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);223 }224 checkExplicitNames(cmd.commands);225 });226 }227 checkExplicitNames(cmd.commands);228229 opts = opts || {};230 if (opts.isDefault) this._defaultCommandName = cmd._name;231 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation232233 this.commands.push(cmd);234 cmd.parent = this;235 return this;236 };237238 /**239 * Factory routine to create a new unattached argument.240 *241 * See .argument() for creating an attached argument, which uses this routine to242 * create the argument. You can override createArgument to return a custom argument.243 *244 * @param {string} name245 * @param {string} [description]246 * @return {Argument} new argument247 */248249 createArgument(name, description) {250 return new Argument(name, description);251 };252253 /**254 * Define argument syntax for command.255 *256 * The default is that the argument is required, and you can explicitly257 * indicate this with <> around the name. Put [] around the name for an optional argument.258 *259 * @example260 *261 * program.argument('<input-file>');262 * program.argument('[output-file]');263 *264 * @param {string} name265 * @param {string} [description]266 * @param {Function|*} [fn] - custom argument processing function267 * @param {*} [defaultValue]268 * @return {Command} `this` command for chaining269 */270 argument(name, description, fn, defaultValue) {271 const argument = this.createArgument(name, description);272 if (typeof fn === 'function') {273 argument.default(defaultValue).argParser(fn);274 } else {275 argument.default(fn);276 }277 this.addArgument(argument);278 return this;279 }280281 /**282 * Define argument syntax for command, adding multiple at once (without descriptions).283 *284 * See also .argument().285 *286 * @example287 *288 * program.arguments('<cmd> [env]');289 *290 * @param {string} names291 * @return {Command} `this` command for chaining292 */293294 arguments(names) {295 names.split(/ +/).forEach((detail) => {296 this.argument(detail);297 });298 return this;299 };300301 /**302 * Define argument syntax for command, adding a prepared argument.303 *304 * @param {Argument} argument305 * @return {Command} `this` command for chaining306 */307 addArgument(argument) {308 const previousArgument = this._args.slice(-1)[0];309 if (previousArgument && previousArgument.variadic) {310 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);311 }312 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {313 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);314 }315 this._args.push(argument);316 return this;317 }318319 /**320 * Override default decision whether to add implicit help command.321 *322 * addHelpCommand() // force on323 * addHelpCommand(false); // force off324 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details325 *326 * @return {Command} `this` command for chaining327 */328329 addHelpCommand(enableOrNameAndArgs, description) {330 if (enableOrNameAndArgs === false) {331 this._addImplicitHelpCommand = false;332 } else {333 this._addImplicitHelpCommand = true;334 if (typeof enableOrNameAndArgs === 'string') {335 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];336 this._helpCommandnameAndArgs = enableOrNameAndArgs;337 }338 this._helpCommandDescription = description || this._helpCommandDescription;339 }340 return this;341 };342343 /**344 * @return {boolean}345 * @api private346 */347348 _hasImplicitHelpCommand() {349 if (this._addImplicitHelpCommand === undefined) {350 return this.commands.length && !this._actionHandler && !this._findCommand('help');351 }352 return this._addImplicitHelpCommand;353 };354355 /**356 * Add hook for life cycle event.357 *358 * @param {string} event359 * @param {Function} listener360 * @return {Command} `this` command for chaining361 */362363 hook(event, listener) {364 const allowedValues = ['preAction', 'postAction'];365 if (!allowedValues.includes(event)) {366 throw new Error(`Unexpected value for event passed to hook : '${event}'.367Expecting one of '${allowedValues.join("', '")}'`);368 }369 if (this._lifeCycleHooks[event]) {370 this._lifeCycleHooks[event].push(listener);371 } else {372 this._lifeCycleHooks[event] = [listener];373 }374 return this;375 }376377 /**378 * Register callback to use as replacement for calling process.exit.379 *380 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing381 * @return {Command} `this` command for chaining382 */383384 exitOverride(fn) {385 if (fn) {386 this._exitCallback = fn;387 } else {388 this._exitCallback = (err) => {389 if (err.code !== 'commander.executeSubCommandAsync') {390 throw err;391 } else {392 // Async callback from spawn events, not useful to throw.393 }394 };395 }396 return this;397 };398399 /**400 * Call process.exit, and _exitCallback if defined.401 *402 * @param {number} exitCode exit code for using with process.exit403 * @param {string} code an id string representing the error404 * @param {string} message human-readable description of the error405 * @return never406 * @api private407 */408409 _exit(exitCode, code, message) {410 if (this._exitCallback) {411 this._exitCallback(new CommanderError(exitCode, code, message));412 // Expecting this line is not reached.413 }414 process.exit(exitCode);415 };416417 /**418 * Register callback `fn` for the command.419 *420 * Examples:421 *422 * program423 * .command('help')424 * .description('display verbose help')425 * .action(function() {426 * // output help here427 * });428 *429 * @param {Function} fn430 * @return {Command} `this` command for chaining431 */432433 action(fn) {434 const listener = (args) => {435 // The .action callback takes an extra parameter which is the command or options.436 const expectedArgsCount = this._args.length;437 const actionArgs = args.slice(0, expectedArgsCount);438 if (this._storeOptionsAsProperties) {439 actionArgs[expectedArgsCount] = this; // backwards compatible "options"440 } else {441 actionArgs[expectedArgsCount] = this.opts();442 }443 actionArgs.push(this);444445 return fn.apply(this, actionArgs);446 };447 this._actionHandler = listener;448 return this;449 };450451 /**452 * Factory routine to create a new unattached option.453 *454 * See .option() for creating an attached option, which uses this routine to455 * create the option. You can override createOption to return a custom option.456 *457 * @param {string} flags458 * @param {string} [description]459 * @return {Option} new option460 */461462 createOption(flags, description) {463 return new Option(flags, description);464 };465466 /**467 * Add an option.468 *469 * @param {Option} option470 * @return {Command} `this` command for chaining471 */472 addOption(option) {473 const oname = option.name();474 const name = option.attributeName();475476 let defaultValue = option.defaultValue;477478 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value479 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {480 // when --no-foo we make sure default is true, unless a --foo option is already defined481 if (option.negate) {482 const positiveLongFlag = option.long.replace(/^--no-/, '--');483 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;484 }485 // preassign only if we have a default486 if (defaultValue !== undefined) {487 this.setOptionValue(name, defaultValue);488 }489 }490491 // register the option492 this.options.push(option);493494 // when it's passed assign the value495 // and conditionally invoke the callback496 this.on('option:' + oname, (val) => {497 const oldValue = this.getOptionValue(name);498499 // custom processing500 if (val !== null && option.parseArg) {501 try {502 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);503 } catch (err) {504 if (err.code === 'commander.invalidArgument') {505 const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;506 this._displayError(err.exitCode, err.code, message);507 }508 throw err;509 }510 } else if (val !== null && option.variadic) {511 val = option._concatValue(val, oldValue);512 }513514 // unassigned or boolean value515 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {516 // if no value, negate false, and we have a default, then use it!517 if (val == null) {518 this.setOptionValue(name, option.negate519 ? false520 : defaultValue || true);521 } else {522 this.setOptionValue(name, val);523 }524 } else if (val !== null) {525 // reassign526 this.setOptionValue(name, option.negate ? false : val);527 }528 });529530 return this;531 }532533 /**534 * Internal implementation shared by .option() and .requiredOption()535 *536 * @api private537 */538 _optionEx(config, flags, description, fn, defaultValue) {539 const option = this.createOption(flags, description);540 option.makeOptionMandatory(!!config.mandatory);541 if (typeof fn === 'function') {542 option.default(defaultValue).argParser(fn);543 } else if (fn instanceof RegExp) {544 // deprecated545 const regex = fn;546 fn = (val, def) => {547 const m = regex.exec(val);548 return m ? m[0] : def;549 };550 option.default(defaultValue).argParser(fn);551 } else {552 option.default(fn);553 }554555 return this.addOption(option);556 }557558 /**559 * Define option with `flags`, `description` and optional560 * coercion `fn`.561 *562 * The `flags` string contains the short and/or long flags,563 * separated by comma, a pipe or space. The following are all valid564 * all will output this way when `--help` is used.565 *566 * "-p, --pepper"567 * "-p|--pepper"568 * "-p --pepper"569 *570 * Examples:571 *572 * // simple boolean defaulting to undefined573 * program.option('-p, --pepper', 'add pepper');574 *575 * program.pepper576 * // => undefined577 *578 * --pepper579 * program.pepper580 * // => true581 *582 * // simple boolean defaulting to true (unless non-negated option is also defined)583 * program.option('-C, --no-cheese', 'remove cheese');584 *585 * program.cheese586 * // => true587 *588 * --no-cheese589 * program.cheese590 * // => false591 *592 * // required argument593 * program.option('-C, --chdir <path>', 'change the working directory');594 *595 * --chdir /tmp596 * program.chdir597 * // => "/tmp"598 *599 * // optional argument600 * program.option('-c, --cheese [type]', 'add cheese [marble]');601 *602 * @param {string} flags603 * @param {string} [description]604 * @param {Function|*} [fn] - custom option processing function or default value605 * @param {*} [defaultValue]606 * @return {Command} `this` command for chaining607 */608609 option(flags, description, fn, defaultValue) {610 return this._optionEx({}, flags, description, fn, defaultValue);611 };612613 /**614 * Add a required option which must have a value after parsing. This usually means615 * the option must be specified on the command line. (Otherwise the same as .option().)616 *617 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.618 *619 * @param {string} flags620 * @param {string} [description]621 * @param {Function|*} [fn] - custom option processing function or default value622 * @param {*} [defaultValue]623 * @return {Command} `this` command for chaining624 */625626 requiredOption(flags, description, fn, defaultValue) {627 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);628 };629630 /**631 * Alter parsing of short flags with optional values.632 *633 * Examples:634 *635 * // for `.option('-f,--flag [value]'):636 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour637 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`638 *639 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.640 */641 combineFlagAndOptionalValue(combine = true) {642 this._combineFlagAndOptionalValue = !!combine;643 return this;644 };645646 /**647 * Allow unknown options on the command line.648 *649 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown650 * for unknown options.651 */652 allowUnknownOption(allowUnknown = true) {653 this._allowUnknownOption = !!allowUnknown;654 return this;655 };656657 /**658 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.659 *660 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown661 * for excess arguments.662 */663 allowExcessArguments(allowExcess = true) {664 this._allowExcessArguments = !!allowExcess;665 return this;666 };667668 /**669 * Enable positional options. Positional means global options are specified before subcommands which lets670 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.671 * The default behaviour is non-positional and global options may appear anywhere on the command line.672 *673 * @param {Boolean} [positional=true]674 */675 enablePositionalOptions(positional = true) {676 this._enablePositionalOptions = !!positional;677 return this;678 };679680 /**681 * Pass through options that come after command-arguments rather than treat them as command-options,682 * so actual command-options come before command-arguments. Turning this on for a subcommand requires683 * positional options to have been enabled on the program (parent commands).684 * The default behaviour is non-positional and options may appear before or after command-arguments.685 *686 * @param {Boolean} [passThrough=true]687 * for unknown options.688 */689 passThroughOptions(passThrough = true) {690 this._passThroughOptions = !!passThrough;691 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {692 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');693 }694 return this;695 };696697 /**698 * Whether to store option values as properties on command object,699 * or store separately (specify false). In both cases the option values can be accessed using .opts().700 *701 * @param {boolean} [storeAsProperties=true]702 * @return {Command} `this` command for chaining703 */704705 storeOptionsAsProperties(storeAsProperties = true) {706 this._storeOptionsAsProperties = !!storeAsProperties;707 if (this.options.length) {708 throw new Error('call .storeOptionsAsProperties() before adding options');709 }710 return this;711 };712713 /**714 * Retrieve option value.715 *716 * @param {string} key717 * @return {Object} value718 */719720 getOptionValue(key) {721 if (this._storeOptionsAsProperties) {722 return this[key];723 }724 return this._optionValues[key];725 };726727 /**728 * Store option value.729 *730 * @param {string} key731 * @param {Object} value732 * @return {Command} `this` command for chaining733 */734735 setOptionValue(key, value) {736 if (this._storeOptionsAsProperties) {737 this[key] = value;738 } else {739 this._optionValues[key] = value;740 }741 return this;742 };743744 /**745 * Get user arguments implied or explicit arguments.746 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.747 *748 * @api private749 */750751 _prepareUserArgs(argv, parseOptions) {752 if (argv !== undefined && !Array.isArray(argv)) {753 throw new Error('first parameter to parse must be array or undefined');754 }755 parseOptions = parseOptions || {};756757 // Default to using process.argv758 if (argv === undefined) {759 argv = process.argv;760 // @ts-ignore: unknown property761 if (process.versions && process.versions.electron) {762 parseOptions.from = 'electron';763 }764 }765 this.rawArgs = argv.slice();766767 // make it a little easier for callers by supporting various argv conventions768 let userArgs;769 switch (parseOptions.from) {770 case undefined:771 case 'node':772 this._scriptPath = argv[1];773 userArgs = argv.slice(2);774 break;775 case 'electron':776 // @ts-ignore: unknown property777 if (process.defaultApp) {778 this._scriptPath = argv[1];779 userArgs = argv.slice(2);780 } else {781 userArgs = argv.slice(1);782 }783 break;784 case 'user':785 userArgs = argv.slice(0);786 break;787 default:788 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);789 }790 if (!this._scriptPath && require.main) {791 this._scriptPath = require.main.filename;792 }793794 // Guess name, used in usage in help.795 this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));796797 return userArgs;798 }799800 /**801 * Parse `argv`, setting options and invoking commands when defined.802 *803 * The default expectation is that the arguments are from node and have the application as argv[0]804 * and the script being run in argv[1], with user parameters after that.805 *806 * Examples:807 *808 * program.parse(process.argv);809 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions810 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]811 *812 * @param {string[]} [argv] - optional, defaults to process.argv813 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron814 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'815 * @return {Command} `this` command for chaining816 */817818 parse(argv, parseOptions) {819 const userArgs = this._prepareUserArgs(argv, parseOptions);820 this._parseCommand([], userArgs);821822 return this;823 };824825 /**826 * Parse `argv`, setting options and invoking commands when defined.827 *828 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.829 *830 * The default expectation is that the arguments are from node and have the application as argv[0]831 * and the script being run in argv[1], with user parameters after that.832 *833 * Examples:834 *835 * await program.parseAsync(process.argv);836 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions837 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]838 *839 * @param {string[]} [argv]840 * @param {Object} [parseOptions]841 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'842 * @return {Promise}843 */844845 async parseAsync(argv, parseOptions) {846 const userArgs = this._prepareUserArgs(argv, parseOptions);847 await this._parseCommand([], userArgs);848849 return this;850 };851852 /**853 * Execute a sub-command executable.854 *855 * @api private856 */857858 _executeSubCommand(subcommand, args) {859 args = args.slice();860 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.861 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];862863 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.864 this._checkForMissingMandatoryOptions();865866 // Want the entry script as the reference for command name and directory for searching for other files.867 let scriptPath = this._scriptPath;868 // Fallback in case not set, due to how Command created or called.869 if (!scriptPath && require.main) {870 scriptPath = require.main.filename;871 }872873 let baseDir;874 try {875 const resolvedLink = fs.realpathSync(scriptPath);876 baseDir = path.dirname(resolvedLink);877 } catch (e) {878 baseDir = '.'; // dummy, probably not going to find executable!879 }880881 // name of the subcommand, like `pm-install`882 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;883 if (subcommand._executableFile) {884 bin = subcommand._executableFile;885 }886887 const localBin = path.join(baseDir, bin);888 if (fs.existsSync(localBin)) {889 // prefer local `./<bin>` to bin in the $PATH890 bin = localBin;891 } else {892 // Look for source files.893 sourceExt.forEach((ext) => {894 if (fs.existsSync(`${localBin}${ext}`)) {895 bin = `${localBin}${ext}`;896 }897 });898 }899 launchWithNode = sourceExt.includes(path.extname(bin));900901 let proc;902 if (process.platform !== 'win32') {903 if (launchWithNode) {904 args.unshift(bin);905 // add executable arguments to spawn906 args = incrementNodeInspectorPort(process.execArgv).concat(args);907908 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });909 } else {910 proc = childProcess.spawn(bin, args, { stdio: 'inherit' });911 }912 } else {913 args.unshift(bin);914 // add executable arguments to spawn915 args = incrementNodeInspectorPort(process.execArgv).concat(args);916 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });917 }918919 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];920 signals.forEach((signal) => {921 // @ts-ignore922 process.on(signal, () => {923 if (proc.killed === false && proc.exitCode === null) {924 proc.kill(signal);925 }926 });927 });928929 // By default terminate process when spawned process terminates.930 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!931 const exitCallback = this._exitCallback;932 if (!exitCallback) {933 proc.on('close', process.exit.bind(process));934 } else {935 proc.on('close', () => {936 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));937 });938 }939 proc.on('error', (err) => {940 // @ts-ignore941 if (err.code === 'ENOENT') {942 const executableMissing = `'${bin}' does not exist943 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead944 - if the default executable name is not suitable, use the executableFile option to supply a custom name`;945 throw new Error(executableMissing);946 // @ts-ignore947 } else if (err.code === 'EACCES') {948 throw new Error(`'${bin}' not executable`);949 }950 if (!exitCallback) {951 process.exit(1);952 } else {953 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');954 wrappedError.nestedError = err;955 exitCallback(wrappedError);956 }957 });958959 // Store the reference to the child process960 this.runningCommand = proc;961 };962963 /**964 * @api private965 */966967 _dispatchSubcommand(commandName, operands, unknown) {968 const subCommand = this._findCommand(commandName);969 if (!subCommand) this.help({ error: true });970971 if (subCommand._executableHandler) {972 this._executeSubCommand(subCommand, operands.concat(unknown));973 } else {974 return subCommand._parseCommand(operands, unknown);975 }976 };977978 /**979 * Package arguments (this.args) for passing to action handler based980 * on declared arguments (this._args).981 *982 * @api private983 */984985 _getActionArguments() {986 const myParseArg = (argument, value, previous) => {987 // Extra processing for nice error message on parsing failure.988 let parsedValue = value;989 if (value !== null && argument.parseArg) {990 try {991 parsedValue = argument.parseArg(value, previous);992 } catch (err) {993 if (err.code === 'commander.invalidArgument') {994 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;995 this._displayError(err.exitCode, err.code, message);996 }997 throw err;998 }999 }1000 return parsedValue;1001 };10021003 const actionArgs = [];1004 this._args.forEach((declaredArg, index) => {1005 let value = declaredArg.defaultValue;1006 if (declaredArg.variadic) {1007 // Collect together remaining arguments for passing together as an array.1008 if (index < this.args.length) {1009 value = this.args.slice(index);1010 if (declaredArg.parseArg) {1011 value = value.reduce((processed, v) => {1012 return myParseArg(declaredArg, v, processed);1013 }, declaredArg.defaultValue);1014 }1015 } else if (value === undefined) {1016 value = [];1017 }1018 } else if (index < this.args.length) {1019 value = this.args[index];1020 if (declaredArg.parseArg) {1021 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1022 }1023 }1024 actionArgs[index] = value;1025 });1026 return actionArgs;1027 }10281029 /**1030 * Once we have a promise we chain, but call synchronously until then.1031 *1032 * @param {Promise|undefined} promise1033 * @param {Function} fn1034 * @return {Promise|undefined}1035 */10361037 _chainOrCall(promise, fn) {1038 // thenable1039 if (promise && promise.then && typeof promise.then === 'function') {1040 // already have a promise, chain callback1041 return promise.then(() => fn());1042 }1043 // callback might return a promise1044 return fn();1045 }10461047 /**1048 *1049 * @param {Promise|undefined} promise1050 * @param {string} event1051 * @return {Promise|undefined}1052 * @api private1053 */10541055 _chainOrCallHooks(promise, event) {1056 let result = promise;1057 const hooks = [];1058 getCommandAndParents(this)1059 .reverse()1060 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1061 .forEach(hookedCommand => {1062 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1063 hooks.push({ hookedCommand, callback });1064 });1065 });1066 if (event === 'postAction') {1067 hooks.reverse();1068 }10691070 hooks.forEach((hookDetail) => {1071 result = this._chainOrCall(result, () => {1072 return hookDetail.callback(hookDetail.hookedCommand, this);1073 });1074 });1075 return result;1076 }10771078 /**1079 * Process arguments in context of this command.1080 * Returns action result, in case it is a promise.1081 *1082 * @api private1083 */10841085 _parseCommand(operands, unknown) {1086 const parsed = this.parseOptions(unknown);1087 operands = operands.concat(parsed.operands);1088 unknown = parsed.unknown;1089 this.args = operands.concat(unknown);10901091 if (operands && this._findCommand(operands[0])) {1092 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1093 }1094 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1095 if (operands.length === 1) {1096 this.help();1097 }1098 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1099 }1100 if (this._defaultCommandName) {1101 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1102 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1103 }1104 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1105 // probably missing subcommand and no handler, user needs help (and exit)1106 this.help({ error: true });1107 }11081109 outputHelpIfRequested(this, parsed.unknown);1110 this._checkForMissingMandatoryOptions();11111112 // We do not always call this check to avoid masking a "better" error, like unknown command.1113 const checkForUnknownOptions = () => {1114 if (parsed.unknown.length > 0) {1115 this.unknownOption(parsed.unknown[0]);1116 }1117 };1118 const checkNumberOfArguments = () => {1119 // too few1120 this._args.forEach((arg, i) => {1121 if (arg.required && this.args[i] == null) {1122 this.missingArgument(arg.name());1123 }1124 });1125 // too many1126 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1127 return;1128 }1129 if (this.args.length > this._args.length) {1130 this._excessArguments(this.args);1131 }1132 };11331134 const commandEvent = `command:${this.name()}`;1135 if (this._actionHandler) {1136 checkForUnknownOptions();1137 checkNumberOfArguments();11381139 let actionResult;1140 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1141 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this._getActionArguments()));1142 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1143 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1144 return actionResult;1145 }1146 if (this.parent && this.parent.listenerCount(commandEvent)) {1147 checkForUnknownOptions();1148 checkNumberOfArguments();1149 this.parent.emit(commandEvent, operands, unknown); // legacy1150 } else if (operands.length) {1151 if (this._findCommand('*')) { // legacy default command1152 return this._dispatchSubcommand('*', operands, unknown);1153 }1154 if (this.listenerCount('command:*')) {1155 // skip option check, emit event for possible misspelling suggestion1156 this.emit('command:*', operands, unknown);1157 } else if (this.commands.length) {1158 this.unknownCommand();1159 } else {1160 checkForUnknownOptions();1161 checkNumberOfArguments();1162 }1163 } else if (this.commands.length) {1164 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1165 this.help({ error: true });1166 } else {1167 checkForUnknownOptions();1168 checkNumberOfArguments();1169 // fall through for caller to handle after calling .parse()1170 }1171 };11721173 /**1174 * Find matching command.1175 *1176 * @api private1177 */1178 _findCommand(name) {1179 if (!name) return undefined;1180 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1181 };11821183 /**1184 * Return an option matching `arg` if any.1185 *1186 * @param {string} arg1187 * @return {Option}1188 * @api private1189 */11901191 _findOption(arg) {1192 return this.options.find(option => option.is(arg));1193 };11941195 /**1196 * Display an error message if a mandatory option does not have a value.1197 * Lazy calling after checking for help flags from leaf subcommand.1198 *1199 * @api private1200 */12011202 _checkForMissingMandatoryOptions() {1203 // Walk up hierarchy so can call in subcommand after checking for displaying help.1204 for (let cmd = this; cmd; cmd = cmd.parent) {1205 cmd.options.forEach((anOption) => {1206 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1207 cmd.missingMandatoryOptionValue(anOption);1208 }1209 });1210 }1211 };12121213 /**1214 * Parse options from `argv` removing known options,1215 * and return argv split into operands and unknown arguments.1216 *1217 * Examples:1218 *1219 * argv => operands, unknown1220 * --known kkk op => [op], []1221 * op --known kkk => [op], []1222 * sub --unknown uuu op => [sub], [--unknown uuu op]1223 * sub -- --unknown uuu op => [sub --unknown uuu op], []1224 *1225 * @param {String[]} argv1226 * @return {{operands: String[], unknown: String[]}}1227 */12281229 parseOptions(argv) {1230 const operands = []; // operands, not options or values1231 const unknown = []; // first unknown option and remaining unknown args1232 let dest = operands;1233 const args = argv.slice();12341235 function maybeOption(arg) {1236 return arg.length > 1 && arg[0] === '-';1237 }12381239 // parse options1240 let activeVariadicOption = null;1241 while (args.length) {1242 const arg = args.shift();12431244 // literal1245 if (arg === '--') {1246 if (dest === unknown) dest.push(arg);1247 dest.push(...args);1248 break;1249 }12501251 if (activeVariadicOption && !maybeOption(arg)) {1252 this.emit(`option:${activeVariadicOption.name()}`, arg);1253 continue;1254 }1255 activeVariadicOption = null;12561257 if (maybeOption(arg)) {1258 const option = this._findOption(arg);1259 // recognised option, call listener to assign value with possible custom processing1260 if (option) {1261 if (option.required) {1262 const value = args.shift();1263 if (value === undefined) this.optionMissingArgument(option);1264 this.emit(`option:${option.name()}`, value);1265 } else if (option.optional) {1266 let value = null;1267 // historical behaviour is optional value is following arg unless an option1268 if (args.length > 0 && !maybeOption(args[0])) {1269 value = args.shift();1270 }1271 this.emit(`option:${option.name()}`, value);1272 } else { // boolean flag1273 this.emit(`option:${option.name()}`);1274 }1275 activeVariadicOption = option.variadic ? option : null;1276 continue;1277 }1278 }12791280 // Look for combo options following single dash, eat first one if known.1281 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1282 const option = this._findOption(`-${arg[1]}`);1283 if (option) {1284 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1285 // option with value following in same argument1286 this.emit(`option:${option.name()}`, arg.slice(2));1287 } else {1288 // boolean option, emit and put back remainder of arg for further processing1289 this.emit(`option:${option.name()}`);1290 args.unshift(`-${arg.slice(2)}`);1291 }1292 continue;1293 }1294 }12951296 // Look for known long flag with value, like --foo=bar1297 if (/^--[^=]+=/.test(arg)) {1298 const index = arg.indexOf('=');1299 const option = this._findOption(arg.slice(0, index));1300 if (option && (option.required || option.optional)) {1301 this.emit(`option:${option.name()}`, arg.slice(index + 1));1302 continue;1303 }1304 }13051306 // Not a recognised option by this command.1307 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.13081309 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1310 if (maybeOption(arg)) {1311 dest = unknown;1312 }13131314 // If using positionalOptions, stop processing our options at subcommand.1315 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1316 if (this._findCommand(arg)) {1317 operands.push(arg);1318 if (args.length > 0) unknown.push(...args);1319 break;1320 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1321 operands.push(arg);1322 if (args.length > 0) operands.push(...args);1323 break;1324 } else if (this._defaultCommandName) {1325 unknown.push(arg);1326 if (args.length > 0) unknown.push(...args);1327 break;1328 }1329 }13301331 // If using passThroughOptions, stop processing options at first command-argument.1332 if (this._passThroughOptions) {1333 dest.push(arg);1334 if (args.length > 0) dest.push(...args);1335 break;1336 }13371338 // add arg1339 dest.push(arg);1340 }13411342 return { operands, unknown };1343 };13441345 /**1346 * Return an object containing options as key-value pairs1347 *1348 * @return {Object}1349 */1350 opts() {1351 if (this._storeOptionsAsProperties) {1352 // Preserve original behaviour so backwards compatible when still using properties1353 const result = {};1354 const len = this.options.length;13551356 for (let i = 0; i < len; i++) {1357 const key = this.options[i].attributeName();1358 result[key] = key === this._versionOptionName ? this._version : this[key];1359 }1360 return result;1361 }13621363 return this._optionValues;1364 };13651366 /**1367 * Internal bottleneck for handling of parsing errors.1368 *1369 * @api private1370 */1371 _displayError(exitCode, code, message) {1372 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1373 this._exit(exitCode, code, message);1374 }13751376 /**1377 * Argument `name` is missing.1378 *1379 * @param {string} name1380 * @api private1381 */13821383 missingArgument(name) {1384 const message = `error: missing required argument '${name}'`;1385 this._displayError(1, 'commander.missingArgument', message);1386 };13871388 /**1389 * `Option` is missing an argument.1390 *1391 * @param {Option} option1392 * @api private1393 */13941395 optionMissingArgument(option) {1396 const message = `error: option '${option.flags}' argument missing`;1397 this._displayError(1, 'commander.optionMissingArgument', message);1398 };13991400 /**1401 * `Option` does not have a value, and is a mandatory option.1402 *1403 * @param {Option} option1404 * @api private1405 */14061407 missingMandatoryOptionValue(option) {1408 const message = `error: required option '${option.flags}' not specified`;1409 this._displayError(1, 'commander.missingMandatoryOptionValue', message);1410 };14111412 /**1413 * Unknown option `flag`.1414 *1415 * @param {string} flag1416 * @api private1417 */14181419 unknownOption(flag) {1420 if (this._allowUnknownOption) return;1421 const message = `error: unknown option '${flag}'`;1422 this._displayError(1, 'commander.unknownOption', message);1423 };14241425 /**1426 * Excess arguments, more than expected.1427 *1428 * @param {string[]} receivedArgs1429 * @api private1430 */14311432 _excessArguments(receivedArgs) {1433 if (this._allowExcessArguments) return;14341435 const expected = this._args.length;1436 const s = (expected === 1) ? '' : 's';1437 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1438 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1439 this._displayError(1, 'commander.excessArguments', message);1440 };14411442 /**1443 * Unknown command.1444 *1445 * @api private1446 */14471448 unknownCommand() {1449 const partCommands = [this.name()];1450 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1451 partCommands.unshift(parentCmd.name());1452 }1453 const fullCommand = partCommands.join(' ');1454 const message = `error: unknown command '${this.args[0]}'.` +1455 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');1456 this._displayError(1, 'commander.unknownCommand', message);1457 };14581459 /**1460 * Set the program version to `str`.1461 *1462 * This method auto-registers the "-V, --version" flag1463 * which will print the version number when passed.1464 *1465 * You can optionally supply the flags and description to override the defaults.1466 *1467 * @param {string} str1468 * @param {string} [flags]1469 * @param {string} [description]1470 * @return {this | string} `this` command for chaining, or version string if no arguments1471 */14721473 version(str, flags, description) {1474 if (str === undefined) return this._version;1475 this._version = str;1476 flags = flags || '-V, --version';1477 description = description || 'output the version number';1478 const versionOption = this.createOption(flags, description);1479 this._versionOptionName = versionOption.attributeName();1480 this.options.push(versionOption);1481 this.on('option:' + versionOption.name(), () => {1482 this._outputConfiguration.writeOut(`${str}\n`);1483 this._exit(0, 'commander.version', str);1484 });1485 return this;1486 };14871488 /**1489 * Set the description to `str`.1490 *1491 * @param {string} [str]1492 * @param {Object} [argsDescription]1493 * @return {string|Command}1494 */1495 description(str, argsDescription) {1496 if (str === undefined && argsDescription === undefined) return this._description;1497 this._description = str;1498 if (argsDescription) {1499 this._argsDescription = argsDescription;1500 }1501 return this;1502 };15031504 /**1505 * Set an alias for the command.1506 *1507 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1508 *1509 * @param {string} [alias]1510 * @return {string|Command}1511 */15121513 alias(alias) {1514 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility15151516 let command = this;1517 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1518 // assume adding alias for last added executable subcommand, rather than this1519 command = this.commands[this.commands.length - 1];1520 }15211522 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');15231524 command._aliases.push(alias);1525 return this;1526 };15271528 /**1529 * Set aliases for the command.1530 *1531 * Only the first alias is shown in the auto-generated help.1532 *1533 * @param {string[]} [aliases]1534 * @return {string[]|Command}1535 */15361537 aliases(aliases) {1538 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1539 if (aliases === undefined) return this._aliases;15401541 aliases.forEach((alias) => this.alias(alias));1542 return this;1543 };15441545 /**1546 * Set / get the command usage `str`.1547 *1548 * @param {string} [str]1549 * @return {String|Command}1550 */15511552 usage(str) {1553 if (str === undefined) {1554 if (this._usage) return this._usage;15551556 const args = this._args.map((arg) => {1557 return humanReadableArgName(arg);1558 });1559 return [].concat(1560 (this.options.length || this._hasHelpOption ? '[options]' : []),1561 (this.commands.length ? '[command]' : []),1562 (this._args.length ? args : [])1563 ).join(' ');1564 }15651566 this._usage = str;1567 return this;1568 };15691570 /**1571 * Get or set the name of the command1572 *1573 * @param {string} [str]1574 * @return {string|Command}1575 */15761577 name(str) {1578 if (str === undefined) return this._name;1579 this._name = str;1580 return this;1581 };15821583 /**1584 * Return program help documentation.1585 *1586 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1587 * @return {string}1588 */15891590 helpInformation(contextOptions) {1591 const helper = this.createHelp();1592 if (helper.helpWidth === undefined) {1593 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1594 }1595 return helper.formatHelp(this, helper);1596 };15971598 /**1599 * @api private1600 */16011602 _getHelpContext(contextOptions) {1603 contextOptions = contextOptions || {};1604 const context = { error: !!contextOptions.error };1605 let write;1606 if (context.error) {1607 write = (arg) => this._outputConfiguration.writeErr(arg);1608 } else {1609 write = (arg) => this._outputConfiguration.writeOut(arg);1610 }1611 context.write = contextOptions.write || write;1612 context.command = this;1613 return context;1614 }16151616 /**1617 * Output help information for this command.1618 *1619 * Outputs built-in help, and custom text added using `.addHelpText()`.1620 *1621 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1622 */16231624 outputHelp(contextOptions) {1625 let deprecatedCallback;1626 if (typeof contextOptions === 'function') {1627 deprecatedCallback = contextOptions;1628 contextOptions = undefined;1629 }1630 const context = this._getHelpContext(contextOptions);16311632 const groupListeners = [];1633 let command = this;1634 while (command) {1635 groupListeners.push(command); // ordered from current command to root1636 command = command.parent;1637 }16381639 groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));1640 this.emit('beforeHelp', context);16411642 let helpInformation = this.helpInformation(context);1643 if (deprecatedCallback) {1644 helpInformation = deprecatedCallback(helpInformation);1645 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1646 throw new Error('outputHelp callback must return a string or a Buffer');1647 }1648 }1649 context.write(helpInformation);16501651 this.emit(this._helpLongFlag); // deprecated1652 this.emit('afterHelp', context);1653 groupListeners.forEach(command => command.emit('afterAllHelp', context));1654 };16551656 /**1657 * You can pass in flags and a description to override the help1658 * flags and help description for your command. Pass in false to1659 * disable the built-in help option.1660 *1661 * @param {string | boolean} [flags]1662 * @param {string} [description]1663 * @return {Command} `this` command for chaining1664 */16651666 helpOption(flags, description) {1667 if (typeof flags === 'boolean') {1668 this._hasHelpOption = flags;1669 return this;1670 }1671 this._helpFlags = flags || this._helpFlags;1672 this._helpDescription = description || this._helpDescription;16731674 const helpFlags = splitOptionFlags(this._helpFlags);1675 this._helpShortFlag = helpFlags.shortFlag;1676 this._helpLongFlag = helpFlags.longFlag;16771678 return this;1679 };16801681 /**1682 * Output help information and exit.1683 *1684 * Outputs built-in help, and custom text added using `.addHelpText()`.1685 *1686 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1687 */16881689 help(contextOptions) {1690 this.outputHelp(contextOptions);1691 let exitCode = process.exitCode || 0;1692 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1693 exitCode = 1;1694 }1695 // message: do not have all displayed text available so only passing placeholder.1696 this._exit(exitCode, 'commander.help', '(outputHelp)');1697 };16981699 /**1700 * Add additional text to be displayed with the built-in help.1701 *1702 * Position is 'before' or 'after' to affect just this command,1703 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1704 *1705 * @param {string} position - before or after built-in help1706 * @param {string | Function} text - string to add, or a function returning a string1707 * @return {Command} `this` command for chaining1708 */1709 addHelpText(position, text) {1710 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1711 if (!allowedValues.includes(position)) {1712 throw new Error(`Unexpected value for position to addHelpText.1713Expecting one of '${allowedValues.join("', '")}'`);1714 }1715 const helpEvent = `${position}Help`;1716 this.on(helpEvent, (context) => {1717 let helpStr;1718 if (typeof text === 'function') {1719 helpStr = text({ error: context.error, command: context.command });1720 } else {1721 helpStr = text;1722 }1723 // Ignore falsy value when nothing to output.1724 if (helpStr) {1725 context.write(`${helpStr}\n`);1726 }1727 });1728 return this;1729 }1730};17311732/**1733 * Output help information if help flags specified1734 *1735 * @param {Command} cmd - command to output help for1736 * @param {Array} args - array of options to search for help flags1737 * @api private1738 */17391740function outputHelpIfRequested(cmd, args) {1741 const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1742 if (helpOption) {1743 cmd.outputHelp();1744 // (Do not have all displayed text available so only passing placeholder.)1745 cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');1746 }1747}17481749/**1750 * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).1751 *1752 * @param {string[]} args - array of arguments from node.execArgv1753 * @returns {string[]}1754 * @api private1755 */17561757function incrementNodeInspectorPort(args) {1758 // Testing for these options:1759 // --inspect[=[host:]port]1760 // --inspect-brk[=[host:]port]1761 // --inspect-port=[host:]port1762 return args.map((arg) => {1763 if (!arg.startsWith('--inspect')) {1764 return arg;1765 }1766 let debugOption;1767 let debugHost = '127.0.0.1';1768 let debugPort = '9229';1769 let match;1770 if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {1771 // e.g. --inspect1772 debugOption = match[1];1773 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {1774 debugOption = match[1];1775 if (/^\d+$/.test(match[3])) {1776 // e.g. --inspect=12341777 debugPort = match[3];1778 } else {1779 // e.g. --inspect=localhost1780 debugHost = match[3];1781 }1782 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {1783 // e.g. --inspect=localhost:12341784 debugOption = match[1];1785 debugHost = match[3];1786 debugPort = match[4];1787 }17881789 if (debugOption && debugPort !== '0') {1790 return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;1791 }1792 return arg;1793 });1794}17951796/**1797 * @param {Command} startCommand1798 * @returns {Command[]}1799 * @api private1800 */18011802function getCommandAndParents(startCommand) {1803 const result = [];1804 for (let command = startCommand; command; command = command.parent) {1805 result.push(command);1806 }1807 return result;1808}18091810exports.Command = Command;
added:lib/error.js+45 added
added:lib/help.js+383 added
1const { humanReadableArgName } = require('./argument.js');23/**4 * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`5 * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types6 * @typedef { import("./argument.js").Argument } Argument7 * @typedef { import("./command.js").Command } Command8 * @typedef { import("./option.js").Option } Option9 */1011// @ts-check1213// Although this is a class, methods are static in style to allow override using subclass or just functions.14class Help {15 constructor() {16 this.helpWidth = undefined;17 this.sortSubcommands = false;18 this.sortOptions = false;19 }2021 /**22 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.23 *24 * @param {Command} cmd25 * @returns {Command[]}26 */2728 visibleCommands(cmd) {29 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);30 if (cmd._hasImplicitHelpCommand()) {31 // Create a command matching the implicit help command.32 const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);33 const helpCommand = cmd.createCommand(helpName)34 .helpOption(false);35 helpCommand.description(cmd._helpCommandDescription);36 if (helpArgs) helpCommand.arguments(helpArgs);37 visibleCommands.push(helpCommand);38 }39 if (this.sortSubcommands) {40 visibleCommands.sort((a, b) => {41 return a.name().localeCompare(b.name());42 });43 }44 return visibleCommands;45 }4647 /**48 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.49 *50 * @param {Command} cmd51 * @returns {Option[]}52 */5354 visibleOptions(cmd) {55 const visibleOptions = cmd.options.filter((option) => !option.hidden);56 // Implicit help57 const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);58 const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);59 if (showShortHelpFlag || showLongHelpFlag) {60 let helpOption;61 if (!showShortHelpFlag) {62 helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);63 } else if (!showLongHelpFlag) {64 helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);65 } else {66 helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);67 }68 visibleOptions.push(helpOption);69 }70 if (this.sortOptions) {71 const getSortKey = (option) => {72 // WYSIWYG for order displayed in help with short before long, no special handling for negated.73 return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');74 };75 visibleOptions.sort((a, b) => {76 return getSortKey(a).localeCompare(getSortKey(b));77 });78 }79 return visibleOptions;80 }8182 /**83 * Get an array of the arguments if any have a description.84 *85 * @param {Command} cmd86 * @returns {Argument[]}87 */8889 visibleArguments(cmd) {90 // Side effect! Apply the legacy descriptions before the arguments are displayed.91 if (cmd._argsDescription) {92 cmd._args.forEach(argument => {93 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';94 });95 }9697 // If there are any arguments with a description then return all the arguments.98 if (cmd._args.find(argument => argument.description)) {99 return cmd._args;100 };101 return [];102 }103104 /**105 * Get the command term to show in the list of subcommands.106 *107 * @param {Command} cmd108 * @returns {string}109 */110111 subcommandTerm(cmd) {112 // Legacy. Ignores custom usage string, and nested commands.113 const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');114 return cmd._name +115 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +116 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option117 (args ? ' ' + args : '');118 }119120 /**121 * Get the option term to show in the list of options.122 *123 * @param {Option} option124 * @returns {string}125 */126127 optionTerm(option) {128 return option.flags;129 }130131 /**132 * Get the argument term to show in the list of arguments.133 *134 * @param {Argument} argument135 * @returns {string}136 */137138 argumentTerm(argument) {139 return argument.name();140 }141142 /**143 * Get the longest command term length.144 *145 * @param {Command} cmd146 * @param {Help} helper147 * @returns {number}148 */149150 longestSubcommandTermLength(cmd, helper) {151 return helper.visibleCommands(cmd).reduce((max, command) => {152 return Math.max(max, helper.subcommandTerm(command).length);153 }, 0);154 };155156 /**157 * Get the longest option term length.158 *159 * @param {Command} cmd160 * @param {Help} helper161 * @returns {number}162 */163164 longestOptionTermLength(cmd, helper) {165 return helper.visibleOptions(cmd).reduce((max, option) => {166 return Math.max(max, helper.optionTerm(option).length);167 }, 0);168 };169170 /**171 * Get the longest argument term length.172 *173 * @param {Command} cmd174 * @param {Help} helper175 * @returns {number}176 */177178 longestArgumentTermLength(cmd, helper) {179 return helper.visibleArguments(cmd).reduce((max, argument) => {180 return Math.max(max, helper.argumentTerm(argument).length);181 }, 0);182 };183184 /**185 * Get the command usage to be displayed at the top of the built-in help.186 *187 * @param {Command} cmd188 * @returns {string}189 */190191 commandUsage(cmd) {192 // Usage193 let cmdName = cmd._name;194 if (cmd._aliases[0]) {195 cmdName = cmdName + '|' + cmd._aliases[0];196 }197 let parentCmdNames = '';198 for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {199 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;200 }201 return parentCmdNames + cmdName + ' ' + cmd.usage();202 }203204 /**205 * Get the description for the command.206 *207 * @param {Command} cmd208 * @returns {string}209 */210211 commandDescription(cmd) {212 // @ts-ignore: overloaded return type213 return cmd.description();214 }215216 /**217 * Get the command description to show in the list of subcommands.218 *219 * @param {Command} cmd220 * @returns {string}221 */222223 subcommandDescription(cmd) {224 // @ts-ignore: overloaded return type225 return cmd.description();226 }227228 /**229 * Get the option description to show in the list of options.230 *231 * @param {Option} option232 * @return {string}233 */234235 optionDescription(option) {236 if (option.negate) {237 return option.description;238 }239 const extraInfo = [];240 if (option.argChoices) {241 extraInfo.push(242 // use stringify to match the display of the default value243 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);244 }245 if (option.defaultValue !== undefined) {246 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);247 }248 if (extraInfo.length > 0) {249 return `${option.description} (${extraInfo.join(', ')})`;250 }251 return option.description;252 };253254 /**255 * Get the argument description to show in the list of arguments.256 *257 * @param {Argument} argument258 * @return {string}259 */260261 argumentDescription(argument) {262 const extraInfo = [];263 if (argument.defaultValue !== undefined) {264 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);265 }266 if (extraInfo.length > 0) {267 return `${argument.description} (${extraInfo.join(', ')})`;268 }269 return argument.description;270 }271272 /**273 * Generate the built-in help text.274 *275 * @param {Command} cmd276 * @param {Help} helper277 * @returns {string}278 */279280 formatHelp(cmd, helper) {281 const termWidth = helper.padWidth(cmd, helper);282 const helpWidth = helper.helpWidth || 80;283 const itemIndentWidth = 2;284 const itemSeparatorWidth = 2; // between term and description285 function formatItem(term, description) {286 if (description) {287 const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;288 return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);289 }290 return term;291 };292 function formatList(textArray) {293 return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));294 }295296 // Usage297 let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];298299 // Description300 const commandDescription = helper.commandDescription(cmd);301 if (commandDescription.length > 0) {302 output = output.concat([commandDescription, '']);303 }304305 // Arguments306 const argumentList = helper.visibleArguments(cmd).map((argument) => {307 return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));308 });309 if (argumentList.length > 0) {310 output = output.concat(['Arguments:', formatList(argumentList), '']);311 }312313 // Options314 const optionList = helper.visibleOptions(cmd).map((option) => {315 return formatItem(helper.optionTerm(option), helper.optionDescription(option));316 });317 if (optionList.length > 0) {318 output = output.concat(['Options:', formatList(optionList), '']);319 }320321 // Commands322 const commandList = helper.visibleCommands(cmd).map((cmd) => {323 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));324 });325 if (commandList.length > 0) {326 output = output.concat(['Commands:', formatList(commandList), '']);327 }328329 return output.join('\n');330 }331332 /**333 * Calculate the pad width from the maximum term length.334 *335 * @param {Command} cmd336 * @param {Help} helper337 * @returns {number}338 */339340 padWidth(cmd, helper) {341 return Math.max(342 helper.longestOptionTermLength(cmd, helper),343 helper.longestSubcommandTermLength(cmd, helper),344 helper.longestArgumentTermLength(cmd, helper)345 );346 };347348 /**349 * Wrap the given string to width characters per line, with lines after the first indented.350 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.351 *352 * @param {string} str353 * @param {number} width354 * @param {number} indent355 * @param {number} [minColumnWidth=40]356 * @return {string}357 *358 */359360 wrap(str, width, indent, minColumnWidth = 40) {361 // Detect manually wrapped and indented strings by searching for line breaks362 // followed by multiple spaces/tabs.363 if (str.match(/[\n]\s+/)) return str;364 // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).365 const columnWidth = width - indent;366 if (columnWidth < minColumnWidth) return str;367368 const leadingStr = str.substr(0, indent);369 const columnText = str.substr(indent);370371 const indentString = ' '.repeat(indent);372 const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');373 const lines = columnText.match(regex) || [];374 return leadingStr + lines.map((line, i) => {375 if (line.slice(-1) === '\n') {376 line = line.slice(0, line.length - 1);377 }378 return ((i > 0) ? indentString : '') + line.trimRight();379 }).join('\n');380 }381}382383exports.Help = Help;
added:lib/option.js+194 added
1const { InvalidArgumentError } = require('./error.js');23// @ts-check45class Option {6 /**7 * Initialize a new `Option` with the given `flags` and `description`.8 *9 * @param {string} flags10 * @param {string} [description]11 */1213 constructor(flags, description) {14 this.flags = flags;15 this.description = description || '';1617 this.required = flags.includes('<'); // A value must be supplied when the option is specified.18 this.optional = flags.includes('['); // A value is optional when the option is specified.19 // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument20 this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.21 this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.22 const optionFlags = splitOptionFlags(flags);23 this.short = optionFlags.shortFlag;24 this.long = optionFlags.longFlag;25 this.negate = false;26 if (this.long) {27 this.negate = this.long.startsWith('--no-');28 }29 this.defaultValue = undefined;30 this.defaultValueDescription = undefined;31 this.parseArg = undefined;32 this.hidden = false;33 this.argChoices = undefined;34 }3536 /**37 * Set the default value, and optionally supply the description to be displayed in the help.38 *39 * @param {any} value40 * @param {string} [description]41 * @return {Option}42 */4344 default(value, description) {45 this.defaultValue = value;46 this.defaultValueDescription = description;47 return this;48 };4950 /**51 * Set the custom handler for processing CLI option arguments into option values.52 *53 * @param {Function} [fn]54 * @return {Option}55 */5657 argParser(fn) {58 this.parseArg = fn;59 return this;60 };6162 /**63 * Whether the option is mandatory and must have a value after parsing.64 *65 * @param {boolean} [mandatory=true]66 * @return {Option}67 */6869 makeOptionMandatory(mandatory = true) {70 this.mandatory = !!mandatory;71 return this;72 };7374 /**75 * Hide option in help.76 *77 * @param {boolean} [hide=true]78 * @return {Option}79 */8081 hideHelp(hide = true) {82 this.hidden = !!hide;83 return this;84 };8586 /**87 * @api private88 */8990 _concatValue(value, previous) {91 if (previous === this.defaultValue || !Array.isArray(previous)) {92 return [value];93 }9495 return previous.concat(value);96 }9798 /**99 * Only allow option value to be one of choices.100 *101 * @param {string[]} values102 * @return {Option}103 */104105 choices(values) {106 this.argChoices = values;107 this.parseArg = (arg, previous) => {108 if (!values.includes(arg)) {109 throw new InvalidArgumentError(`Allowed choices are ${values.join(', ')}.`);110 }111 if (this.variadic) {112 return this._concatValue(arg, previous);113 }114 return arg;115 };116 return this;117 };118119 /**120 * Return option name.121 *122 * @return {string}123 */124125 name() {126 if (this.long) {127 return this.long.replace(/^--/, '');128 }129 return this.short.replace(/^-/, '');130 };131132 /**133 * Return option name, in a camelcase format that can be used134 * as a object attribute key.135 *136 * @return {string}137 * @api private138 */139140 attributeName() {141 return camelcase(this.name().replace(/^no-/, ''));142 };143144 /**145 * Check if `arg` matches the short or long flag.146 *147 * @param {string} arg148 * @return {boolean}149 * @api private150 */151152 is(arg) {153 return this.short === arg || this.long === arg;154 };155}156157/**158 * Convert string from kebab-case to camelCase.159 *160 * @param {string} str161 * @return {string}162 * @api private163 */164165function camelcase(str) {166 return str.split('-').reduce((str, word) => {167 return str + word[0].toUpperCase() + word.slice(1);168 });169}170171/**172 * Split the short and long flag out of something like '-m,--mixed <value>'173 *174 * @api private175 */176177function splitOptionFlags(flags) {178 let shortFlag;179 let longFlag;180 // Use original very loose parsing to maintain backwards compatibility for now,181 // which allowed for example unintended `-sw, --short-word` [sic].182 const flagParts = flags.split(/[ |,]+/);183 if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();184 longFlag = flagParts.shift();185 // Add support for lone short flag without significantly changing parsing!186 if (!shortFlag && /^-[^-]$/.test(longFlag)) {187 shortFlag = longFlag;188 longFlag = undefined;189 }190 return { shortFlag, longFlag };191}192193exports.Option = Option;194exports.splitOptionFlags = splitOptionFlags;
modified:index.js+9 added-2498 removed
1/**2 * Module dependencies.3 */1const { Argument } = require('./lib/argument.js');2const { Command } = require('./lib/command.js');3const { CommanderError, InvalidArgumentError } = require('./lib/error.js');4const { Help } = require('./lib/help.js');5const { Option } = require('./lib/option.js');65const EventEmitter = require('events').EventEmitter;6const childProcess = require('child_process');7const path = require('path');8const fs = require('fs');97// @ts-check812// Although this is a class, methods are static in style to allow override using subclass or just functions.13class Help {14 constructor() {15 this.helpWidth = undefined;16 this.sortSubcommands = false;17 this.sortOptions = false;18 }1920 /**21 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.22 *23 * @param {Command} cmd24 * @returns {Command[]}25 */2627 visibleCommands(cmd) {28 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);29 if (cmd._hasImplicitHelpCommand()) {30 // Create a command matching the implicit help command.31 const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);32 const helpCommand = cmd.createCommand(helpName)33 .helpOption(false);34 helpCommand.description(cmd._helpCommandDescription);35 if (helpArgs) helpCommand.arguments(helpArgs);36 visibleCommands.push(helpCommand);37 }38 if (this.sortSubcommands) {39 visibleCommands.sort((a, b) => {40 return a.name().localeCompare(b.name());41 });42 }43 return visibleCommands;44 }4546 /**47 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.48 *49 * @param {Command} cmd50 * @returns {Option[]}51 */5253 visibleOptions(cmd) {54 const visibleOptions = cmd.options.filter((option) => !option.hidden);55 // Implicit help56 const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);57 const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);58 if (showShortHelpFlag || showLongHelpFlag) {59 let helpOption;60 if (!showShortHelpFlag) {61 helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);62 } else if (!showLongHelpFlag) {63 helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);64 } else {65 helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);66 }67 visibleOptions.push(helpOption);68 }69 if (this.sortOptions) {70 const getSortKey = (option) => {71 // WYSIWYG for order displayed in help with short before long, no special handling for negated.72 return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');73 };74 visibleOptions.sort((a, b) => {75 return getSortKey(a).localeCompare(getSortKey(b));76 });77 }78 return visibleOptions;79 }8081 /**82 * Get an array of the arguments if any have a description.83 *84 * @param {Command} cmd85 * @returns {Argument[]}86 */8788 visibleArguments(cmd) {89 // Side effect! Apply the legacy descriptions before the arguments are displayed.90 if (cmd._argsDescription) {91 cmd._args.forEach(argument => {92 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';93 });94 }9596 // If there are any arguments with a description then return all the arguments.97 if (cmd._args.find(argument => argument.description)) {98 return cmd._args;99 };100 return [];101 }102103 /**104 * Get the command term to show in the list of subcommands.105 *106 * @param {Command} cmd107 * @returns {string}108 */109110 subcommandTerm(cmd) {111 // Legacy. Ignores custom usage string, and nested commands.112 const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');113 return cmd._name +114 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +115 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option116 (args ? ' ' + args : '');117 }118119 /**120 * Get the option term to show in the list of options.121 *122 * @param {Option} option123 * @returns {string}124 */125126 optionTerm(option) {127 return option.flags;128 }129130 /**131 * Get the argument term to show in the list of arguments.132 *133 * @param {Argument} argument134 * @returns {string}135 */136137 argumentTerm(argument) {138 return argument.name();139 }140141 /**142 * Get the longest command term length.143 *144 * @param {Command} cmd145 * @param {Help} helper146 * @returns {number}147 */148149 longestSubcommandTermLength(cmd, helper) {150 return helper.visibleCommands(cmd).reduce((max, command) => {151 return Math.max(max, helper.subcommandTerm(command).length);152 }, 0);153 };154155 /**156 * Get the longest option term length.157 *158 * @param {Command} cmd159 * @param {Help} helper160 * @returns {number}161 */162163 longestOptionTermLength(cmd, helper) {164 return helper.visibleOptions(cmd).reduce((max, option) => {165 return Math.max(max, helper.optionTerm(option).length);166 }, 0);167 };168169 /**170 * Get the longest argument term length.171 *172 * @param {Command} cmd173 * @param {Help} helper174 * @returns {number}175 */176177 longestArgumentTermLength(cmd, helper) {178 return helper.visibleArguments(cmd).reduce((max, argument) => {179 return Math.max(max, helper.argumentTerm(argument).length);180 }, 0);181 };182183 /**184 * Get the command usage to be displayed at the top of the built-in help.185 *186 * @param {Command} cmd187 * @returns {string}188 */189190 commandUsage(cmd) {191 // Usage192 let cmdName = cmd._name;193 if (cmd._aliases[0]) {194 cmdName = cmdName + '|' + cmd._aliases[0];195 }196 let parentCmdNames = '';197 for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {198 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;199 }200 return parentCmdNames + cmdName + ' ' + cmd.usage();201 }202203 /**204 * Get the description for the command.205 *206 * @param {Command} cmd207 * @returns {string}208 */209210 commandDescription(cmd) {211 // @ts-ignore: overloaded return type212 return cmd.description();213 }214215 /**216 * Get the command description to show in the list of subcommands.217 *218 * @param {Command} cmd219 * @returns {string}220 */221222 subcommandDescription(cmd) {223 // @ts-ignore: overloaded return type224 return cmd.description();225 }226227 /**228 * Get the option description to show in the list of options.229 *230 * @param {Option} option231 * @return {string}232 */233234 optionDescription(option) {235 if (option.negate) {236 return option.description;237 }238 const extraInfo = [];239 if (option.argChoices) {240 extraInfo.push(241 // use stringify to match the display of the default value242 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);243 }244 if (option.defaultValue !== undefined) {245 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);246 }247 if (extraInfo.length > 0) {248 return `${option.description} (${extraInfo.join(', ')})`;249 }250 return option.description;251 };252253 /**254 * Get the argument description to show in the list of arguments.255 *256 * @param {Argument} argument257 * @return {string}258 */259260 argumentDescription(argument) {261 const extraInfo = [];262 if (argument.defaultValue !== undefined) {263 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);264 }265 if (extraInfo.length > 0) {266 return `${argument.description} (${extraInfo.join(', ')})`;267 }268 return argument.description;269 }270271 /**272 * Generate the built-in help text.273 *274 * @param {Command} cmd275 * @param {Help} helper276 * @returns {string}277 */278279 formatHelp(cmd, helper) {280 const termWidth = helper.padWidth(cmd, helper);281 const helpWidth = helper.helpWidth || 80;282 const itemIndentWidth = 2;283 const itemSeparatorWidth = 2; // between term and description284 function formatItem(term, description) {285 if (description) {286 const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;287 return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);288 }289 return term;290 };291 function formatList(textArray) {292 return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));293 }294295 // Usage296 let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];297298 // Description299 const commandDescription = helper.commandDescription(cmd);300 if (commandDescription.length > 0) {301 output = output.concat([commandDescription, '']);302 }303304 // Arguments305 const argumentList = helper.visibleArguments(cmd).map((argument) => {306 return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));307 });308 if (argumentList.length > 0) {309 output = output.concat(['Arguments:', formatList(argumentList), '']);310 }311312 // Options313 const optionList = helper.visibleOptions(cmd).map((option) => {314 return formatItem(helper.optionTerm(option), helper.optionDescription(option));315 });316 if (optionList.length > 0) {317 output = output.concat(['Options:', formatList(optionList), '']);318 }319320 // Commands321 const commandList = helper.visibleCommands(cmd).map((cmd) => {322 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));323 });324 if (commandList.length > 0) {325 output = output.concat(['Commands:', formatList(commandList), '']);326 }327328 return output.join('\n');329 }330331 /**332 * Calculate the pad width from the maximum term length.333 *334 * @param {Command} cmd335 * @param {Help} helper336 * @returns {number}337 */338339 padWidth(cmd, helper) {340 return Math.max(341 helper.longestOptionTermLength(cmd, helper),342 helper.longestSubcommandTermLength(cmd, helper),343 helper.longestArgumentTermLength(cmd, helper)344 );345 };346347 /**348 * Wrap the given string to width characters per line, with lines after the first indented.349 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.350 *351 * @param {string} str352 * @param {number} width353 * @param {number} indent354 * @param {number} [minColumnWidth=40]355 * @return {string}356 *357 */358359 wrap(str, width, indent, minColumnWidth = 40) {360 // Detect manually wrapped and indented strings by searching for line breaks361 // followed by multiple spaces/tabs.362 if (str.match(/[\n]\s+/)) return str;363 // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).364 const columnWidth = width - indent;365 if (columnWidth < minColumnWidth) return str;366367 const leadingStr = str.substr(0, indent);368 const columnText = str.substr(indent);369370 const indentString = ' '.repeat(indent);371 const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');372 const lines = columnText.match(regex) || [];373 return leadingStr + lines.map((line, i) => {374 if (line.slice(-1) === '\n') {375 line = line.slice(0, line.length - 1);376 }377 return ((i > 0) ? indentString : '') + line.trimRight();378 }).join('\n');379 }380}381382class Argument {383 /**384 * Initialize a new command argument with the given name and description.385 * The default is that the argument is required, and you can explicitly386 * indicate this with <> around the name. Put [] around the name for an optional argument.387 *388 * @param {string} name389 * @param {string} [description]390 */391392 constructor(name, description) {393 this.description = description || '';394 this.variadic = false;395 this.parseArg = undefined;396 this.defaultValue = undefined;397 this.defaultValueDescription = undefined;398399 switch (name[0]) {400 case '<': // e.g. <required>401 this.required = true;402 this._name = name.slice(1, -1);403 break;404 case '[': // e.g. [optional]405 this.required = false;406 this._name = name.slice(1, -1);407 break;408 default:409 this.required = true;410 this._name = name;411 break;412 }413414 if (this._name.length > 3 && this._name.slice(-3) === '...') {415 this.variadic = true;416 this._name = this._name.slice(0, -3);417 }418 }419420 /**421 * Return argument name.422 *423 * @return {string}424 */425426 name() {427 return this._name;428 };429430 /**431 * Set the default value, and optionally supply the description to be displayed in the help.432 *433 * @param {any} value434 * @param {string} [description]435 * @return {Argument}436 */437438 default(value, description) {439 this.defaultValue = value;440 this.defaultValueDescription = description;441 return this;442 };443444 /**445 * Set the custom handler for processing CLI command arguments into argument values.446 *447 * @param {Function} [fn]448 * @return {Argument}449 */450451 argParser(fn) {452 this.parseArg = fn;453 return this;454 };455}456457class Option {458 /**459 * Initialize a new `Option` with the given `flags` and `description`.460 *461 * @param {string} flags462 * @param {string} [description]463 */464465 constructor(flags, description) {466 this.flags = flags;467 this.description = description || '';468469 this.required = flags.includes('<'); // A value must be supplied when the option is specified.470 this.optional = flags.includes('['); // A value is optional when the option is specified.471 // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument472 this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.473 this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.474 const optionFlags = _parseOptionFlags(flags);475 this.short = optionFlags.shortFlag;476 this.long = optionFlags.longFlag;477 this.negate = false;478 if (this.long) {479 this.negate = this.long.startsWith('--no-');480 }481 this.defaultValue = undefined;482 this.defaultValueDescription = undefined;483 this.parseArg = undefined;484 this.hidden = false;485 this.argChoices = undefined;486 }487488 /**489 * Set the default value, and optionally supply the description to be displayed in the help.490 *491 * @param {any} value492 * @param {string} [description]493 * @return {Option}494 */495496 default(value, description) {497 this.defaultValue = value;498 this.defaultValueDescription = description;499 return this;500 };501502 /**503 * Set the custom handler for processing CLI option arguments into option values.504 *505 * @param {Function} [fn]506 * @return {Option}507 */508509 argParser(fn) {510 this.parseArg = fn;511 return this;512 };513514 /**515 * Whether the option is mandatory and must have a value after parsing.516 *517 * @param {boolean} [mandatory=true]518 * @return {Option}519 */520521 makeOptionMandatory(mandatory = true) {522 this.mandatory = !!mandatory;523 return this;524 };525526 /**527 * Hide option in help.528 *529 * @param {boolean} [hide=true]530 * @return {Option}531 */532533 hideHelp(hide = true) {534 this.hidden = !!hide;535 return this;536 };537538 /**539 * @api private540 */541542 _concatValue(value, previous) {543 if (previous === this.defaultValue || !Array.isArray(previous)) {544 return [value];545 }546547 return previous.concat(value);548 }549550 /**551 * Only allow option value to be one of choices.552 *553 * @param {string[]} values554 * @return {Option}555 */556557 choices(values) {558 this.argChoices = values;559 this.parseArg = (arg, previous) => {560 if (!values.includes(arg)) {561 throw new InvalidArgumentError(`Allowed choices are ${values.join(', ')}.`);562 }563 if (this.variadic) {564 return this._concatValue(arg, previous);565 }566 return arg;567 };568 return this;569 };570571 /**572 * Return option name.573 *574 * @return {string}575 */576577 name() {578 if (this.long) {579 return this.long.replace(/^--/, '');580 }581 return this.short.replace(/^-/, '');582 };583584 /**585 * Return option name, in a camelcase format that can be used586 * as a object attribute key.587 *588 * @return {string}589 * @api private590 */591592 attributeName() {593 return camelcase(this.name().replace(/^no-/, ''));594 };595596 /**597 * Check if `arg` matches the short or long flag.598 *599 * @param {string} arg600 * @return {boolean}601 * @api private602 */603604 is(arg) {605 return this.short === arg || this.long === arg;606 };607}6089/**610 * CommanderError class611 * @class612 */613class CommanderError extends Error {614 /**615 * Constructs the CommanderError class616 * @param {number} exitCode suggested exit code which could be used with process.exit617 * @param {string} code an id string representing the error618 * @param {string} message human-readable description of the error619 * @constructor620 */621 constructor(exitCode, code, message) {622 super(message);623 // properly capture stack trace in Node.js624 Error.captureStackTrace(this, this.constructor);625 this.name = this.constructor.name;626 this.code = code;627 this.exitCode = exitCode;628 this.nestedError = undefined;629 }630}631632/**633 * InvalidArgumentError class634 * @class635 */636class InvalidArgumentError extends CommanderError {637 /**638 * Constructs the InvalidArgumentError class639 * @param {string} [message] explanation of why argument is invalid640 * @constructor641 */642 constructor(message) {643 super(1, 'commander.invalidArgument', message);644 // properly capture stack trace in Node.js645 Error.captureStackTrace(this, this.constructor);646 this.name = this.constructor.name;647 }648}649650class Command extends EventEmitter {651 /**652 * Initialize a new `Command`.653 *654 * @param {string} [name]655 */656657 constructor(name) {658 super();659 this.commands = [];660 this.options = [];661 this.parent = null;662 this._allowUnknownOption = false;663 this._allowExcessArguments = true;664 this._args = [];665 this.rawArgs = null;666 this._scriptPath = null;667 this._name = name || '';668 this._optionValues = {};669 this._storeOptionsAsProperties = false;670 this._actionHandler = null;671 this._executableHandler = false;672 this._executableFile = null; // custom name for executable673 this._defaultCommandName = null;674 this._exitCallback = null;675 this._aliases = [];676 this._combineFlagAndOptionalValue = true;677 this._description = '';678 this._argsDescription = undefined; // legacy679 this._enablePositionalOptions = false;680 this._passThroughOptions = false;681 this._lifeCycleHooks = {}; // a hash of arrays682683 // see .configureOutput() for docs684 this._outputConfiguration = {685 writeOut: (str) => process.stdout.write(str),686 writeErr: (str) => process.stderr.write(str),687 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,688 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,689 outputError: (str, write) => write(str)690 };691692 this._hidden = false;693 this._hasHelpOption = true;694 this._helpFlags = '-h, --help';695 this._helpDescription = 'display help for command';696 this._helpShortFlag = '-h';697 this._helpLongFlag = '--help';698 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false699 this._helpCommandName = 'help';700 this._helpCommandnameAndArgs = 'help [command]';701 this._helpCommandDescription = 'display help for command';702 this._helpConfiguration = {};703 }704705 /**706 * Define a command.707 *708 * There are two styles of command: pay attention to where to put the description.709 *710 * Examples:711 *712 * // Command implemented using action handler (description is supplied separately to `.command`)713 * program714 * .command('clone <source> [destination]')715 * .description('clone a repository into a newly created directory')716 * .action((source, destination) => {717 * console.log('clone command called');718 * });719 *720 * // Command implemented using separate executable file (description is second parameter to `.command`)721 * program722 * .command('start <service>', 'start named service')723 * .command('stop [service]', 'stop named service, or all if no name supplied');724 *725 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`726 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)727 * @param {Object} [execOpts] - configuration options (for executable)728 * @return {Command} returns new command for action handler, or `this` for executable command729 */730731 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {732 let desc = actionOptsOrExecDesc;733 let opts = execOpts;734 if (typeof desc === 'object' && desc !== null) {735 opts = desc;736 desc = null;737 }738 opts = opts || {};739 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);740 const cmd = this.createCommand(name);741742 if (desc) {743 cmd.description(desc);744 cmd._executableHandler = true;745 }746 if (opts.isDefault) this._defaultCommandName = cmd._name;747748 cmd._outputConfiguration = this._outputConfiguration;749750 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden751 cmd._hasHelpOption = this._hasHelpOption;752 cmd._helpFlags = this._helpFlags;753 cmd._helpDescription = this._helpDescription;754 cmd._helpShortFlag = this._helpShortFlag;755 cmd._helpLongFlag = this._helpLongFlag;756 cmd._helpCommandName = this._helpCommandName;757 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;758 cmd._helpCommandDescription = this._helpCommandDescription;759 cmd._helpConfiguration = this._helpConfiguration;760 cmd._exitCallback = this._exitCallback;761 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;762 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;763 cmd._allowExcessArguments = this._allowExcessArguments;764 cmd._enablePositionalOptions = this._enablePositionalOptions;765766 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor767 if (args) cmd.arguments(args);768 this.commands.push(cmd);769 cmd.parent = this;770771 if (desc) return this;772 return cmd;773 };774775 /**776 * Factory routine to create a new unattached command.777 *778 * See .command() for creating an attached subcommand, which uses this routine to779 * create the command. You can override createCommand to customise subcommands.780 *781 * @param {string} [name]782 * @return {Command} new command783 */784785 createCommand(name) {786 return new Command(name);787 };788789 /**790 * You can customise the help with a subclass of Help by overriding createHelp,791 * or by overriding Help properties using configureHelp().792 *793 * @return {Help}794 */795796 createHelp() {797 return Object.assign(new Help(), this.configureHelp());798 };799800 /**801 * You can customise the help by overriding Help properties using configureHelp(),802 * or with a subclass of Help by overriding createHelp().803 *804 * @param {Object} [configuration] - configuration options805 * @return {Command|Object} `this` command for chaining, or stored configuration806 */807808 configureHelp(configuration) {809 if (configuration === undefined) return this._helpConfiguration;810811 this._helpConfiguration = configuration;812 return this;813 }814815 /**816 * The default output goes to stdout and stderr. You can customise this for special817 * applications. You can also customise the display of errors by overriding outputError.818 *819 * The configuration properties are all functions:820 *821 * // functions to change where being written, stdout and stderr822 * writeOut(str)823 * writeErr(str)824 * // matching functions to specify width for wrapping help825 * getOutHelpWidth()826 * getErrHelpWidth()827 * // functions based on what is being written out828 * outputError(str, write) // used for displaying errors, and not used for displaying help829 *830 * @param {Object} [configuration] - configuration options831 * @return {Command|Object} `this` command for chaining, or stored configuration832 */833834 configureOutput(configuration) {835 if (configuration === undefined) return this._outputConfiguration;836837 Object.assign(this._outputConfiguration, configuration);838 return this;839 }840841 /**842 * Add a prepared subcommand.843 *844 * See .command() for creating an attached subcommand which inherits settings from its parent.845 *846 * @param {Command} cmd - new subcommand847 * @param {Object} [opts] - configuration options848 * @return {Command} `this` command for chaining849 */850851 addCommand(cmd, opts) {852 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');853854 // To keep things simple, block automatic name generation for deeply nested executables.855 // Fail fast and detect when adding rather than later when parsing.856 function checkExplicitNames(commandArray) {857 commandArray.forEach((cmd) => {858 if (cmd._executableHandler && !cmd._executableFile) {859 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);860 }861 checkExplicitNames(cmd.commands);862 });863 }864 checkExplicitNames(cmd.commands);865866 opts = opts || {};867 if (opts.isDefault) this._defaultCommandName = cmd._name;868 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation869870 this.commands.push(cmd);871 cmd.parent = this;872 return this;873 };874875 /**876 * Factory routine to create a new unattached argument.877 *878 * See .argument() for creating an attached argument, which uses this routine to879 * create the argument. You can override createArgument to return a custom argument.880 *881 * @param {string} name882 * @param {string} [description]883 * @return {Argument} new argument884 */885886 createArgument(name, description) {887 return new Argument(name, description);888 };889890 /**891 * Define argument syntax for command.892 *893 * The default is that the argument is required, and you can explicitly894 * indicate this with <> around the name. Put [] around the name for an optional argument.895 *896 * @example897 *898 * program.argument('<input-file>');899 * program.argument('[output-file]');900 *901 * @param {string} name902 * @param {string} [description]903 * @param {Function|*} [fn] - custom argument processing function904 * @param {*} [defaultValue]905 * @return {Command} `this` command for chaining906 */907 argument(name, description, fn, defaultValue) {908 const argument = this.createArgument(name, description);909 if (typeof fn === 'function') {910 argument.default(defaultValue).argParser(fn);911 } else {912 argument.default(fn);913 }914 this.addArgument(argument);915 return this;916 }917918 /**919 * Define argument syntax for command, adding multiple at once (without descriptions).920 *921 * See also .argument().922 *923 * @example924 *925 * program.arguments('<cmd> [env]');926 *927 * @param {string} names928 * @return {Command} `this` command for chaining929 */930931 arguments(names) {932 names.split(/ +/).forEach((detail) => {933 this.argument(detail);934 });935 return this;936 };937938 /**939 * Define argument syntax for command, adding a prepared argument.940 *941 * @param {Argument} argument942 * @return {Command} `this` command for chaining943 */944 addArgument(argument) {945 const previousArgument = this._args.slice(-1)[0];946 if (previousArgument && previousArgument.variadic) {947 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);948 }949 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {950 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);951 }952 this._args.push(argument);953 return this;954 }955956 /**957 * Override default decision whether to add implicit help command.958 *959 * addHelpCommand() // force on960 * addHelpCommand(false); // force off961 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details962 *963 * @return {Command} `this` command for chaining964 */965966 addHelpCommand(enableOrNameAndArgs, description) {967 if (enableOrNameAndArgs === false) {968 this._addImplicitHelpCommand = false;969 } else {970 this._addImplicitHelpCommand = true;971 if (typeof enableOrNameAndArgs === 'string') {972 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];973 this._helpCommandnameAndArgs = enableOrNameAndArgs;974 }975 this._helpCommandDescription = description || this._helpCommandDescription;976 }977 return this;978 };979980 /**981 * @return {boolean}982 * @api private983 */984985 _hasImplicitHelpCommand() {986 if (this._addImplicitHelpCommand === undefined) {987 return this.commands.length && !this._actionHandler && !this._findCommand('help');988 }989 return this._addImplicitHelpCommand;990 };991992 /**993 * Add hook for life cycle event.994 *995 * @param {string} event996 * @param {Function} listener997 * @return {Command} `this` command for chaining998 */9991000 hook(event, listener) {1001 const allowedValues = ['preAction', 'postAction'];1002 if (!allowedValues.includes(event)) {1003 throw new Error(`Unexpected value for event passed to hook : '${event}'.1004Expecting one of '${allowedValues.join("', '")}'`);1005 }1006 if (this._lifeCycleHooks[event]) {1007 this._lifeCycleHooks[event].push(listener);1008 } else {1009 this._lifeCycleHooks[event] = [listener];1010 }1011 return this;1012 }10131014 /**1015 * Register callback to use as replacement for calling process.exit.1016 *1017 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing1018 * @return {Command} `this` command for chaining1019 */10201021 exitOverride(fn) {1022 if (fn) {1023 this._exitCallback = fn;1024 } else {1025 this._exitCallback = (err) => {1026 if (err.code !== 'commander.executeSubCommandAsync') {1027 throw err;1028 } else {1029 // Async callback from spawn events, not useful to throw.1030 }1031 };1032 }1033 return this;1034 };10351036 /**1037 * Call process.exit, and _exitCallback if defined.1038 *1039 * @param {number} exitCode exit code for using with process.exit1040 * @param {string} code an id string representing the error1041 * @param {string} message human-readable description of the error1042 * @return never1043 * @api private1044 */10451046 _exit(exitCode, code, message) {1047 if (this._exitCallback) {1048 this._exitCallback(new CommanderError(exitCode, code, message));1049 // Expecting this line is not reached.1050 }1051 process.exit(exitCode);1052 };10531054 /**1055 * Register callback `fn` for the command.1056 *1057 * Examples:1058 *1059 * program1060 * .command('help')1061 * .description('display verbose help')1062 * .action(function() {1063 * // output help here1064 * });1065 *1066 * @param {Function} fn1067 * @return {Command} `this` command for chaining1068 */10691070 action(fn) {1071 const listener = (args) => {1072 // The .action callback takes an extra parameter which is the command or options.1073 const expectedArgsCount = this._args.length;1074 const actionArgs = args.slice(0, expectedArgsCount);1075 if (this._storeOptionsAsProperties) {1076 actionArgs[expectedArgsCount] = this; // backwards compatible "options"1077 } else {1078 actionArgs[expectedArgsCount] = this.opts();1079 }1080 actionArgs.push(this);10811082 return fn.apply(this, actionArgs);1083 };1084 this._actionHandler = listener;1085 return this;1086 };10871088 /**1089 * Factory routine to create a new unattached option.1090 *1091 * See .option() for creating an attached option, which uses this routine to1092 * create the option. You can override createOption to return a custom option.1093 *1094 * @param {string} flags1095 * @param {string} [description]1096 * @return {Option} new option1097 */10981099 createOption(flags, description) {1100 return new Option(flags, description);1101 };11021103 /**1104 * Add an option.1105 *1106 * @param {Option} option1107 * @return {Command} `this` command for chaining1108 */1109 addOption(option) {1110 const oname = option.name();1111 const name = option.attributeName();11121113 let defaultValue = option.defaultValue;11141115 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value1116 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {1117 // when --no-foo we make sure default is true, unless a --foo option is already defined1118 if (option.negate) {1119 const positiveLongFlag = option.long.replace(/^--no-/, '--');1120 defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;1121 }1122 // preassign only if we have a default1123 if (defaultValue !== undefined) {1124 this.setOptionValue(name, defaultValue);1125 }1126 }11271128 // register the option1129 this.options.push(option);11301131 // when it's passed assign the value1132 // and conditionally invoke the callback1133 this.on('option:' + oname, (val) => {1134 const oldValue = this.getOptionValue(name);11351136 // custom processing1137 if (val !== null && option.parseArg) {1138 try {1139 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);1140 } catch (err) {1141 if (err.code === 'commander.invalidArgument') {1142 const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;1143 this._displayError(err.exitCode, err.code, message);1144 }1145 throw err;1146 }1147 } else if (val !== null && option.variadic) {1148 val = option._concatValue(val, oldValue);1149 }11501151 // unassigned or boolean value1152 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {1153 // if no value, negate false, and we have a default, then use it!1154 if (val == null) {1155 this.setOptionValue(name, option.negate1156 ? false1157 : defaultValue || true);1158 } else {1159 this.setOptionValue(name, val);1160 }1161 } else if (val !== null) {1162 // reassign1163 this.setOptionValue(name, option.negate ? false : val);1164 }1165 });11661167 return this;1168 }11691170 /**1171 * Internal implementation shared by .option() and .requiredOption()1172 *1173 * @api private1174 */1175 _optionEx(config, flags, description, fn, defaultValue) {1176 const option = this.createOption(flags, description);1177 option.makeOptionMandatory(!!config.mandatory);1178 if (typeof fn === 'function') {1179 option.default(defaultValue).argParser(fn);1180 } else if (fn instanceof RegExp) {1181 // deprecated1182 const regex = fn;1183 fn = (val, def) => {1184 const m = regex.exec(val);1185 return m ? m[0] : def;1186 };1187 option.default(defaultValue).argParser(fn);1188 } else {1189 option.default(fn);1190 }11911192 return this.addOption(option);1193 }11941195 /**1196 * Define option with `flags`, `description` and optional1197 * coercion `fn`.1198 *1199 * The `flags` string contains the short and/or long flags,1200 * separated by comma, a pipe or space. The following are all valid1201 * all will output this way when `--help` is used.1202 *1203 * "-p, --pepper"1204 * "-p|--pepper"1205 * "-p --pepper"1206 *1207 * Examples:1208 *1209 * // simple boolean defaulting to undefined1210 * program.option('-p, --pepper', 'add pepper');1211 *1212 * program.pepper1213 * // => undefined1214 *1215 * --pepper1216 * program.pepper1217 * // => true1218 *1219 * // simple boolean defaulting to true (unless non-negated option is also defined)1220 * program.option('-C, --no-cheese', 'remove cheese');1221 *1222 * program.cheese1223 * // => true1224 *1225 * --no-cheese1226 * program.cheese1227 * // => false1228 *1229 * // required argument1230 * program.option('-C, --chdir <path>', 'change the working directory');1231 *1232 * --chdir /tmp1233 * program.chdir1234 * // => "/tmp"1235 *1236 * // optional argument1237 * program.option('-c, --cheese [type]', 'add cheese [marble]');1238 *1239 * @param {string} flags1240 * @param {string} [description]1241 * @param {Function|*} [fn] - custom option processing function or default value1242 * @param {*} [defaultValue]1243 * @return {Command} `this` command for chaining1244 */12451246 option(flags, description, fn, defaultValue) {1247 return this._optionEx({}, flags, description, fn, defaultValue);1248 };12491250 /**1251 * Add a required option which must have a value after parsing. This usually means1252 * the option must be specified on the command line. (Otherwise the same as .option().)1253 *1254 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.1255 *1256 * @param {string} flags1257 * @param {string} [description]1258 * @param {Function|*} [fn] - custom option processing function or default value1259 * @param {*} [defaultValue]1260 * @return {Command} `this` command for chaining1261 */12621263 requiredOption(flags, description, fn, defaultValue) {1264 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);1265 };12661267 /**1268 * Alter parsing of short flags with optional values.1269 *1270 * Examples:1271 *1272 * // for `.option('-f,--flag [value]'):1273 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour1274 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`1275 *1276 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.1277 */1278 combineFlagAndOptionalValue(combine = true) {1279 this._combineFlagAndOptionalValue = !!combine;1280 return this;1281 };12821283 /**1284 * Allow unknown options on the command line.1285 *1286 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown1287 * for unknown options.1288 */1289 allowUnknownOption(allowUnknown = true) {1290 this._allowUnknownOption = !!allowUnknown;1291 return this;1292 };12931294 /**1295 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.1296 *1297 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown1298 * for excess arguments.1299 */1300 allowExcessArguments(allowExcess = true) {1301 this._allowExcessArguments = !!allowExcess;1302 return this;1303 };13041305 /**1306 * Enable positional options. Positional means global options are specified before subcommands which lets1307 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.1308 * The default behaviour is non-positional and global options may appear anywhere on the command line.1309 *1310 * @param {Boolean} [positional=true]1311 */1312 enablePositionalOptions(positional = true) {1313 this._enablePositionalOptions = !!positional;1314 return this;1315 };13161317 /**1318 * Pass through options that come after command-arguments rather than treat them as command-options,1319 * so actual command-options come before command-arguments. Turning this on for a subcommand requires1320 * positional options to have been enabled on the program (parent commands).1321 * The default behaviour is non-positional and options may appear before or after command-arguments.1322 *1323 * @param {Boolean} [passThrough=true]1324 * for unknown options.1325 */1326 passThroughOptions(passThrough = true) {1327 this._passThroughOptions = !!passThrough;1328 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {1329 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');1330 }1331 return this;1332 };13331334 /**1335 * Whether to store option values as properties on command object,1336 * or store separately (specify false). In both cases the option values can be accessed using .opts().1337 *1338 * @param {boolean} [storeAsProperties=true]1339 * @return {Command} `this` command for chaining1340 */13411342 storeOptionsAsProperties(storeAsProperties = true) {1343 this._storeOptionsAsProperties = !!storeAsProperties;1344 if (this.options.length) {1345 throw new Error('call .storeOptionsAsProperties() before adding options');1346 }1347 return this;1348 };13491350 /**1351 * Retrieve option value.1352 *1353 * @param {string} key1354 * @return {Object} value1355 */13561357 getOptionValue(key) {1358 if (this._storeOptionsAsProperties) {1359 return this[key];1360 }1361 return this._optionValues[key];1362 };13631364 /**1365 * Store option value.1366 *1367 * @param {string} key1368 * @param {Object} value1369 * @return {Command} `this` command for chaining1370 */13711372 setOptionValue(key, value) {1373 if (this._storeOptionsAsProperties) {1374 this[key] = value;1375 } else {1376 this._optionValues[key] = value;1377 }1378 return this;1379 };13801381 /**1382 * Get user arguments implied or explicit arguments.1383 * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.1384 *1385 * @api private1386 */13871388 _prepareUserArgs(argv, parseOptions) {1389 if (argv !== undefined && !Array.isArray(argv)) {1390 throw new Error('first parameter to parse must be array or undefined');1391 }1392 parseOptions = parseOptions || {};13931394 // Default to using process.argv1395 if (argv === undefined) {1396 argv = process.argv;1397 // @ts-ignore: unknown property1398 if (process.versions && process.versions.electron) {1399 parseOptions.from = 'electron';1400 }1401 }1402 this.rawArgs = argv.slice();14031404 // make it a little easier for callers by supporting various argv conventions1405 let userArgs;1406 switch (parseOptions.from) {1407 case undefined:1408 case 'node':1409 this._scriptPath = argv[1];1410 userArgs = argv.slice(2);1411 break;1412 case 'electron':1413 // @ts-ignore: unknown property1414 if (process.defaultApp) {1415 this._scriptPath = argv[1];1416 userArgs = argv.slice(2);1417 } else {1418 userArgs = argv.slice(1);1419 }1420 break;1421 case 'user':1422 userArgs = argv.slice(0);1423 break;1424 default:1425 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);1426 }1427 if (!this._scriptPath && require.main) {1428 this._scriptPath = require.main.filename;1429 }14301431 // Guess name, used in usage in help.1432 this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));14331434 return userArgs;1435 }14361437 /**1438 * Parse `argv`, setting options and invoking commands when defined.1439 *1440 * The default expectation is that the arguments are from node and have the application as argv[0]1441 * and the script being run in argv[1], with user parameters after that.1442 *1443 * Examples:1444 *1445 * program.parse(process.argv);1446 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions1447 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1448 *1449 * @param {string[]} [argv] - optional, defaults to process.argv1450 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron1451 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1452 * @return {Command} `this` command for chaining1453 */14541455 parse(argv, parseOptions) {1456 const userArgs = this._prepareUserArgs(argv, parseOptions);1457 this._parseCommand([], userArgs);14581459 return this;1460 };14611462 /**1463 * Parse `argv`, setting options and invoking commands when defined.1464 *1465 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.1466 *1467 * The default expectation is that the arguments are from node and have the application as argv[0]1468 * and the script being run in argv[1], with user parameters after that.1469 *1470 * Examples:1471 *1472 * await program.parseAsync(process.argv);1473 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1474 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1475 *1476 * @param {string[]} [argv]1477 * @param {Object} [parseOptions]1478 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1479 * @return {Promise}1480 */14811482 async parseAsync(argv, parseOptions) {1483 const userArgs = this._prepareUserArgs(argv, parseOptions);1484 await this._parseCommand([], userArgs);14851486 return this;1487 };14881489 /**1490 * Execute a sub-command executable.1491 *1492 * @api private1493 */14941495 _executeSubCommand(subcommand, args) {1496 args = args.slice();1497 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1498 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];14991500 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1501 this._checkForMissingMandatoryOptions();15021503 // Want the entry script as the reference for command name and directory for searching for other files.1504 let scriptPath = this._scriptPath;1505 // Fallback in case not set, due to how Command created or called.1506 if (!scriptPath && require.main) {1507 scriptPath = require.main.filename;1508 }15091510 let baseDir;1511 try {1512 const resolvedLink = fs.realpathSync(scriptPath);1513 baseDir = path.dirname(resolvedLink);1514 } catch (e) {1515 baseDir = '.'; // dummy, probably not going to find executable!1516 }15171518 // name of the subcommand, like `pm-install`1519 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;1520 if (subcommand._executableFile) {1521 bin = subcommand._executableFile;1522 }15231524 const localBin = path.join(baseDir, bin);1525 if (fs.existsSync(localBin)) {1526 // prefer local `./<bin>` to bin in the $PATH1527 bin = localBin;1528 } else {1529 // Look for source files.1530 sourceExt.forEach((ext) => {1531 if (fs.existsSync(`${localBin}${ext}`)) {1532 bin = `${localBin}${ext}`;1533 }1534 });1535 }1536 launchWithNode = sourceExt.includes(path.extname(bin));15371538 let proc;1539 if (process.platform !== 'win32') {1540 if (launchWithNode) {1541 args.unshift(bin);1542 // add executable arguments to spawn1543 args = incrementNodeInspectorPort(process.execArgv).concat(args);15441545 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1546 } else {1547 proc = childProcess.spawn(bin, args, { stdio: 'inherit' });1548 }1549 } else {1550 args.unshift(bin);1551 // add executable arguments to spawn1552 args = incrementNodeInspectorPort(process.execArgv).concat(args);1553 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1554 }15551556 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1557 signals.forEach((signal) => {1558 // @ts-ignore1559 process.on(signal, () => {1560 if (proc.killed === false && proc.exitCode === null) {1561 proc.kill(signal);1562 }1563 });1564 });15651566 // By default terminate process when spawned process terminates.1567 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1568 const exitCallback = this._exitCallback;1569 if (!exitCallback) {1570 proc.on('close', process.exit.bind(process));1571 } else {1572 proc.on('close', () => {1573 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1574 });1575 }1576 proc.on('error', (err) => {1577 // @ts-ignore1578 if (err.code === 'ENOENT') {1579 const executableMissing = `'${bin}' does not exist1580 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1581 - if the default executable name is not suitable, use the executableFile option to supply a custom name`;1582 throw new Error(executableMissing);1583 // @ts-ignore1584 } else if (err.code === 'EACCES') {1585 throw new Error(`'${bin}' not executable`);1586 }1587 if (!exitCallback) {1588 process.exit(1);1589 } else {1590 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1591 wrappedError.nestedError = err;1592 exitCallback(wrappedError);1593 }1594 });15951596 // Store the reference to the child process1597 this.runningCommand = proc;1598 };15991600 /**1601 * @api private1602 */16031604 _dispatchSubcommand(commandName, operands, unknown) {1605 const subCommand = this._findCommand(commandName);1606 if (!subCommand) this.help({ error: true });16071608 if (subCommand._executableHandler) {1609 this._executeSubCommand(subCommand, operands.concat(unknown));1610 } else {1611 return subCommand._parseCommand(operands, unknown);1612 }1613 };16141615 /**1616 * Package arguments (this.args) for passing to action handler based1617 * on declared arguments (this._args).1618 *1619 * @api private1620 */16211622 _getActionArguments() {1623 const myParseArg = (argument, value, previous) => {1624 // Extra processing for nice error message on parsing failure.1625 let parsedValue = value;1626 if (value !== null && argument.parseArg) {1627 try {1628 parsedValue = argument.parseArg(value, previous);1629 } catch (err) {1630 if (err.code === 'commander.invalidArgument') {1631 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1632 this._displayError(err.exitCode, err.code, message);1633 }1634 throw err;1635 }1636 }1637 return parsedValue;1638 };16391640 const actionArgs = [];1641 this._args.forEach((declaredArg, index) => {1642 let value = declaredArg.defaultValue;1643 if (declaredArg.variadic) {1644 // Collect together remaining arguments for passing together as an array.1645 if (index < this.args.length) {1646 value = this.args.slice(index);1647 if (declaredArg.parseArg) {1648 value = value.reduce((processed, v) => {1649 return myParseArg(declaredArg, v, processed);1650 }, declaredArg.defaultValue);1651 }1652 } else if (value === undefined) {1653 value = [];1654 }1655 } else if (index < this.args.length) {1656 value = this.args[index];1657 if (declaredArg.parseArg) {1658 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1659 }1660 }1661 actionArgs[index] = value;1662 });1663 return actionArgs;1664 }16651666 /**1667 * Once we have a promise we chain, but call synchronously until then.1668 *1669 * @param {Promise|undefined} promise1670 * @param {Function} fn1671 * @return {Promise|undefined}1672 */16731674 _chainOrCall(promise, fn) {1675 // thenable1676 if (promise && promise.then && typeof promise.then === 'function') {1677 // already have a promise, chain callback1678 return promise.then(() => fn());1679 }1680 // callback might return a promise1681 return fn();1682 }16831684 /**1685 *1686 * @param {Promise|undefined} promise1687 * @param {string} event1688 * @return {Promise|undefined}1689 * @api private1690 */16911692 _chainOrCallHooks(promise, event) {1693 let result = promise;1694 const hooks = [];1695 getCommandAndParents(this)1696 .reverse()1697 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1698 .forEach(hookedCommand => {1699 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1700 hooks.push({ hookedCommand, callback });1701 });1702 });1703 if (event === 'postAction') {1704 hooks.reverse();1705 }17061707 hooks.forEach((hookDetail) => {1708 result = this._chainOrCall(result, () => {1709 return hookDetail.callback(hookDetail.hookedCommand, this);1710 });1711 });1712 return result;1713 }17141715 /**1716 * Process arguments in context of this command.1717 * Returns action result, in case it is a promise.1718 *1719 * @api private1720 */17211722 _parseCommand(operands, unknown) {1723 const parsed = this.parseOptions(unknown);1724 operands = operands.concat(parsed.operands);1725 unknown = parsed.unknown;1726 this.args = operands.concat(unknown);17271728 if (operands && this._findCommand(operands[0])) {1729 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1730 }1731 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1732 if (operands.length === 1) {1733 this.help();1734 }1735 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1736 }1737 if (this._defaultCommandName) {1738 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1739 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1740 }1741 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1742 // probably missing subcommand and no handler, user needs help (and exit)1743 this.help({ error: true });1744 }17451746 outputHelpIfRequested(this, parsed.unknown);1747 this._checkForMissingMandatoryOptions();17481749 // We do not always call this check to avoid masking a "better" error, like unknown command.1750 const checkForUnknownOptions = () => {1751 if (parsed.unknown.length > 0) {1752 this.unknownOption(parsed.unknown[0]);1753 }1754 };1755 const checkNumberOfArguments = () => {1756 // too few1757 this._args.forEach((arg, i) => {1758 if (arg.required && this.args[i] == null) {1759 this.missingArgument(arg.name());1760 }1761 });1762 // too many1763 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1764 return;1765 }1766 if (this.args.length > this._args.length) {1767 this._excessArguments(this.args);1768 }1769 };17701771 const commandEvent = `command:${this.name()}`;1772 if (this._actionHandler) {1773 checkForUnknownOptions();1774 checkNumberOfArguments();17751776 let actionResult;1777 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1778 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this._getActionArguments()));1779 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1780 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1781 return actionResult;1782 }1783 if (this.parent && this.parent.listenerCount(commandEvent)) {1784 checkForUnknownOptions();1785 checkNumberOfArguments();1786 this.parent.emit(commandEvent, operands, unknown); // legacy1787 } else if (operands.length) {1788 if (this._findCommand('*')) { // legacy default command1789 return this._dispatchSubcommand('*', operands, unknown);1790 }1791 if (this.listenerCount('command:*')) {1792 // skip option check, emit event for possible misspelling suggestion1793 this.emit('command:*', operands, unknown);1794 } else if (this.commands.length) {1795 this.unknownCommand();1796 } else {1797 checkForUnknownOptions();1798 checkNumberOfArguments();1799 }1800 } else if (this.commands.length) {1801 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1802 this.help({ error: true });1803 } else {1804 checkForUnknownOptions();1805 checkNumberOfArguments();1806 // fall through for caller to handle after calling .parse()1807 }1808 };18091810 /**1811 * Find matching command.1812 *1813 * @api private1814 */1815 _findCommand(name) {1816 if (!name) return undefined;1817 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1818 };18191820 /**1821 * Return an option matching `arg` if any.1822 *1823 * @param {string} arg1824 * @return {Option}1825 * @api private1826 */18271828 _findOption(arg) {1829 return this.options.find(option => option.is(arg));1830 };18311832 /**1833 * Display an error message if a mandatory option does not have a value.1834 * Lazy calling after checking for help flags from leaf subcommand.1835 *1836 * @api private1837 */18381839 _checkForMissingMandatoryOptions() {1840 // Walk up hierarchy so can call in subcommand after checking for displaying help.1841 for (let cmd = this; cmd; cmd = cmd.parent) {1842 cmd.options.forEach((anOption) => {1843 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1844 cmd.missingMandatoryOptionValue(anOption);1845 }1846 });1847 }1848 };18491850 /**1851 * Parse options from `argv` removing known options,1852 * and return argv split into operands and unknown arguments.1853 *1854 * Examples:1855 *1856 * argv => operands, unknown1857 * --known kkk op => [op], []1858 * op --known kkk => [op], []1859 * sub --unknown uuu op => [sub], [--unknown uuu op]1860 * sub -- --unknown uuu op => [sub --unknown uuu op], []1861 *1862 * @param {String[]} argv1863 * @return {{operands: String[], unknown: String[]}}1864 */18651866 parseOptions(argv) {1867 const operands = []; // operands, not options or values1868 const unknown = []; // first unknown option and remaining unknown args1869 let dest = operands;1870 const args = argv.slice();18711872 function maybeOption(arg) {1873 return arg.length > 1 && arg[0] === '-';1874 }18751876 // parse options1877 let activeVariadicOption = null;1878 while (args.length) {1879 const arg = args.shift();18801881 // literal1882 if (arg === '--') {1883 if (dest === unknown) dest.push(arg);1884 dest.push(...args);1885 break;1886 }18871888 if (activeVariadicOption && !maybeOption(arg)) {1889 this.emit(`option:${activeVariadicOption.name()}`, arg);1890 continue;1891 }1892 activeVariadicOption = null;18931894 if (maybeOption(arg)) {1895 const option = this._findOption(arg);1896 // recognised option, call listener to assign value with possible custom processing1897 if (option) {1898 if (option.required) {1899 const value = args.shift();1900 if (value === undefined) this.optionMissingArgument(option);1901 this.emit(`option:${option.name()}`, value);1902 } else if (option.optional) {1903 let value = null;1904 // historical behaviour is optional value is following arg unless an option1905 if (args.length > 0 && !maybeOption(args[0])) {1906 value = args.shift();1907 }1908 this.emit(`option:${option.name()}`, value);1909 } else { // boolean flag1910 this.emit(`option:${option.name()}`);1911 }1912 activeVariadicOption = option.variadic ? option : null;1913 continue;1914 }1915 }19161917 // Look for combo options following single dash, eat first one if known.1918 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1919 const option = this._findOption(`-${arg[1]}`);1920 if (option) {1921 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1922 // option with value following in same argument1923 this.emit(`option:${option.name()}`, arg.slice(2));1924 } else {1925 // boolean option, emit and put back remainder of arg for further processing1926 this.emit(`option:${option.name()}`);1927 args.unshift(`-${arg.slice(2)}`);1928 }1929 continue;1930 }1931 }19321933 // Look for known long flag with value, like --foo=bar1934 if (/^--[^=]+=/.test(arg)) {1935 const index = arg.indexOf('=');1936 const option = this._findOption(arg.slice(0, index));1937 if (option && (option.required || option.optional)) {1938 this.emit(`option:${option.name()}`, arg.slice(index + 1));1939 continue;1940 }1941 }19421943 // Not a recognised option by this command.1944 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.19451946 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1947 if (maybeOption(arg)) {1948 dest = unknown;1949 }19501951 // If using positionalOptions, stop processing our options at subcommand.1952 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1953 if (this._findCommand(arg)) {1954 operands.push(arg);1955 if (args.length > 0) unknown.push(...args);1956 break;1957 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1958 operands.push(arg);1959 if (args.length > 0) operands.push(...args);1960 break;1961 } else if (this._defaultCommandName) {1962 unknown.push(arg);1963 if (args.length > 0) unknown.push(...args);1964 break;1965 }1966 }19671968 // If using passThroughOptions, stop processing options at first command-argument.1969 if (this._passThroughOptions) {1970 dest.push(arg);1971 if (args.length > 0) dest.push(...args);1972 break;1973 }19741975 // add arg1976 dest.push(arg);1977 }19781979 return { operands, unknown };1980 };19811982 /**1983 * Return an object containing options as key-value pairs1984 *1985 * @return {Object}1986 */1987 opts() {1988 if (this._storeOptionsAsProperties) {1989 // Preserve original behaviour so backwards compatible when still using properties1990 const result = {};1991 const len = this.options.length;19921993 for (let i = 0; i < len; i++) {1994 const key = this.options[i].attributeName();1995 result[key] = key === this._versionOptionName ? this._version : this[key];1996 }1997 return result;1998 }19992000 return this._optionValues;2001 };20022003 /**2004 * Internal bottleneck for handling of parsing errors.2005 *2006 * @api private2007 */2008 _displayError(exitCode, code, message) {2009 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);2010 this._exit(exitCode, code, message);2011 }20122013 /**2014 * Argument `name` is missing.2015 *2016 * @param {string} name2017 * @api private2018 */20192020 missingArgument(name) {2021 const message = `error: missing required argument '${name}'`;2022 this._displayError(1, 'commander.missingArgument', message);2023 };20242025 /**2026 * `Option` is missing an argument.2027 *2028 * @param {Option} option2029 * @api private2030 */20312032 optionMissingArgument(option) {2033 const message = `error: option '${option.flags}' argument missing`;2034 this._displayError(1, 'commander.optionMissingArgument', message);2035 };20362037 /**2038 * `Option` does not have a value, and is a mandatory option.2039 *2040 * @param {Option} option2041 * @api private2042 */20432044 missingMandatoryOptionValue(option) {2045 const message = `error: required option '${option.flags}' not specified`;2046 this._displayError(1, 'commander.missingMandatoryOptionValue', message);2047 };20482049 /**2050 * Unknown option `flag`.2051 *2052 * @param {string} flag2053 * @api private2054 */20552056 unknownOption(flag) {2057 if (this._allowUnknownOption) return;2058 const message = `error: unknown option '${flag}'`;2059 this._displayError(1, 'commander.unknownOption', message);2060 };20612062 /**2063 * Excess arguments, more than expected.2064 *2065 * @param {string[]} receivedArgs2066 * @api private2067 */20682069 _excessArguments(receivedArgs) {2070 if (this._allowExcessArguments) return;20712072 const expected = this._args.length;2073 const s = (expected === 1) ? '' : 's';2074 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';2075 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;2076 this._displayError(1, 'commander.excessArguments', message);2077 };20782079 /**2080 * Unknown command.2081 *2082 * @api private2083 */20842085 unknownCommand() {2086 const partCommands = [this.name()];2087 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {2088 partCommands.unshift(parentCmd.name());2089 }2090 const fullCommand = partCommands.join(' ');2091 const message = `error: unknown command '${this.args[0]}'.` +2092 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');2093 this._displayError(1, 'commander.unknownCommand', message);2094 };20952096 /**2097 * Set the program version to `str`.2098 *2099 * This method auto-registers the "-V, --version" flag2100 * which will print the version number when passed.2101 *2102 * You can optionally supply the flags and description to override the defaults.2103 *2104 * @param {string} str2105 * @param {string} [flags]2106 * @param {string} [description]2107 * @return {this | string} `this` command for chaining, or version string if no arguments2108 */21092110 version(str, flags, description) {2111 if (str === undefined) return this._version;2112 this._version = str;2113 flags = flags || '-V, --version';2114 description = description || 'output the version number';2115 const versionOption = this.createOption(flags, description);2116 this._versionOptionName = versionOption.attributeName();2117 this.options.push(versionOption);2118 this.on('option:' + versionOption.name(), () => {2119 this._outputConfiguration.writeOut(`${str}\n`);2120 this._exit(0, 'commander.version', str);2121 });2122 return this;2123 };21242125 /**2126 * Set the description to `str`.2127 *2128 * @param {string} [str]2129 * @param {Object} [argsDescription]2130 * @return {string|Command}2131 */2132 description(str, argsDescription) {2133 if (str === undefined && argsDescription === undefined) return this._description;2134 this._description = str;2135 if (argsDescription) {2136 this._argsDescription = argsDescription;2137 }2138 return this;2139 };21402141 /**2142 * Set an alias for the command.2143 *2144 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.2145 *2146 * @param {string} [alias]2147 * @return {string|Command}2148 */21492150 alias(alias) {2151 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility21522153 let command = this;2154 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {2155 // assume adding alias for last added executable subcommand, rather than this2156 command = this.commands[this.commands.length - 1];2157 }21582159 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');21602161 command._aliases.push(alias);2162 return this;2163 };21642165 /**2166 * Set aliases for the command.2167 *2168 * Only the first alias is shown in the auto-generated help.2169 *2170 * @param {string[]} [aliases]2171 * @return {string[]|Command}2172 */21732174 aliases(aliases) {2175 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().2176 if (aliases === undefined) return this._aliases;21772178 aliases.forEach((alias) => this.alias(alias));2179 return this;2180 };21812182 /**2183 * Set / get the command usage `str`.2184 *2185 * @param {string} [str]2186 * @return {String|Command}2187 */21882189 usage(str) {2190 if (str === undefined) {2191 if (this._usage) return this._usage;21922193 const args = this._args.map((arg) => {2194 return humanReadableArgName(arg);2195 });2196 return [].concat(2197 (this.options.length || this._hasHelpOption ? '[options]' : []),2198 (this.commands.length ? '[command]' : []),2199 (this._args.length ? args : [])2200 ).join(' ');2201 }22022203 this._usage = str;2204 return this;2205 };22062207 /**2208 * Get or set the name of the command2209 *2210 * @param {string} [str]2211 * @return {string|Command}2212 */22132214 name(str) {2215 if (str === undefined) return this._name;2216 this._name = str;2217 return this;2218 };22192220 /**2221 * Return program help documentation.2222 *2223 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout2224 * @return {string}2225 */22262227 helpInformation(contextOptions) {2228 const helper = this.createHelp();2229 if (helper.helpWidth === undefined) {2230 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();2231 }2232 return helper.formatHelp(this, helper);2233 };22342235 /**2236 * @api private2237 */22382239 _getHelpContext(contextOptions) {2240 contextOptions = contextOptions || {};2241 const context = { error: !!contextOptions.error };2242 let write;2243 if (context.error) {2244 write = (arg) => this._outputConfiguration.writeErr(arg);2245 } else {2246 write = (arg) => this._outputConfiguration.writeOut(arg);2247 }2248 context.write = contextOptions.write || write;2249 context.command = this;2250 return context;2251 }22522253 /**2254 * Output help information for this command.2255 *2256 * Outputs built-in help, and custom text added using `.addHelpText()`.2257 *2258 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout2259 */22602261 outputHelp(contextOptions) {2262 let deprecatedCallback;2263 if (typeof contextOptions === 'function') {2264 deprecatedCallback = contextOptions;2265 contextOptions = undefined;2266 }2267 const context = this._getHelpContext(contextOptions);22682269 const groupListeners = [];2270 let command = this;2271 while (command) {2272 groupListeners.push(command); // ordered from current command to root2273 command = command.parent;2274 }22752276 groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));2277 this.emit('beforeHelp', context);22782279 let helpInformation = this.helpInformation(context);2280 if (deprecatedCallback) {2281 helpInformation = deprecatedCallback(helpInformation);2282 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {2283 throw new Error('outputHelp callback must return a string or a Buffer');2284 }2285 }2286 context.write(helpInformation);22872288 this.emit(this._helpLongFlag); // deprecated2289 this.emit('afterHelp', context);2290 groupListeners.forEach(command => command.emit('afterAllHelp', context));2291 };22922293 /**2294 * You can pass in flags and a description to override the help2295 * flags and help description for your command. Pass in false to2296 * disable the built-in help option.2297 *2298 * @param {string | boolean} [flags]2299 * @param {string} [description]2300 * @return {Command} `this` command for chaining2301 */23022303 helpOption(flags, description) {2304 if (typeof flags === 'boolean') {2305 this._hasHelpOption = flags;2306 return this;2307 }2308 this._helpFlags = flags || this._helpFlags;2309 this._helpDescription = description || this._helpDescription;23102311 const helpFlags = _parseOptionFlags(this._helpFlags);2312 this._helpShortFlag = helpFlags.shortFlag;2313 this._helpLongFlag = helpFlags.longFlag;23142315 return this;2316 };23172318 /**2319 * Output help information and exit.2320 *2321 * Outputs built-in help, and custom text added using `.addHelpText()`.2322 *2323 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout2324 */23252326 help(contextOptions) {2327 this.outputHelp(contextOptions);2328 let exitCode = process.exitCode || 0;2329 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {2330 exitCode = 1;2331 }2332 // message: do not have all displayed text available so only passing placeholder.2333 this._exit(exitCode, 'commander.help', '(outputHelp)');2334 };23352336 /**2337 * Add additional text to be displayed with the built-in help.2338 *2339 * Position is 'before' or 'after' to affect just this command,2340 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.2341 *2342 * @param {string} position - before or after built-in help2343 * @param {string | Function} text - string to add, or a function returning a string2344 * @return {Command} `this` command for chaining2345 */2346 addHelpText(position, text) {2347 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];2348 if (!allowedValues.includes(position)) {2349 throw new Error(`Unexpected value for position to addHelpText.2350Expecting one of '${allowedValues.join("', '")}'`);2351 }2352 const helpEvent = `${position}Help`;2353 this.on(helpEvent, (context) => {2354 let helpStr;2355 if (typeof text === 'function') {2356 helpStr = text({ error: context.error, command: context.command });2357 } else {2358 helpStr = text;2359 }2360 // Ignore falsy value when nothing to output.2361 if (helpStr) {2362 context.write(`${helpStr}\n`);2363 }2364 });2365 return this;2366 }2367};23682369/**10 * Expose the root command.11 */1213exports = module.exports = new Command();14exports.program = exports; // More explicit access to global command.15// Implicit export of createArgument, createCommand, and createOption.1617/**18 * Expose classes19 */202380exports.Command = Command;2381exports.Option = Option;21exports.Argument = Argument;22exports.Command = Command;23exports.CommanderError = CommanderError;24exports.Help = Help;25exports.InvalidArgumentError = InvalidArgumentError;26exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated2386exports.Help = Help;23872388/**2389 * Camel-case the given `flag`2390 *2391 * @param {string} flag2392 * @return {string}2393 * @api private2394 */23952396function camelcase(flag) {2397 return flag.split('-').reduce((str, word) => {2398 return str + word[0].toUpperCase() + word.slice(1);2399 });2400}24012402/**2403 * Output help information if help flags specified2404 *2405 * @param {Command} cmd - command to output help for2406 * @param {Array} args - array of options to search for help flags2407 * @api private2408 */24092410function outputHelpIfRequested(cmd, args) {2411 const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);2412 if (helpOption) {2413 cmd.outputHelp();2414 // (Do not have all displayed text available so only passing placeholder.)2415 cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');2416 }2417}24182419/**2420 * Takes an argument and returns its human readable equivalent for help usage.2421 *2422 * @param {Argument} arg2423 * @return {string}2424 * @api private2425 */24262427function humanReadableArgName(arg) {2428 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');24292430 return arg.required2431 ? '<' + nameOutput + '>'2432 : '[' + nameOutput + ']';2433}24342435/**2436 * Parse the short and long flag out of something like '-m,--mixed <value>'2437 *2438 * @api private2439 */24402441function _parseOptionFlags(flags) {2442 let shortFlag;2443 let longFlag;2444 // Use original very loose parsing to maintain backwards compatibility for now,2445 // which allowed for example unintended `-sw, --short-word` [sic].2446 const flagParts = flags.split(/[ |,]+/);2447 if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();2448 longFlag = flagParts.shift();2449 // Add support for lone short flag without significantly changing parsing!2450 if (!shortFlag && /^-[^-]$/.test(longFlag)) {2451 shortFlag = longFlag;2452 longFlag = undefined;2453 }2454 return { shortFlag, longFlag };2455}24562457/**2458 * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).2459 *2460 * @param {string[]} args - array of arguments from node.execArgv2461 * @returns {string[]}2462 * @api private2463 */24642465function incrementNodeInspectorPort(args) {2466 // Testing for these options:2467 // --inspect[=[host:]port]2468 // --inspect-brk[=[host:]port]2469 // --inspect-port=[host:]port2470 return args.map((arg) => {2471 if (!arg.startsWith('--inspect')) {2472 return arg;2473 }2474 let debugOption;2475 let debugHost = '127.0.0.1';2476 let debugPort = '9229';2477 let match;2478 if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {2479 // e.g. --inspect2480 debugOption = match[1];2481 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {2482 debugOption = match[1];2483 if (/^\d+$/.test(match[3])) {2484 // e.g. --inspect=12342485 debugPort = match[3];2486 } else {2487 // e.g. --inspect=localhost2488 debugHost = match[3];2489 }2490 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {2491 // e.g. --inspect=localhost:12342492 debugOption = match[1];2493 debugHost = match[3];2494 debugPort = match[4];2495 }24962497 if (debugOption && debugPort !== '0') {2498 return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;2499 }2500 return arg;2501 });2502}25032504/**2505 * @param {Command} startCommand2506 * @returns {Command[]}2507 * @api private2508 */25092510function getCommandAndParents(startCommand) {2511 const result = [];2512 for (let command = startCommand; command; command = command.parent) {2513 result.push(command);2514 }2515 return result;2516}27exports.Option = Option;
modified:package.json+3 added-2 removed