Support argument processing without action handler (#1529)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Process command-arguments without needing action handler * Add some test for new behaviours without action handler * Modify README
authored by John Gee · committed by GitHub · parent 082717f · Browse files · 6 files·+94 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+94 added−31 removed
- tests:+45 added−3 removed
- other:+49 added−28 removed
Provenance
- Commit
4663597- Tree
bb2f3b3- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
082717f
6 files changed+94 added−31 removed
modified:lib/command.js+42 added-27 removed
17 unmodified lines18 */19 20 constructor(name) {21 super();22+ /** @type {Command[]} */23 this.commands = [];24+ /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;28 this._allowExcessArguments = true;29+ /** @type {Argument[]} */30 this._args = [];31+ /** @type {string[]} */32+ this.args = []; // cli args with options removed28- this.rawArgs = null;33+ this.rawArgs = [];34+ this.processedArgs = []; // like .args but after custom processing and collecting variadic35 this._scriptPath = null;36 this._name = name || '';37 this._optionValues = {};38 this._storeOptionsAsProperties = false;957 unmodified lines996 }997 };998 999 /**994- * Package arguments (this.args) for passing to action handler based995- * on declared arguments (this._args).1000+ * Check this.args against expected this._args.1001 *1002 * @api private1003 */1004 1000- _getActionArguments() {1005+ _checkNumberOfArguments() {1006+ // too few1007+ this._args.forEach((arg, i) => {1008+ if (arg.required && this.args[i] == null) {1009+ this.missingArgument(arg.name());1010+ }1011+ });1012+ // too many1013+ if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1014+ return;1015+ }1016+ if (this.args.length > this._args.length) {1017+ this._excessArguments(this.args);1018+ }1019+ };1020+1021+ /**1022+ * Process this.args using this._args and save as this.processedArgs!1023+ *1024+ * @api private1025+ */1026+1027+ _processArguments() {1028 const myParseArg = (argument, value, previous) => {1029 // Extra processing for nice error message on parsing failure.1030 let parsedValue = value;1031 if (value !== null && argument.parseArg) {9 unmodified lines1041 }1042 return parsedValue;1043 };1044 1045+ this._checkNumberOfArguments();1046+1018- const actionArgs = [];1047+ const processedArgs = [];1048 this._args.forEach((declaredArg, index) => {1049 let value = declaredArg.defaultValue;1050 if (declaredArg.variadic) {1051 // Collect together remaining arguments for passing together as an array.12 unmodified lines1064 if (declaredArg.parseArg) {1065 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1066 }1067 }1039- actionArgs[index] = value;1068+ processedArgs[index] = value;1069 });1041- return actionArgs;1070+ this.processedArgs = processedArgs;1071 }1072 1073 /**1074 * Once we have a promise we chain, but call synchronously until then.83 unmodified lines1158 if (parsed.unknown.length > 0) {1159 this.unknownOption(parsed.unknown[0]);1160 }1161 };1133- const checkNumberOfArguments = () => {1134- // too few1135- this._args.forEach((arg, i) => {1136- if (arg.required && this.args[i] == null) {1137- this.missingArgument(arg.name());1138- }1139- });1140- // too many1141- if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1142- return;1143- }1144- if (this.args.length > this._args.length) {1145- this._excessArguments(this.args);1146- }1147- };1162 1163 const commandEvent = `command:${this.name()}`;1164 if (this._actionHandler) {1165 checkForUnknownOptions();1152- checkNumberOfArguments();1166+ this._processArguments();1167 1168 let actionResult;1169 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1156- actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this._getActionArguments()));1170+ actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));1171 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1172 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1173 return actionResult;1174 }1175 if (this.parent && this.parent.listenerCount(commandEvent)) {1176 checkForUnknownOptions();1163- checkNumberOfArguments();1177+ this._processArguments();1178 this.parent.emit(commandEvent, operands, unknown); // legacy1179 } else if (operands.length) {1180 if (this._findCommand('*')) { // legacy default command1181 return this._dispatchSubcommand('*', operands, unknown);4 unmodified lines1186 } else if (this.commands.length) {1187 this.unknownCommand();1188 } else {1189 checkForUnknownOptions();1176- checkNumberOfArguments();1190+ this._processArguments();1191 }1192 } else if (this.commands.length) {1193 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1194 this.help({ error: true });1195 } else {1196 checkForUnknownOptions();1183- checkNumberOfArguments();1197+ this._processArguments();1198 // fall through for caller to handle after calling .parse()1199 }1200 };1201 339 unmodified lines1541 1542 alias(alias) {1543 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1544 1545+ /** @type {Command} */1546 let command = this;1547 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1548 // assume adding alias for last added executable subcommand, rather than this1549 command = this.commands[this.commands.length - 1];291 unmodified linesmodified:lib/help.js+1 added
36 unmodified lines37 visibleCommands.push(helpCommand);38 }39 if (this.sortSubcommands) {40 visibleCommands.sort((a, b) => {41+ // @ts-ignore: overloaded return type42 return a.name().localeCompare(b.name());43 });44 }45 return visibleCommands;348 unmodified linesmodified:tests/argument.custom-processing.test.js+45 added-3 removed
1234567825 unmodified lines343536373738394041422 unmodified lines454647484950515253545556575859605061626364652 unmodified lines68697071727374757677787980818283848586873 unmodified lines919293947495969798994 unmodified lines10410510610710810911011111211311411511611711811912012112212312412530 unmodified lines1561571581591601611621631641651661671681691701712 unmodified lines17417517617717817918018118237 unmodified linesconst commander = require('../');
// Testing default value and custom processing behaviours.// Some double assertions in tests to check action argument and .processedArg
test('when argument not specified then callback not called', () => { const mockCoercion = jest.fn(); const program = new commander.Command();25 unmodified lines program.parse([], { from: 'user' }); expect(mockCoercion).not.toHaveBeenCalled();});
test('when custom with starting value and argument not specified then action argument is starting value', () => {test('when custom with starting value and argument not specified with action handler then action argument is starting value', () => { const startingValue = 1; let actionValue; const program = new commander.Command(); program2 unmodified lines actionValue = arg; }); program.parse([], { from: 'user' }); expect(actionValue).toEqual(startingValue); expect(program.processedArgs).toEqual([startingValue]);});
test('when custom with starting value and argument not specified without action handler then .processedArgs has starting value', () => { const startingValue = 1; const program = new commander.Command(); program .argument('[n]', 'number', parseFloat, startingValue); program.parse([], { from: 'user' }); expect(program.processedArgs).toEqual([startingValue]);});
test('when default value is defined (without custom processing) and argument not specified then action argument is default value', () => {test('when default value is defined (without custom processing) and argument not specified with action handler then action argument is default value', () => { const defaultValue = 1; let actionValue; const program = new commander.Command(); program2 unmodified lines actionValue = arg; }); program.parse([], { from: 'user' }); expect(actionValue).toEqual(defaultValue); expect(program.processedArgs).toEqual([defaultValue]);});
test('when default value is defined (without custom processing) and argument not specified without action handler then .processedArgs is default value', () => { const defaultValue = 1; const program = new commander.Command(); program .argument('[n]', 'number', defaultValue); program.parse([], { from: 'user' }); expect(program.processedArgs).toEqual([defaultValue]);});
test('when argument specified then callback called with value', () => { const mockCoercion = jest.fn(); const value = '1'; const program = new commander.Command();3 unmodified lines program.parse([value], { from: 'user' }); expect(mockCoercion).toHaveBeenCalledWith(value, undefined);});
test('when argument specified then action value is as returned from callback', () => {test('when argument specified with action handler then action value is as returned from callback', () => { const callbackResult = 2; let actionValue; const program = new commander.Command(); program4 unmodified lines actionValue = arg; }); program.parse(['node', 'test', 'alpha']); expect(actionValue).toEqual(callbackResult); expect(program.processedArgs).toEqual([callbackResult]);});
test('when argument specified without action handler then .processedArgs is as returned from callback', () => { const callbackResult = 2; const program = new commander.Command(); program .argument('[n]', 'number', () => { return callbackResult; }); program.parse(['node', 'test', 'alpha']); expect(program.processedArgs).toEqual([callbackResult]);});
test('when argument specified then program.args has original rather than custom', () => { // This is as intended, so check behaviour. const callbackResult = 2; const program = new commander.Command();30 unmodified lines expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined); expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');});
test('when variadic argument without action handler then .processedArg has array', () => { const program = new commander.Command(); program .argument('<n...>', 'number'); program.parse(['1', '2'], { from: 'user' }); expect(program.processedArgs).toEqual([['1', '2']]);});
test('when parseFloat "1e2" then action argument is 100', () => { let actionValue; const program = new commander.Command(); program2 unmodified lines actionValue = arg; }); program.parse(['1e2'], { from: 'user' }); expect(actionValue).toEqual(100); expect(program.processedArgs).toEqual([actionValue]);});
test('when defined default value for required argument then throw', () => { const program = new commander.Command();37 unmodified linesmodified:typings/index.d.ts+1 added
215 unmodified lines216 }217 218 export class Command {219 args: string[];220+ processedArgs: any[];221 commands: Command[];222 parent: Command | null;223 224 constructor(name?: string);508 unmodified linesmodified:typings/index.test-d.ts+2 added
23 unmodified lines24 expectType<commander.Argument>(commander.createArgument('<foo>'));25 26 // Command properties27 expectType<string[]>(program.args);28+// eslint-disable-next-line @typescript-eslint/no-explicit-any29+expectType<any[]>(program.processedArgs);30 expectType<commander.Command[]>(program.commands);31 expectType<commander.Command | null>(program.parent);32 33 // version364 unmodified linesmodified:Readme.md+3 added-1 removed
487 unmodified lines488 ```489 490 #### Custom argument processing491 492-You may specify a function to do custom processing of command-arguments before they are passed to the action handler.492+You may specify a function to do custom processing of command-arguments (like for option-arguments).493 The callback function receives two parameters, the user specified command-argument and the previous value for the argument.494 It returns the new value for the argument.495 496+The processed argument values are passed to the action handler, and saved as `.processedArgs`.497+498 You can optionally specify the default/starting value for the argument after the function parameter.499 500 Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)501 505 unmodified lines