Skip to content
Myr

Merge remote-tracking branch 'origin/develop' into release/12.x

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

authored by John Gee · committed by John Gee · parents 37c9398, 744ee3f · Browse files · 15 files+121 added−123 removed
This commit

State

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

Diff stats

15 files+121 added−123 removed

  • tests:+19 added−15 removed
  • other:+102 added−108 removed

15 files+121 added−123 removed

modified:.github/workflows/codeql-analysis.yml+1 added-1 removed
modified:.github/workflows/tests.yml+1 added-1 removed
modified:docs/deprecated.md+17 added
13 unmodified lines
14 - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)15 - [InvalidOptionArgumentError](#invalidoptionargumenterror)16 - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)17 - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)18 - [cmd.\_args](#cmd_args)1920## RegExp .option() parameter2122The `.option()` method allowed a RegExp as the third parameter to restrict what values were accepted.
185 unmodified lines
208import { Command } from 'commander';209```210211README updated in Commander v9. Deprecated from Commander v9.212213## cmd._args214215This was always private, but was previously the only way to access the command `Argument` array.216217```js218const registeredArguments = program._args;219```220221The registered command arguments are now accessible via `.registeredArguments`.222223```js224const registeredArguments = program.registeredArguments;225```226227Deprecated from Commander v11.
modified:lib/argument.js+1 added-1 removed
64 unmodified lines
6566 /**67 * Set the default value, and optionally supply the description to be displayed in the help.68 *69 * @param {any} value69 * @param {*} value70 * @param {string} [description]71 * @return {Argument}72 */73
74 unmodified lines
modified:lib/command.js+30 added-57 removed
27 unmodified lines
28 this.parent = null;29 this._allowUnknownOption = false;30 this._allowExcessArguments = true;31 /** @type {Argument[]} */32 this._args = [];32 this.registeredArguments = [];33 this._args = this.registeredArguments; // deprecated old name34 /** @type {string[]} */35 this.args = []; // cli args with options removed36 this.rawArgs = [];37 this.processedArgs = []; // like .args but after custom processing and collecting variadic
320 unmodified lines
358 * @param {Argument} argument359 * @return {Command} `this` command for chaining360 */361 addArgument(argument) {361 const previousArgument = this._args.slice(-1)[0];362 const previousArgument = this.registeredArguments.slice(-1)[0];363 if (previousArgument && previousArgument.variadic) {364 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);365 }366 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {367 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);368 }368 this._args.push(argument);369 this.registeredArguments.push(argument);370 return this;371 }372373 /**
111 unmodified lines
485486 action(fn) {487 const listener = (args) => {488 // The .action callback takes an extra parameter which is the command or options.488 const expectedArgsCount = this._args.length;489 const expectedArgsCount = this.registeredArguments.length;490 const actionArgs = args.slice(0, expectedArgsCount);491 if (this._storeOptionsAsProperties) {492 actionArgs[expectedArgsCount] = this; // backwards compatible "options"493 } else {
26 unmodified lines
520 * Wrap parseArgs to catch 'commander.invalidArgument'.521 *522 * @param {Option | Argument} target523 * @param {string} value523 * @param {any} previous524 * @param {*} previous525 * @param {string} invalidArgumentMessage526 * @private527 */528
105 unmodified lines
634 return this.addOption(option);635 }636637 /**637 * Define option with `flags`, `description` and optional638 * coercion `fn`.638 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.639 *640 * The `flags` string contains the short and/or long flags,641 * separated by comma, a pipe or space. The following are all valid642 * all will output this way when `--help` is used.640 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required641 * option-argument is indicated by `<>` and an optional option-argument by `[]`.642 *644 * "-p, --pepper"645 * "-p|--pepper"646 * "-p --pepper"643 * See the README for more details, and see also addOption() and requiredOption().644 *645 * @example649 * // simple boolean defaulting to undefined650 * program.option('-p, --pepper', 'add pepper');646 * program647 * .option('-p, --pepper', 'add pepper')648 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument649 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default650 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function651 *652 * program.pepper653 * // => undefined654 *655 * --pepper656 * program.pepper657 * // => true658 *659 * // simple boolean defaulting to true (unless non-negated option is also defined)660 * program.option('-C, --no-cheese', 'remove cheese');661 *662 * program.cheese663 * // => true664 *665 * --no-cheese666 * program.cheese667 * // => false668 *669 * // required argument670 * program.option('-C, --chdir <path>', 'change the working directory');671 *672 * --chdir /tmp673 * program.chdir674 * // => "/tmp"675 *676 * // optional argument677 * program.option('-c, --cheese [type]', 'add cheese [marble]');678 *652 * @param {string} flags653 * @param {string} [description]681 * @param {Function|*} [fn] - custom option processing function or default value654 * @param {Function|*} [parseArg] - custom option processing function or default value655 * @param {*} [defaultValue]656 * @return {Command} `this` command for chaining657 */658686 option(flags, description, fn, defaultValue) {687 return this._optionEx({}, flags, description, fn, defaultValue);659 option(flags, description, parseArg, defaultValue) {660 return this._optionEx({}, flags, description, parseArg, defaultValue);661 }662663 /**664 * Add a required option which must have a value after parsing. This usually means
2 unmodified lines
667 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.668 *669 * @param {string} flags670 * @param {string} [description]698 * @param {Function|*} [fn] - custom option processing function or default value671 * @param {Function|*} [parseArg] - custom option processing function or default value672 * @param {*} [defaultValue]673 * @return {Command} `this` command for chaining674 */675703 requiredOption(flags, description, fn, defaultValue) {704 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);676 requiredOption(flags, description, parseArg, defaultValue) {677 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);678 }679680 /**681 * Alter parsing of short flags with optional values.
437 unmodified lines
1119 ]);1120 }11211122 /**1150 * Check this.args against expected this._args.1123 * Check this.args against expected this.registeredArguments.1124 *1125 * @private1126 */11271128 _checkNumberOfArguments() {1129 // too few1157 this._args.forEach((arg, i) => {1130 this.registeredArguments.forEach((arg, i) => {1131 if (arg.required && this.args[i] == null) {1132 this.missingArgument(arg.name());1133 }1134 });1135 // too many1163 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1136 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {1137 return;1138 }1166 if (this.args.length > this._args.length) {1139 if (this.args.length > this.registeredArguments.length) {1140 this._excessArguments(this.args);1141 }1142 }11431144 /**1172 * Process this.args using this._args and save as this.processedArgs!1145 * Process this.args using this.registeredArguments and save as this.processedArgs!1146 *1147 * @private1148 */1149
10 unmodified lines
11601161 this._checkNumberOfArguments();11621163 const processedArgs = [];1191 this._args.forEach((declaredArg, index) => {1164 this.registeredArguments.forEach((declaredArg, index) => {1165 let value = declaredArg.defaultValue;1166 if (declaredArg.variadic) {1167 // Collect together remaining arguments for passing together as an array.1168 if (index < this.args.length) {
606 unmodified lines
17751776 _excessArguments(receivedArgs) {1777 if (this._allowExcessArguments) return;17781806 const expected = this._args.length;1779 const expected = this.registeredArguments.length;1780 const s = (expected === 1) ? '' : 's';1781 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1782 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1783 this.error(message, { code: 'commander.excessArguments' });
131 unmodified lines
1915 usage(str) {1916 if (str === undefined) {1917 if (this._usage) return this._usage;19181946 const args = this._args.map((arg) => {1919 const args = this.registeredArguments.map((arg) => {1920 return humanReadableArgName(arg);1921 });1922 return [].concat(1923 (this.options.length || this._hasHelpOption ? '[options]' : []),1924 (this.commands.length ? '[command]' : []),1952 (this._args.length ? args : [])1925 (this.registeredArguments.length ? args : [])1926 ).join(' ');1927 }19281929 this._usage = str;
261 unmodified lines
modified:lib/help.js+4 added-4 removed
119 unmodified lines
120121 visibleArguments(cmd) {122 // Side effect! Apply the legacy descriptions before the arguments are displayed.123 if (cmd._argsDescription) {124 cmd._args.forEach(argument => {124 cmd.registeredArguments.forEach(argument => {125 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';126 });127 }128129 // If there are any arguments with a description then return all the arguments.130 if (cmd._args.find(argument => argument.description)) {131 return cmd._args;130 if (cmd.registeredArguments.find(argument => argument.description)) {131 return cmd.registeredArguments;132 }133 return [];134 }135
5 unmodified lines
141 */142143 subcommandTerm(cmd) {144 // Legacy. Ignores custom usage string, and nested commands.145 const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');145 const args = cmd.registeredArguments.map(arg => humanReadableArgName(arg)).join(' ');146 return cmd._name +147 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +148 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option149 (args ? ' ' + args : '');
315 unmodified lines
modified:lib/option.js+3 added-3 removed
38 unmodified lines
3940 /**41 * Set the default value, and optionally supply the description to be displayed in the help.42 *43 * @param {any} value43 * @param {*} value44 * @param {string} [description]45 * @return {Option}46 */47
10 unmodified lines
58 * @example59 * new Option('--color').default('GREYSCALE').preset('RGB');60 * new Option('--donate [amount]').preset('20').argParser(parseFloat);61 *62 * @param {any} arg62 * @param {*} arg63 * @return {Option}64 */6566 preset(arg) {
206 unmodified lines
273274 /**275 * Did the value come from the option, and not from possible matching dual option?276 *277 * @param {any} value277 * @param {*} value278 * @param {Option} option279 * @returns {boolean}280 */281 valueFromOption(value, option) {
49 unmodified lines
modified:tests/fixtures/inspect.js+2 added
modified:tests/fixtures/pm+2 added
1#!/usr/bin/env node23var { program } = require('../../');45process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/1439167program8 .version('0.0.1')9 .command('install [name]', 'install one or more packages').alias('i')10 .command('search [query]', 'search with optional query').alias('s')
10 unmodified lines
modified:tests/command.argumentVariations.test.js+9 added-9 removed
2 unmodified lines
3// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,4// and not exhaustively testing all methods elsewhere.56test.each(getSingleArgCases('<explicit-required>'))('when add "<arg>" using %s then argument required', (methodName, cmd) => {7 const argument = cmd._args[0];7 const argument = cmd.registeredArguments[0];8 const expectedShape = {9 _name: 'explicit-required',10 required: true,11 variadic: false,
2 unmodified lines
14 expect(argument).toEqual(expectedShape);15});1617test.each(getSingleArgCases('implicit-required'))('when add "arg" using %s then argument required', (methodName, cmd) => {18 const argument = cmd._args[0];18 const argument = cmd.registeredArguments[0];19 const expectedShape = {20 _name: 'implicit-required',21 required: true,22 variadic: false,
2 unmodified lines
25 expect(argument).toEqual(expectedShape);26});2728test.each(getSingleArgCases('[optional]'))('when add "[arg]" using %s then argument optional', (methodName, cmd) => {29 const argument = cmd._args[0];29 const argument = cmd.registeredArguments[0];30 const expectedShape = {31 _name: 'optional',32 required: false,33 variadic: false,
2 unmodified lines
36 expect(argument).toEqual(expectedShape);37});3839test.each(getSingleArgCases('<explicit-required...>'))('when add "<arg...>" using %s then argument required and variadic', (methodName, cmd) => {40 const argument = cmd._args[0];40 const argument = cmd.registeredArguments[0];41 const expectedShape = {42 _name: 'explicit-required',43 required: true,44 variadic: true,
2 unmodified lines
47 expect(argument).toEqual(expectedShape);48});4950test.each(getSingleArgCases('implicit-required...'))('when add "arg..." using %s then argument required and variadic', (methodName, cmd) => {51 const argument = cmd._args[0];51 const argument = cmd.registeredArguments[0];52 const expectedShape = {53 _name: 'implicit-required',54 required: true,55 variadic: true,
2 unmodified lines
58 expect(argument).toEqual(expectedShape);59});6061test.each(getSingleArgCases('[optional...]'))('when add "[arg...]" using %s then argument optional and variadic', (methodName, cmd) => {62 const argument = cmd._args[0];62 const argument = cmd.registeredArguments[0];63 const expectedShape = {64 _name: 'optional',65 required: false,66 variadic: true,
11 unmodified lines
78 ];79}8081test.each(getMultipleArgCases('<first>', '[second]'))('when add two arguments using %s then two arguments', (methodName, cmd) => {82 expect(cmd._args[0].name()).toEqual('first');83 expect(cmd._args[1].name()).toEqual('second');82 expect(cmd.registeredArguments[0].name()).toEqual('first');83 expect(cmd.registeredArguments[1].name()).toEqual('second');84});8586function getMultipleArgCases(arg1, arg2) {87 return [
10 unmodified lines
98 const cmd = program.command('sub <arg1> <arg2>');99 cmd.arguments('<arg3> <arg4>');100 cmd.argument('<arg5>');101 cmd.addArgument(new commander.Argument('arg6'));102 const argNames = cmd._args.map(arg => arg.name());102 const argNames = cmd.registeredArguments.map(arg => arg.name());103 expect(argNames).toEqual(['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6']);104});
modified:tests/command.createArgument.test.js+6 added-6 removed
19 unmodified lines
2021test('when override createArgument then used for argument()', () => {22 const program = new MyCommand();23 program.argument('<file>');24 expect(program._args.length).toEqual(1);25 expect(program._args[0].myProperty).toEqual('MyArgument');24 expect(program.registeredArguments.length).toEqual(1);25 expect(program.registeredArguments[0].myProperty).toEqual('MyArgument');26});2728test('when override createArgument then used for arguments()', () => {29 const program = new MyCommand();30 program.arguments('<file>');31 expect(program._args.length).toEqual(1);32 expect(program._args[0].myProperty).toEqual('MyArgument');31 expect(program.registeredArguments.length).toEqual(1);32 expect(program.registeredArguments[0].myProperty).toEqual('MyArgument');33});3435test('when override createArgument and createCommand then used for argument of command()', () => {36 const program = new MyCommand();37 const sub = program.command('sub <file>');38 expect(sub._args.length).toEqual(1);39 expect(sub._args[0].myProperty).toEqual('MyArgument');38 expect(sub.registeredArguments.length).toEqual(1);39 expect(sub.registeredArguments[0].myProperty).toEqual('MyArgument');40});
modified:typings/index.d.ts+18 added-36 removed
48 unmodified lines
49export class Argument {50 description: string;51 required: boolean;52 variadic: boolean;53 defaultValue?: any;54 defaultValueDescription?: string;55 argChoices?: string[];5657 /**58 * Initialize a new command argument with the given name and description.59 * The default is that the argument is required, and you can explicitly
44 unmodified lines
104 long?: string;105 negate: boolean;106 defaultValue?: any;107 defaultValueDescription?: string;108 presetArg?: unknown;109 envVar?: string;110 parseArg?: <T>(value: string, previous: T) => T;111 hidden: boolean;112 argChoices?: string[];113
180 unmodified lines
294 args: string[];295 processedArgs: any[];296 readonly commands: readonly Command[];297 readonly options: readonly Option[];298 readonly registeredArguments: readonly Argument[];299 parent: Command | null;300301 constructor(name?: string);302
212 unmodified lines
515 */516 action(fn: (...args: any[]) => void | Promise<void>): this;517518 /**513 * Define option with `flags`, `description` and optional514 * coercion `fn`.519 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.520 *516 * The `flags` string contains the short and/or long flags,517 * separated by comma, a pipe or space. The following are all valid518 * all will output this way when `--help` is used.521 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required522 * option-argument is indicated by `<>` and an optional option-argument by `[]`.523 *520 * "-p, --pepper"521 * "-p|--pepper"522 * "-p --pepper"524 * See the README for more details, and see also addOption() and requiredOption().525 *526 * @example525 * ```526 * // simple boolean defaulting to false527 * program.option('-p, --pepper', 'add pepper');527 *529 * --pepper530 * program.pepper531 * // => Boolean532 *533 * // simple boolean defaulting to true534 * program.option('-C, --no-cheese', 'remove cheese');535 *536 * program.cheese537 * // => true538 *539 * --no-cheese540 * program.cheese541 * // => false542 *543 * // required argument544 * program.option('-C, --chdir <path>', 'change the working directory');545 *546 * --chdir /tmp547 * program.chdir548 * // => "/tmp"549 *550 * // optional argument551 * program.option('-c, --cheese [type]', 'add cheese [marble]');528 * ```js529 * program530 * .option('-p, --pepper', 'add pepper')531 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument532 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default533 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function534 * ```535 *536 * @returns `this` command for chaining537 */538 option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;557 option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;539 option<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;540 /** @deprecated since v7, instead use choices or a custom function */541 option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;542543 /**
2 unmodified lines
546 *547 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.548 */549 requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;568 requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;550 requiredOption<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;551 /** @deprecated since v7, instead use choices or a custom function */552 requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;553554 /**
330 unmodified lines
modified:typings/index.test-d.ts+22 added-2 removed
28 unmodified lines
29// eslint-disable-next-line @typescript-eslint/no-explicit-any30expectType<any[]>(program.processedArgs);31expectType<readonly commander.Command[]>(program.commands);32expectType<readonly commander.Option[]>(program.options);33expectType<readonly commander.Argument[]>(program.registeredArguments);34expectType<commander.Command | null>(program.parent);3536// version37expectType<commander.Command>(program.version('1.2.3'));
359 unmodified lines
397expectType<string>(helper.wrap('a b c', 50, 3));398399expectType<string>(helper.formatHelp(helperCommand, helper));400400// Option methods401401// Option properties402const baseOption = new commander.Option('-f,--foo', 'foo description');403expectType<string>(baseOption.flags);404expectType<string>(baseOption.description);405expectType<boolean>(baseOption.required);406expectType<boolean>(baseOption.optional);407expectType<boolean>(baseOption.variadic);408expectType<boolean>(baseOption.mandatory);409expectType<string | undefined>(baseOption.short);410expectType<string | undefined>(baseOption.long);411expectType<boolean>(baseOption.negate);412expectType<any>(baseOption.defaultValue);413expectType<string | undefined>(baseOption.defaultValueDescription);414expectType<unknown>(baseOption.presetArg);415expectType<string | undefined>(baseOption.envVar);416expectType<boolean>(baseOption.hidden);417expectType<string[] | undefined>(baseOption.argChoices);418419// Option methods420421// default422expectType<commander.Option>(baseOption.default(3));423expectType<commander.Option>(baseOption.default(60, 'one minute'));424
44 unmodified lines
469const baseArgument = new commander.Argument('<foo');470expectType<string>(baseArgument.description);471expectType<boolean>(baseArgument.required);472expectType<boolean>(baseArgument.variadic);473expectType<any>(baseArgument.defaultValue);474expectType<string | undefined>(baseArgument.defaultValueDescription);475expectType<string[] | undefined>(baseArgument.argChoices);476477// Argument methods478479// name
23 unmodified lines
modified:index.js+4 added-3 removed
14 unmodified lines
15/**16 * Expose classes17 */1819exports.Argument = Argument;19exports.Command = Command;21exports.CommanderError = CommanderError;20exports.Option = Option;21exports.Argument = Argument;22exports.Help = Help;2324exports.CommanderError = CommanderError;25exports.InvalidArgumentError = InvalidArgumentError;26exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated25exports.Option = Option;
modified:tsconfig.json+1 added
9 unmodified lines
10 "types": [11 "node",12 "jest"13 ],14 "esModuleInterop": true, // Mainly so can test an import problem which only occurs with this option on!15 "noEmit": true,16 "forceConsistentCasingInFileNames": true17 },18 "include": ["**/*.ts"],
1 unmodified line