Skip to content
Myr

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

6 files+94 added−31 removed

modified:lib/command.js+42 added-27 removed
17 unmodified lines
18 */1920 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 lines
996 }997 };998999 /**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 */10041000 _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 };10201021 /**1022 * Process this.args using this._args and save as this.processedArgs!1023 *1024 * @api private1025 */10261027 _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 lines
1041 }1042 return parsedValue;1043 };10441045 this._checkNumberOfArguments();10461018 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 lines
1064 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 }10721073 /**1074 * Once we have a promise we chain, but call synchronously until then.
83 unmodified lines
1158 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 };11621163 const commandEvent = `command:${this.name()}`;1164 if (this._actionHandler) {1165 checkForUnknownOptions();1152 checkNumberOfArguments();1166 this._processArguments();11671168 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 lines
1186 } 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 lines
15411542 alias(alias) {1543 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility15441545 /** @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 lines
modified:lib/help.js+1 added
36 unmodified lines
37 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 lines
modified:tests/argument.custom-processing.test.js+45 added-3 removed
modified:typings/index.d.ts+1 added
215 unmodified lines
216}217218export class Command {219 args: string[];220 processedArgs: any[];221 commands: Command[];222 parent: Command | null;223224 constructor(name?: string);
508 unmodified lines
modified:typings/index.test-d.ts+2 added
23 unmodified lines
24expectType<commander.Argument>(commander.createArgument('<foo>'));2526// Command properties27expectType<string[]>(program.args);28// eslint-disable-next-line @typescript-eslint/no-explicit-any29expectType<any[]>(program.processedArgs);30expectType<commander.Command[]>(program.commands);31expectType<commander.Command | null>(program.parent);3233// version
364 unmodified lines
modified:Readme.md+3 added-1 removed
487 unmodified lines
488```489490#### Custom argument processing491492You may specify a function to do custom processing of command-arguments before they are passed to the action handler.492You may specify a function to do custom processing of command-arguments (like for option-arguments).493The callback function receives two parameters, the user specified command-argument and the previous value for the argument.494It returns the new value for the argument.495496The processed argument values are passed to the action handler, and saved as `.processedArgs`.497498You can optionally specify the default/starting value for the argument after the function parameter.499500Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)501
505 unmodified lines