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
Provenance
- Commit
9afbabd- Tree
2f4f9cf- Author
John Gee <john@ruru.gen.nz>- Committer
John Gee <john@ruru.gen.nz>- Parent 1
37c9398- Parent 2
744ee3f
15 files changed+121 added−123 removed
modified:.github/workflows/codeql-analysis.yml+1 added-1 removed
23 unmodified lines2425262728282930313225 unmodified lines23 unmodified lines language: [ 'javascript' ]
steps: - name: Checkout repository uses: actions/checkout@v3 uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v225 unmodified linesmodified:.github/workflows/tests.yml+1 added-1 removed
14 unmodified lines151617181919202122238 unmodified lines14 unmodified lines node-version: [16.x, 18.x, 20.x] os: [ubuntu-latest, windows-latest, macos-latest]
steps: - uses: actions/checkout@v3 - uses: actions/checkout@v4 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v3 with: cache: 'npm'8 unmodified linesmodified:docs/deprecated.md+17 added
13 unmodified lines14 - [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)19 20 ## RegExp .option() parameter21 22 The `.option()` method allowed a RegExp as the third parameter to restrict what values were accepted.185 unmodified lines208 import { Command } from 'commander';209 ```210 211 README updated in Commander v9. Deprecated from Commander v9.212+213+## cmd._args214+215+This was always private, but was previously the only way to access the command `Argument` array.216+217+```js218+const registeredArguments = program._args;219+```220+221+The registered command arguments are now accessible via `.registeredArguments`.222+223+```js224+const registeredArguments = program.registeredArguments;225+```226+227+Deprecated from Commander v11.modified:lib/argument.js+1 added-1 removed
64 unmodified lines65 66 /**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 linesmodified:lib/command.js+30 added-57 removed
27 unmodified lines28 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 variadic320 unmodified lines358 * @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 }372 373 /**111 unmodified lines485 486 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 lines520 * 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 lines634 return this.addOption(option);635 }636 637 /**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 */658 686- 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 }662 663 /**664 * Add a required option which must have a value after parsing. This usually means2 unmodified lines667 * 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 */675 703- 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 }679 680 /**681 * Alter parsing of short flags with optional values.437 unmodified lines1119 ]);1120 }1121 1122 /**1150- * Check this.args against expected this._args.1123+ * Check this.args against expected this.registeredArguments.1124 *1125 * @private1126 */1127 1128 _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 }1143 1144 /**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 lines1160 1161 this._checkNumberOfArguments();1162 1163 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 lines1775 1776 _excessArguments(receivedArgs) {1777 if (this._allowExcessArguments) return;1778 1806- 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 lines1915 usage(str) {1916 if (str === undefined) {1917 if (this._usage) return this._usage;1918 1946- 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 }1928 1929 this._usage = str;261 unmodified linesmodified:lib/help.js+4 added-4 removed
119 unmodified lines120 121 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 }128 129 // 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 lines141 */142 143 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 linesmodified:lib/option.js+3 added-3 removed
38 unmodified lines39 40 /**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 lines58 * @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 */65 66 preset(arg) {206 unmodified lines273 274 /**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 linesmodified:tests/fixtures/inspect.js+2 added
123456789#!/usr/bin/env node
const { program } = require('../../');
process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/14391
program .command('sub', 'install one or more packages') .parse(process.argv);modified:tests/fixtures/pm+2 added
1 #!/usr/bin/env node2 3 var { program } = require('../../');4 5+process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/143916+7 program8 .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 linesmodified:tests/command.argumentVariations.test.js+9 added-9 removed
2 unmodified lines3 // 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.5 6 test.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 lines14 expect(argument).toEqual(expectedShape);15 });16 17 test.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 lines25 expect(argument).toEqual(expectedShape);26 });27 28 test.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 lines36 expect(argument).toEqual(expectedShape);37 });38 39 test.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 lines47 expect(argument).toEqual(expectedShape);48 });49 50 test.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 lines58 expect(argument).toEqual(expectedShape);59 });60 61 test.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 lines78 ];79 }80 81 test.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 });85 86 function getMultipleArgCases(arg1, arg2) {87 return [10 unmodified lines98 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 lines20 21 test('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 });27 28 test('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 });34 35 test('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 lines49 export class Argument {50 description: string;51 required: boolean;52 variadic: boolean;53+ defaultValue?: any;54+ defaultValueDescription?: string;55+ argChoices?: string[];56 57 /**58 * Initialize a new command argument with the given name and description.59 * The default is that the argument is required, and you can explicitly44 unmodified lines104 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 lines294 args: string[];295 processedArgs: any[];296 readonly commands: readonly Command[];297 readonly options: readonly Option[];298+ readonly registeredArguments: readonly Argument[];299 parent: Command | null;300 301 constructor(name?: string);302 212 unmodified lines515 */516 action(fn: (...args: any[]) => void | Promise<void>): this;517 518 /**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;542 543 /**2 unmodified lines546 *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;553 554 /**330 unmodified linesmodified:typings/index.test-d.ts+22 added-2 removed
28 unmodified lines29 // eslint-disable-next-line @typescript-eslint/no-explicit-any30 expectType<any[]>(program.processedArgs);31 expectType<readonly commander.Command[]>(program.commands);32 expectType<readonly commander.Option[]>(program.options);33+expectType<readonly commander.Argument[]>(program.registeredArguments);34 expectType<commander.Command | null>(program.parent);35 36 // version37 expectType<commander.Command>(program.version('1.2.3'));359 unmodified lines397 expectType<string>(helper.wrap('a b c', 50, 3));398 399 expectType<string>(helper.formatHelp(helperCommand, helper));400 400-// Option methods401-401+// Option properties402 const baseOption = new commander.Option('-f,--foo', 'foo description');403+expectType<string>(baseOption.flags);404+expectType<string>(baseOption.description);405+expectType<boolean>(baseOption.required);406+expectType<boolean>(baseOption.optional);407+expectType<boolean>(baseOption.variadic);408+expectType<boolean>(baseOption.mandatory);409+expectType<string | undefined>(baseOption.short);410+expectType<string | undefined>(baseOption.long);411+expectType<boolean>(baseOption.negate);412+expectType<any>(baseOption.defaultValue);413+expectType<string | undefined>(baseOption.defaultValueDescription);414+expectType<unknown>(baseOption.presetArg);415+expectType<string | undefined>(baseOption.envVar);416+expectType<boolean>(baseOption.hidden);417+expectType<string[] | undefined>(baseOption.argChoices);418 419+// Option methods420+421 // default422 expectType<commander.Option>(baseOption.default(3));423 expectType<commander.Option>(baseOption.default(60, 'one minute'));424 44 unmodified lines469 const baseArgument = new commander.Argument('<foo');470 expectType<string>(baseArgument.description);471 expectType<boolean>(baseArgument.required);472 expectType<boolean>(baseArgument.variadic);473+expectType<any>(baseArgument.defaultValue);474+expectType<string | undefined>(baseArgument.defaultValueDescription);475+expectType<string[] | undefined>(baseArgument.argChoices);476 477 // Argument methods478 479 // name23 unmodified linesmodified:index.js+4 added-3 removed
14 unmodified lines15 /**16 * Expose classes17 */18 19-exports.Argument = Argument;19 exports.Command = Command;21-exports.CommanderError = CommanderError;20+exports.Option = Option;21+exports.Argument = Argument;22 exports.Help = Help;23+24+exports.CommanderError = CommanderError;25 exports.InvalidArgumentError = InvalidArgumentError;26 exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated25-exports.Option = Option;modified:tsconfig.json+1 added
9 unmodified lines10 "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