Add public Arguments property (#2010)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by GitHub · parent 8edcfd9 · Browse files · 7 files·+52 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Wee Bit <aweebit64@gmail.com>
Diff stats
7 files+52 added−32 removed
- tests:+15 added−15 removed
- other:+37 added−17 removed
Provenance
- Commit
7d23437- Tree
929bff1- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
8edcfd9
7 files changed+52 added−32 removed
modified: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.184 unmodified lines207 import { Command } from 'commander';208 ```209 210 README updated in Commander v9. Deprecated from Commander v9.211+212+## cmd._args213+214+This was always private, but was previously the only way to access the command `Argument` array.215+216+```js217+const registeredArguments = program._args;218+```219+220+The registered command arguments are now accessible via `.registeredArguments`.221+222+```js223+const registeredArguments = program.registeredArguments;224+```225+226+Deprecated from Commander v11.modified:lib/command.js+14 added-13 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 variadic318 unmodified lines356 * @param {Argument} argument357 * @return {Command} `this` command for chaining358 */359 addArgument(argument) {359- const previousArgument = this._args.slice(-1)[0];360+ const previousArgument = this.registeredArguments.slice(-1)[0];361 if (previousArgument && previousArgument.variadic) {362 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);363 }364 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {365 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);366 }366- this._args.push(argument);367+ this.registeredArguments.push(argument);368 return this;369 }370 371 /**111 unmodified lines483 484 action(fn) {485 const listener = (args) => {486 // The .action callback takes an extra parameter which is the command or options.486- const expectedArgsCount = this._args.length;487+ const expectedArgsCount = this.registeredArguments.length;488 const actionArgs = args.slice(0, expectedArgsCount);489 if (this._storeOptionsAsProperties) {490 actionArgs[expectedArgsCount] = this; // backwards compatible "options"491 } else {617 unmodified lines1109 ]);1110 }1111 1112 /**1112- * Check this.args against expected this._args.1113+ * Check this.args against expected this.registeredArguments.1114 *1115 * @api private1116 */1117 1118 _checkNumberOfArguments() {1119 // too few1119- this._args.forEach((arg, i) => {1120+ this.registeredArguments.forEach((arg, i) => {1121 if (arg.required && this.args[i] == null) {1122 this.missingArgument(arg.name());1123 }1124 });1125 // too many1125- if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1126+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {1127 return;1128 }1128- if (this.args.length > this._args.length) {1129+ if (this.args.length > this.registeredArguments.length) {1130 this._excessArguments(this.args);1131 }1132 }1133 1134 /**1134- * Process this.args using this._args and save as this.processedArgs!1135+ * Process this.args using this.registeredArguments and save as this.processedArgs!1136 *1137 * @api private1138 */1139 10 unmodified lines1150 1151 this._checkNumberOfArguments();1152 1153 const processedArgs = [];1153- this._args.forEach((declaredArg, index) => {1154+ this.registeredArguments.forEach((declaredArg, index) => {1155 let value = declaredArg.defaultValue;1156 if (declaredArg.variadic) {1157 // Collect together remaining arguments for passing together as an array.1158 if (index < this.args.length) {606 unmodified lines1765 1766 _excessArguments(receivedArgs) {1767 if (this._allowExcessArguments) return;1768 1768- const expected = this._args.length;1769+ const expected = this.registeredArguments.length;1770 const s = (expected === 1) ? '' : 's';1771 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1772 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1773 this.error(message, { code: 'commander.excessArguments' });131 unmodified lines1905 usage(str) {1906 if (str === undefined) {1907 if (this._usage) return this._usage;1908 1908- const args = this._args.map((arg) => {1909+ const args = this.registeredArguments.map((arg) => {1910 return humanReadableArgName(arg);1911 });1912 return [].concat(1913 (this.options.length || this._hasHelpOption ? '[options]' : []),1914 (this.commands.length ? '[command]' : []),1914- (this._args.length ? args : [])1915+ (this.registeredArguments.length ? args : [])1916 ).join(' ');1917 }1918 1919 this._usage = str;262 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:tests/command.argumentVariations.test.js+9 added-9 removed
2 unmodified lines3456778910112 unmodified lines141516171818192021222 unmodified lines252627282929303132332 unmodified lines363738394040414243442 unmodified lines474849505151525354552 unmodified lines5859606162626364656611 unmodified lines78798081828382838485868710 unmodified lines98991001011021021031042 unmodified lines// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,// and not exhaustively testing all methods elsewhere.
test.each(getSingleArgCases('<explicit-required>'))('when add "<arg>" using %s then argument required', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'explicit-required', required: true, variadic: false,2 unmodified lines expect(argument).toEqual(expectedShape);});
test.each(getSingleArgCases('implicit-required'))('when add "arg" using %s then argument required', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'implicit-required', required: true, variadic: false,2 unmodified lines expect(argument).toEqual(expectedShape);});
test.each(getSingleArgCases('[optional]'))('when add "[arg]" using %s then argument optional', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'optional', required: false, variadic: false,2 unmodified lines expect(argument).toEqual(expectedShape);});
test.each(getSingleArgCases('<explicit-required...>'))('when add "<arg...>" using %s then argument required and variadic', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'explicit-required', required: true, variadic: true,2 unmodified lines expect(argument).toEqual(expectedShape);});
test.each(getSingleArgCases('implicit-required...'))('when add "arg..." using %s then argument required and variadic', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'implicit-required', required: true, variadic: true,2 unmodified lines expect(argument).toEqual(expectedShape);});
test.each(getSingleArgCases('[optional...]'))('when add "[arg...]" using %s then argument optional and variadic', (methodName, cmd) => { const argument = cmd._args[0]; const argument = cmd.registeredArguments[0]; const expectedShape = { _name: 'optional', required: false, variadic: true,11 unmodified lines ];}
test.each(getMultipleArgCases('<first>', '[second]'))('when add two arguments using %s then two arguments', (methodName, cmd) => { expect(cmd._args[0].name()).toEqual('first'); expect(cmd._args[1].name()).toEqual('second'); expect(cmd.registeredArguments[0].name()).toEqual('first'); expect(cmd.registeredArguments[1].name()).toEqual('second');});
function getMultipleArgCases(arg1, arg2) { return [10 unmodified lines const cmd = program.command('sub <arg1> <arg2>'); cmd.arguments('<arg3> <arg4>'); cmd.argument('<arg5>'); cmd.addArgument(new commander.Argument('arg6')); const argNames = cmd._args.map(arg => arg.name()); const argNames = cmd.registeredArguments.map(arg => arg.name()); expect(argNames).toEqual(['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6']);});modified:tests/command.createArgument.test.js+6 added-6 removed
19 unmodified lines20212223242524252627282930313231323334353637383938394019 unmodified lines
test('when override createArgument then used for argument()', () => { const program = new MyCommand(); program.argument('<file>'); expect(program._args.length).toEqual(1); expect(program._args[0].myProperty).toEqual('MyArgument'); expect(program.registeredArguments.length).toEqual(1); expect(program.registeredArguments[0].myProperty).toEqual('MyArgument');});
test('when override createArgument then used for arguments()', () => { const program = new MyCommand(); program.arguments('<file>'); expect(program._args.length).toEqual(1); expect(program._args[0].myProperty).toEqual('MyArgument'); expect(program.registeredArguments.length).toEqual(1); expect(program.registeredArguments[0].myProperty).toEqual('MyArgument');});
test('when override createArgument and createCommand then used for argument of command()', () => { const program = new MyCommand(); const sub = program.command('sub <file>'); expect(sub._args.length).toEqual(1); expect(sub._args[0].myProperty).toEqual('MyArgument'); expect(sub.registeredArguments.length).toEqual(1); expect(sub.registeredArguments[0].myProperty).toEqual('MyArgument');});modified:typings/index.d.ts+1 added
288 unmodified lines289 args: string[];290 processedArgs: any[];291 readonly commands: readonly Command[];292 readonly options: readonly Option[];293+ readonly registeredArguments: readonly Argument[];294 parent: Command | null;295 296 constructor(name?: string);297 582 unmodified linesmodified:typings/index.test-d.ts+1 added
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'));446 unmodified lines