Skip to content
Myr

Extend .argument() to add default value and custom parse for command-argument (#1508)

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

* First cut at adding default value and parse for Argument * Simplify reduce call, good match for pattern * Refactor new code into routine * Add custom processing argument tests * Add default value tests for argument * Rename tests * Add error for ignored default value * Add argument default to help information * Default only makes sense for optional argument * Extend argument typings * Add argument custom processing to README * Add InvalidArgumentError and deprecate InvalidOptionArgumentError * Fix JSDoc * Add example of varidic argument custom processing * Update comment * Remove low value comment

authored by John Gee · committed by GitHub · parent 3d67542 · Browse files · 16 files+446 added−39 removed
This commit

State

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

Diff stats

16 files+446 added−39 removed

  • tests:+217 added−9 removed
  • other:+229 added−30 removed

16 files+446 added−39 removed

modified:docs/deprecated.md+29 added
modified:examples/argument.js+2 added-2 removed
added:examples/arguments-custom-processing.js+47 added
modified:examples/options-custom-processing.js+1 added-1 removed
10 unmodified lines
11function myParseInt(value, dummyPrevious) {12 // parseInt takes a string and a radix13 const parsedValue = parseInt(value, 10);14 if (isNaN(parsedValue)) {15 throw new commander.InvalidOptionArgumentError('Not a number.');15 throw new commander.InvalidArgumentError('Not a number.');16 }17 return parsedValue;18}19
35 unmodified lines
added:tests/argument.custom-processing.test.js+144 added
1const commander = require('../');23// Testing default value and custom processing behaviours.45test('when argument not specified then callback not called', () => {6 const mockCoercion = jest.fn();7 const program = new commander.Command();8 program9 .argument('[n]', 'number', mockCoercion)10 .action(() => {});11 program.parse([], { from: 'user' });12 expect(mockCoercion).not.toHaveBeenCalled();13});1415test('when argument not specified then action argument undefined', () => {16 let actionValue = 'foo';17 const program = new commander.Command();18 program19 .argument('[n]', 'number', parseFloat)20 .action((arg) => {21 actionValue = arg;22 });23 program.parse([], { from: 'user' });24 expect(actionValue).toBeUndefined();25});2627test('when custom with starting value and argument not specified then callback not called', () => {28 const mockCoercion = jest.fn();29 const program = new commander.Command();30 program31 .argument('[n]', 'number', parseFloat, 1)32 .action(() => {});33 program.parse([], { from: 'user' });34 expect(mockCoercion).not.toHaveBeenCalled();35});3637test('when custom with starting value and argument not specified then action argument is starting value', () => {38 const startingValue = 1;39 let actionValue;40 const program = new commander.Command();41 program42 .argument('[n]', 'number', parseFloat, startingValue)43 .action((arg) => {44 actionValue = arg;45 });46 program.parse([], { from: 'user' });47 expect(actionValue).toEqual(startingValue);48});4950test('when default value is defined (without custom processing) and argument not specified then action argument is default value', () => {51 const defaultValue = 1;52 let actionValue;53 const program = new commander.Command();54 program55 .argument('[n]', 'number', defaultValue)56 .action((arg) => {57 actionValue = arg;58 });59 program.parse([], { from: 'user' });60 expect(actionValue).toEqual(defaultValue);61});6263test('when argument specified then callback called with value', () => {64 const mockCoercion = jest.fn();65 const value = '1';66 const program = new commander.Command();67 program68 .argument('[n]', 'number', mockCoercion)69 .action(() => {});70 program.parse([value], { from: 'user' });71 expect(mockCoercion).toHaveBeenCalledWith(value, undefined);72});7374test('when argument specified then action value is as returned from callback', () => {75 const callbackResult = 2;76 let actionValue;77 const program = new commander.Command();78 program79 .argument('[n]', 'number', () => {80 return callbackResult;81 })82 .action((arg) => {83 actionValue = arg;84 });85 program.parse(['node', 'test', 'alpha']);86 expect(actionValue).toEqual(callbackResult);87});8889test('when argument specified then program.args has original rather than custom', () => {90 // This is as intended, so check behaviour.91 const callbackResult = 2;92 const program = new commander.Command();93 program94 .argument('[n]', 'number', () => {95 return callbackResult;96 })97 .action(() => {});98 program.parse(['node', 'test', 'alpha']);99 expect(program.args).toEqual(['alpha']);100});101102test('when custom with starting value and argument specified then callback called with value and starting value', () => {103 const mockCoercion = jest.fn();104 const startingValue = 1;105 const value = '2';106 const program = new commander.Command()107 .argument('[n]', 'number', mockCoercion, startingValue)108 .action(() => {});109 program.parse(['node', 'test', value]);110 expect(mockCoercion).toHaveBeenCalledWith(value, startingValue);111});112113test('when variadic argument specified multiple times then callback called with value and previousValue', () => {114 const mockCoercion = jest.fn().mockImplementation(() => {115 return 'callback';116 });117 const program = new commander.Command();118 program119 .argument('<n...>', 'number', mockCoercion)120 .action(() => {});121 program.parse(['1', '2'], { from: 'user' });122 expect(mockCoercion).toHaveBeenCalledTimes(2);123 expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined);124 expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');125});126127test('when parseFloat "1e2" then action argument is 100', () => {128 let actionValue;129 const program = new commander.Command();130 program131 .argument('<number>', 'float argument', parseFloat)132 .action((arg) => {133 actionValue = arg;134 });135 program.parse(['1e2'], { from: 'user' });136 expect(actionValue).toEqual(100);137});138139test('when defined default value for required argument then throw', () => {140 const program = new commander.Command();141 expect(() => {142 program.argument('<number>', 'float argument', 4);143 }).toThrow();144});
modified:tests/command.exitOverride.test.js+24 added-4 removed
270 unmodified lines
271 } catch (err) {272 caughtErr = err;273 }274275 expectCommanderError(caughtErr, 1, 'commander.invalidOptionArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");275 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");276 });277278 test('when custom processing throws InvalidOptionArgumentError then throw CommanderError', () => {278 test('when custom processing for option throws InvalidArgumentError then catch CommanderError', () => {279 function justSayNo(value) {280 throw new commander.InvalidOptionArgumentError('NO');280 throw new commander.InvalidArgumentError('NO');281 }282 const optionFlags = '--colour <shade>';283 const program = new commander.Command();284 program
6 unmodified lines
291 } catch (err) {292 caughtErr = err;293 }294295 expectCommanderError(caughtErr, 1, 'commander.invalidOptionArgument', "error: option '--colour <shade>' argument 'green' is invalid. NO");295 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. NO");296 });297298 test('when custom processing for argument throws InvalidArgumentError then catch CommanderError', () => {299 function justSayNo(value) {300 throw new commander.InvalidArgumentError('NO');301 }302 const program = new commander.Command();303 program304 .exitOverride()305 .argument('[n]', 'number', justSayNo)306 .action(() => {});307308 let caughtErr;309 try {310 program.parse(['green'], { from: 'user' });311 } catch (err) {312 caughtErr = err;313 }314315 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'n'. NO");316 });317});318319test('when no override and error then exit(1)', () => {320 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });
20 unmodified lines
modified:tests/command.help.test.js+9 added
251 unmodified lines
252 const helpInformation = program.helpInformation();253 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);254});255256test('when argument described with default then included in helpInformation', () => {257 const program = new commander.Command();258 program259 .argument('[file]', 'input source', 'test.txt')260 .helpOption(false);261 const helpInformation = program.helpInformation();262 expect(helpInformation).toMatch(/Arguments:\n +file +input source \(default: "test.txt"\)/);263});264265test('when arguments described in deprecated way then included in helpInformation', () => {266 const program = new commander.Command();267 program268 .arguments('<file>')
15 unmodified lines
modified:tests/esm-imports-test.mjs+2 added-2 removed
1import { program, Command, Option, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createArgument, createOption } from '../esm.mjs';1import { program, Command, Option, Argument, CommanderError, InvalidArgumentError, Help, createCommand, createArgument, createOption } from '../esm.mjs';23// Do some simple checks that expected imports are available at runtime.4// Run using `npm run test-esm`.5// Similar tests to test-imports.test.ts
17 unmodified lines
2324checkClass(new Command(), 'Command');25checkClass(new Option('-e, --example'), 'Option');26checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');27checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');27checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');28checkClass(new Help(), 'Help');29checkClass(new Argument('<file>'), 'Argument');3031console.log('Checking createCommand');
7 unmodified lines
added:tests/help.argumentDescription.test.js+30 added
modified:tests/ts-imports.test.ts+8 added-3 removed
1import { program, Command, Option, CommanderError, InvalidOptionArgumentError, Help, createCommand } from '../';1import { program, Command, Option, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Help, createCommand } from '../';23import * as commander from '../';45// Do some simple checks that expected imports are available at runtime.
28 unmodified lines
34test('CommanderError', () => {35 checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');36});3738test('InvalidOptionArgumentError', () => {39 checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');38test('InvalidArgumentError', () => {39 checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');40});4142test('InvalidOptionArgumentError', () => { // Deprecated43 checkClass(new InvalidOptionArgumentError('failed'), 'InvalidArgumentError');44});454647test('Help', () => {48 checkClass(new Help(), 'Help');49});
modified:typings/index.d.ts+7 added-4 removed
14 unmodified lines
15 }16 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;1718 // eslint-disable-next-line @typescript-eslint/no-empty-interface19 interface InvalidOptionArgumentError extends CommanderError {19 interface InvalidArgumentError extends CommanderError {20 }21 type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;21 type InvalidArgumentErrorConstructor = new (message: string) => InvalidArgumentError;2223 interface Argument {24 description: string;25 required: boolean;
243 unmodified lines
269 * program.argument('[output-file]');270 *271 * @returns `this` command for chaining272 */273 argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;273 argument(name: string, description?: string): this;274 argument(name: string, description?: string, defaultValue?: any): this;275276 /**277 * Define argument syntax for command, adding a prepared argument.278 *
392 unmodified lines
671 Command: CommandConstructor;672 Option: OptionConstructor;673 Argument: ArgumentConstructor;674 CommanderError: CommanderErrorConstructor;674 InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;675 InvalidArgumentError: InvalidArgumentErrorConstructor;676 /** @deprecated since v8, replaced by InvalidArgumentError */677 InvalidOptionArgumentError: InvalidArgumentErrorConstructor;678 Help: HelpConstructor;679 }680681}
5 unmodified lines
modified:typings/index.test-d.ts+5 added-1 removed
13 unmodified lines
14expectType<commander.Command>(new commander.Command());15expectType<commander.Command>(new commander.Command('name'));16expectType<commander.Option>(new commander.Option('-f'));17expectType<commander.CommanderError>(new commander.CommanderError(1, 'code', 'message'));18expectType<commander.InvalidOptionArgumentError>(new commander.InvalidOptionArgumentError('message'));18expectType<commander.InvalidArgumentError>(new commander.InvalidArgumentError('message'));19expectType<commander.InvalidArgumentError>(new commander.InvalidOptionArgumentError('message'));20expectType<commander.Command>(commander.createCommand());2122// Command properties23expectType<string[]>(program.args);
16 unmodified lines
4041// argument42expectType<commander.Command>(program.argument('<value>'));43expectType<commander.Command>(program.argument('<value>', 'description'));44expectType<commander.Command>(program.argument('[value]', 'description', 'default'));45expectType<commander.Command>(program.argument('[value]', 'description', parseFloat));46expectType<commander.Command>(program.argument('[value]', 'description', parseFloat, 1.23));4748// arguments49expectType<commander.Command>(program.arguments('<cmd> [env]'));50
305 unmodified lines
modified:esm.mjs+1 added-1 removed
5 unmodified lines
6 createCommand,7 createArgument,8 createOption,9 CommanderError,10 InvalidOptionArgumentError,10 InvalidArgumentError,11 Command,12 Argument,13 Option,14 Help
1 unmodified line
modified:index.js+108 added-16 removed
256 unmodified lines
257 * @return {string}258 */259260 argumentDescription(argument) {261 const extraInfo = [];262 if (argument.defaultValue !== undefined) {263 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);264 }265 if (extraInfo.length > 0) {266 return `${argument.description} (${extraInfo.join(', ')})`;267 }268 return argument.description;269 }270271 /**
119 unmodified lines
391392 constructor(name, description) {393 this.description = description || '';394 this.variadic = false;395 this.parseArg = undefined;396 this.defaultValue = undefined;397 this.defaultValueDescription = undefined;398399 switch (name[0]) {400 case '<': // e.g. <required>401 this.required = true;
23 unmodified lines
425426 name() {427 return this._name;428 };429430 /**431 * Set the default value, and optionally supply the description to be displayed in the help.432 *433 * @param {any} value434 * @param {string} [description]435 * @return {Argument}436 */437438 default(value, description) {439 this.defaultValue = value;440 this.defaultValueDescription = description;441 return this;442 };443444 /**445 * Set the custom handler for processing CLI command arguments into argument values.446 *447 * @param {Function} [fn]448 * @return {Argument}449 */450451 argParser(fn) {452 this.parseArg = fn;453 return this;454 };455}456457class Option {458 /**
98 unmodified lines
557 choices(values) {558 this.argChoices = values;559 this.parseArg = (arg, previous) => {560 if (!values.includes(arg)) {525 throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);561 throw new InvalidArgumentError(`Allowed choices are ${values.join(', ')}.`);562 }563 if (this.variadic) {564 return this._concatValue(arg, previous);565 }
63 unmodified lines
629 }630}631632/**597 * InvalidOptionArgumentError class633 * InvalidArgumentError class634 * @class635 */600class InvalidOptionArgumentError extends CommanderError {636class InvalidArgumentError extends CommanderError {637 /**602 * Constructs the InvalidOptionArgumentError class638 * Constructs the InvalidArgumentError class639 * @param {string} [message] explanation of why argument is invalid640 * @constructor641 */642 constructor(message) {607 super(1, 'commander.invalidOptionArgument', message);643 super(1, 'commander.invalidArgument', message);644 // properly capture stack trace in Node.js645 Error.captureStackTrace(this, this.constructor);646 this.name = this.constructor.name;647 }
251 unmodified lines
899 * program.argument('[output-file]');900 *901 * @param {string} name902 * @param {string} [description]903 * @param {Function|*} [fn] - custom argument processing function904 * @param {*} [defaultValue]905 * @return {Command} `this` command for chaining906 */869 argument(name, description) {907 argument(name, description, fn, defaultValue) {908 const argument = this.createArgument(name, description);909 if (typeof fn === 'function') {910 argument.default(defaultValue).argParser(fn);911 } else {912 argument.default(fn);913 }914 this.addArgument(argument);915 return this;916 }917
27 unmodified lines
945 const previousArgument = this._args.slice(-1)[0];946 if (previousArgument && previousArgument.variadic) {947 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);948 }949 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {950 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);951 }952 this._args.push(argument);953 return this;954 }955
165 unmodified lines
1121 if (val !== null && option.parseArg) {1122 try {1123 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);1124 } catch (err) {1079 if (err.code === 'commander.invalidOptionArgument') {1125 if (err.code === 'commander.invalidArgument') {1126 const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;1127 this._displayError(err.exitCode, err.code, message);1128 }1129 throw err;
440 unmodified lines
15701571 /**1572 * @api private1573 */15741575 _dispatchSubcommand(commandName, operands, unknown) {1576 const subCommand = this._findCommand(commandName);1577 if (!subCommand) this.help({ error: true });1578
4 unmodified lines
1583 }1584 };15851586 /**1587 * Package arguments (this.args) for passing to action handler based1588 * on declared arguments (this._args).1589 *1590 * @api private1591 */15921593 _getActionArguments() {1594 const myParseArg = (argument, value, previous) => {1595 // Extra processing for nice error message on parsing failure.1596 let parsedValue = value;1597 if (value !== null && argument.parseArg) {1598 try {1599 parsedValue = argument.parseArg(value, previous);1600 } catch (err) {1601 if (err.code === 'commander.invalidArgument') {1602 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1603 this._displayError(err.exitCode, err.code, message);1604 }1605 throw err;1606 }1607 }1608 return parsedValue;1609 };16101611 const actionArgs = [];1612 this._args.forEach((declaredArg, index) => {1613 let value = declaredArg.defaultValue;1614 if (declaredArg.variadic) {1615 // Collect together remaining arguments for passing together as an array.1616 if (index < this.args.length) {1617 value = this.args.slice(index);1618 if (declaredArg.parseArg) {1619 value = value.reduce((processed, v) => {1620 return myParseArg(declaredArg, v, processed);1621 }, declaredArg.defaultValue);1622 }1623 } else if (value === undefined) {1624 value = [];1625 }1626 } else if (index < this.args.length) {1627 value = this.args[index];1628 if (declaredArg.parseArg) {1629 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1630 }1631 }1632 actionArgs[index] = value;1633 });1634 return actionArgs;1635 }16361637 /**1638 * Process arguments in context of this command.1639 *1640 * @api private1641 */
49 unmodified lines
1691 const commandEvent = `command:${this.name()}`;1692 if (this._actionHandler) {1693 checkForUnknownOptions();1694 checkNumberOfArguments();1597 // Collect trailing args into variadic.1598 let actionArgs = this.args;1599 const declaredArgCount = this._args.length;1600 if (declaredArgCount > 0 && this._args[declaredArgCount - 1].variadic) {1601 actionArgs = this.args.slice(0, declaredArgCount - 1);1602 actionArgs[declaredArgCount - 1] = this.args.slice(declaredArgCount - 1);1603 }1604 this._actionHandler(actionArgs);1695 this._actionHandler(this._getActionArguments());1696 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1697 } else if (this.parent && this.parent.listenerCount(commandEvent)) {1698 checkForUnknownOptions();1699 checkNumberOfArguments();
594 unmodified lines
2294exports.Command = Command;2295exports.Option = Option;2296exports.Argument = Argument;2297exports.CommanderError = CommanderError;2207exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2298exports.InvalidArgumentError = InvalidArgumentError;2299exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated2300exports.Help = Help;23012302/**2303 * Camel-case the given `flag`
113 unmodified lines
modified:Readme_zh-CN.md+2 added-2 removed
312 unmodified lines
313function myParseInt(value, dummyPrevious) {314 // parseInt takes a string and a radix315 const parsedValue = parseInt(value, 10);316 if (isNaN(parsedValue)) {317 throw new commander.InvalidOptionArgumentError('Not a number.');317 throw new commander.InvalidArgumentError('Not a number.');318 }319 return parsedValue;320}321
554 unmodified lines
876### 企业使用 Commander877878现在 Commander 已作为 Tidelift 订阅的一部分。879880Commander 和很多其他包的维护者已与 Tidelift 合作,面向企业提供开源依赖的商业支持与维护。企业可以向相关依赖包的维护者支付一定的费用,帮助企业节省时间,降低风险,改进代码运行情况。[了解更多](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)880Commander 和很多其他包的维护者已与 Tidelift 合作,面向企业提供开源依赖的商业支持与维护。企业可以向相关依赖包的维护者支付一定的费用,帮助企业节省时间,降低风险,改进代码运行情况。[了解更多](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
modified:Readme.md+27 added-3 removed
21 unmodified lines
22 - [More configuration](#more-configuration)23 - [Custom option processing](#custom-option-processing)24 - [Commands](#commands)25 - [Specify the argument syntax](#specify-the-argument-syntax)26 - [Custom argument processing](#custom-argument-processing)27 - [Action handler](#action-handler)28 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)29 - [Automated help](#automated-help)30 - [Custom help](#custom-help)
311 unmodified lines
342function myParseInt(value, dummyPrevious) {343 // parseInt takes a string and a radix344 const parsedValue = parseInt(value, 10);345 if (isNaN(parsedValue)) {345 throw new commander.InvalidOptionArgumentError('Not a number.');346 throw new commander.InvalidArgumentError('Not a number.');347 }348 return parsedValue;349}350
83 unmodified lines
434you can instead use the following method.435436To configure a command, you can use `.argument()` to specify each expected command-argument. 437You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.438You can specify a default value for an optional command-argument.439440441Example file: [argument.js](./examples/argument.js)442443```js444program445 .version('0.1.0')446 .argument('<username>', 'user to login')444 .argument('[password]', 'password for user, if required')447 .argument('[password]', 'password for user, if required', 'no password given')448 .action((username, password) => {449 console.log('username:', username);447 console.log('password:', password || 'no password given');450 console.log('password:', password);451 });452```453454 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
17 unmodified lines
472program473 .arguments('<username> <password>');474```475476### Custom argument processing477478You may specify a function to do custom processing of command-arguments before they are passed to the action handler.479The callback function receives two parameters, the user specified command-argument and the previous value for the argument.480It returns the new value for the argument.481482You can optionally specify the default/starting value for the argument after the function parameter.483484Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)485486```js487program488 .command('add')489 .argument('<first>', 'integer argument', myParseInt)490 .argument('[second]', 'integer argument', myParseInt, 1000)491 .action((first, second) => {492 console.log(`${first} + ${second} = ${first + second}`);493 })494;495```496497### Action handler498499The action handler gets passed a parameter for each command-argument you declared, and two additional parameters500which are the parsed options and the command object itself.
446 unmodified lines