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
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
Provenance
- Commit
f99d6fa- Tree
4f5c459- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
3d67542
16 files changed+446 added−39 removed
modified:docs/deprecated.md+29 added
109 unmodified linesExpand all110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142109 unmodified linesExpand all
Deprecated from Commander v8.
## InvalidOptionArgumentError
This was used for throwing an error from custom option processing, for a nice error message.
```jsfunction myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidOptionArgumentError('Not a number.'); } return parsedValue;}```
The replacement is `InvalidArgumentError` since can be used now for custom command-argument processing too.
```jsfunction myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidArgumentError('Not a number.'); } return parsedValue;}```
Deprecated from Commander v8.modified:examples/argument.js+2 added-2 removed
7 unmodified lines89101112121314151616171819204 unmodified lines7 unmodified lines
program .version('0.1.0') .argument('<username>', 'user to login') .argument('[password]', 'password for user, if required') .argument('[password]', 'password for user, if required', 'no password given') .description('example program for argument') .action((username, password) => { console.log('username:', username); console.log('password:', password || 'no password given'); console.log('password:', password); });
program.parse();
4 unmodified linesadded:examples/arguments-custom-processing.js+47 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/usr/bin/env node
// This is used as an example in the README for:// Custom argument processing// You may specify a function to do custom processing of argument values.
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
function myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidArgumentError('Not a number.'); } return parsedValue;}
// The previous value passed to the custom processing is used when processing variadic values.function mySum(value, total) { return total + myParseInt(value);}
program .command('add') .argument('<first>', 'integer argument', myParseInt) .argument('[second]', 'integer argument', myParseInt, 1000) .action((first, second) => { console.log(`${first} + ${second} = ${first + second}`); });
program .command('sum') .argument('<value...>', 'values to be summed', mySum, 0) .action((total) => { console.log(`sum is ${total}`); });
program.parse();
// Try the following:// node arguments-custom-processing add --help// node arguments-custom-processing add 2// node arguments-custom-processing add 12 56// node arguments-custom-processing sum 1 2 3// node arguments-custom-processing sum sillymodified:examples/options-custom-processing.js+1 added-1 removed
10 unmodified lines11 function 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 linesadded:tests/argument.custom-processing.test.js+144 added
1+const commander = require('../');2+3+// Testing default value and custom processing behaviours.4+5+test('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+});14+15+test('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+});26+27+test('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+});36+37+test('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+});49+50+test('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+});62+63+test('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+});73+74+test('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+});88+89+test('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+});101+102+test('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+});112+113+test('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+});126+127+test('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+});138+139+test('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 lines271 } catch (err) {272 caughtErr = err;273 }274 275- 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 });277 278- 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 program6 unmodified lines291 } catch (err) {292 caughtErr = err;293 }294 295- 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 });297+298+ 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(() => {});307+308+ let caughtErr;309+ try {310+ program.parse(['green'], { from: 'user' });311+ } catch (err) {312+ caughtErr = err;313+ }314+315+ expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'n'. NO");316+ });317 });318 319 test('when no override and error then exit(1)', () => {320 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });20 unmodified linesmodified:tests/command.help.test.js+9 added
251 unmodified lines252 const helpInformation = program.helpInformation();253 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);254 });255 256+test('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+});264+265 test('when arguments described in deprecated way then included in helpInformation', () => {266 const program = new commander.Command();267 program268 .arguments('<file>')15 unmodified linesmodified:tests/esm-imports-test.mjs+2 added-2 removed
1-import { program, Command, Option, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createArgument, createOption } from '../esm.mjs';1+import { program, Command, Option, Argument, CommanderError, InvalidArgumentError, Help, createCommand, createArgument, createOption } from '../esm.mjs';2 3 // 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.ts17 unmodified lines23 24 checkClass(new Command(), 'Command');25 checkClass(new Option('-e, --example'), 'Option');26 checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');27-checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');27+checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');28 checkClass(new Help(), 'Help');29 checkClass(new Argument('<file>'), 'Argument');30 31 console.log('Checking createCommand');7 unmodified linesadded:tests/help.argumentDescription.test.js+30 added
123456789101112131415161718192021222324252627282930const commander = require('../');
// These are tests of the Help class, not of the Command help.
describe('argumentDescription', () => { test('when argument has no description then empty string', () => { const argument = new commander.Argument('[n]'); const helper = new commander.Help(); expect(helper.argumentDescription(argument)).toEqual(''); });
test('when argument has description then return description', () => { const description = 'description'; const argument = new commander.Argument('[n]', description); const helper = new commander.Help(); expect(helper.argumentDescription(argument)).toEqual(description); });
test('when argument has default value then return description and default value', () => { const argument = new commander.Argument('[n]', 'description').default('default'); const helper = new commander.Help(); expect(helper.argumentDescription(argument)).toEqual('description (default: "default")'); });
test('when argument has default value description then return description and custom default description', () => { const argument = new commander.Argument('[n]', 'description').default('default value', 'custom'); const helper = new commander.Help(); expect(helper.argumentDescription(argument)).toEqual('description (default: custom)'); });});modified:tests/ts-imports.test.ts+8 added-3 removed
1-import { program, Command, Option, CommanderError, InvalidOptionArgumentError, Help, createCommand } from '../';1+import { program, Command, Option, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Help, createCommand } from '../';2 3 import * as commander from '../';4 5 // Do some simple checks that expected imports are available at runtime.28 unmodified lines34 test('CommanderError', () => {35 checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');36 });37 38-test('InvalidOptionArgumentError', () => {39- checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');38+test('InvalidArgumentError', () => {39+ checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');40 });41 42+test('InvalidOptionArgumentError', () => { // Deprecated43+ checkClass(new InvalidOptionArgumentError('failed'), 'InvalidArgumentError');44+});45+46+47 test('Help', () => {48 checkClass(new Help(), 'Help');49 });modified:typings/index.d.ts+7 added-4 removed
14 unmodified lines15 }16 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;17 18 // 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;22 23 interface Argument {24 description: string;25 required: boolean;243 unmodified lines269 * 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;275 276 /**277 * Define argument syntax for command, adding a prepared argument.278 *392 unmodified lines671 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 }680 681 }5 unmodified linesmodified:typings/index.test-d.ts+5 added-1 removed
13 unmodified lines14 expectType<commander.Command>(new commander.Command());15 expectType<commander.Command>(new commander.Command('name'));16 expectType<commander.Option>(new commander.Option('-f'));17 expectType<commander.CommanderError>(new commander.CommanderError(1, 'code', 'message'));18-expectType<commander.InvalidOptionArgumentError>(new commander.InvalidOptionArgumentError('message'));18+expectType<commander.InvalidArgumentError>(new commander.InvalidArgumentError('message'));19+expectType<commander.InvalidArgumentError>(new commander.InvalidOptionArgumentError('message'));20 expectType<commander.Command>(commander.createCommand());21 22 // Command properties23 expectType<string[]>(program.args);16 unmodified lines40 41 // argument42 expectType<commander.Command>(program.argument('<value>'));43 expectType<commander.Command>(program.argument('<value>', 'description'));44+expectType<commander.Command>(program.argument('[value]', 'description', 'default'));45+expectType<commander.Command>(program.argument('[value]', 'description', parseFloat));46+expectType<commander.Command>(program.argument('[value]', 'description', parseFloat, 1.23));47 48 // arguments49 expectType<commander.Command>(program.arguments('<cmd> [env]'));50 305 unmodified linesmodified:esm.mjs+1 added-1 removed
5 unmodified lines6 createCommand,7 createArgument,8 createOption,9 CommanderError,10- InvalidOptionArgumentError,10+ InvalidArgumentError,11 Command,12 Argument,13 Option,14 Help1 unmodified linemodified:index.js+108 added-16 removed
256 unmodified lines257 * @return {string}258 */259 260 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 }270 271 /**119 unmodified lines391 392 constructor(name, description) {393 this.description = description || '';394 this.variadic = false;395+ this.parseArg = undefined;396+ this.defaultValue = undefined;397+ this.defaultValueDescription = undefined;398 399 switch (name[0]) {400 case '<': // e.g. <required>401 this.required = true;23 unmodified lines425 426 name() {427 return this._name;428 };429+430+ /**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+ */437+438+ default(value, description) {439+ this.defaultValue = value;440+ this.defaultValueDescription = description;441+ return this;442+ };443+444+ /**445+ * Set the custom handler for processing CLI command arguments into argument values.446+ *447+ * @param {Function} [fn]448+ * @return {Argument}449+ */450+451+ argParser(fn) {452+ this.parseArg = fn;453+ return this;454+ };455 }456 457 class Option {458 /**98 unmodified lines557 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 lines629 }630 }631 632 /**597- * InvalidOptionArgumentError class633+ * InvalidArgumentError class634 * @class635 */600-class InvalidOptionArgumentError extends CommanderError {636+class 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 lines899 * 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 lines945 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 lines1121 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 lines1570 1571 /**1572 * @api private1573 */1574+1575 _dispatchSubcommand(commandName, operands, unknown) {1576 const subCommand = this._findCommand(commandName);1577 if (!subCommand) this.help({ error: true });1578 4 unmodified lines1583 }1584 };1585 1586 /**1587+ * Package arguments (this.args) for passing to action handler based1588+ * on declared arguments (this._args).1589+ *1590+ * @api private1591+ */1592+1593+ _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+ };1610+1611+ 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+ }1636+1637+ /**1638 * Process arguments in context of this command.1639 *1640 * @api private1641 */49 unmodified lines1691 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 lines2294 exports.Command = Command;2295 exports.Option = Option;2296 exports.Argument = Argument;2297 exports.CommanderError = CommanderError;2207-exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2298+exports.InvalidArgumentError = InvalidArgumentError;2299+exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated2300 exports.Help = Help;2301 2302 /**2303 * Camel-case the given `flag`113 unmodified linesmodified:Readme_zh-CN.md+2 added-2 removed
312 unmodified lines313 function 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 lines876 ### 企业使用 Commander877 878 现在 Commander 已作为 Tidelift 订阅的一部分。879 880-Commander 和很多其他包的维护者已与 Tidelift 合作,面向企业提供开源依赖的商业支持与维护。企业可以向相关依赖包的维护者支付一定的费用,帮助企业节省时间,降低风险,改进代码运行情况。[了解更多](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)880+Commander 和很多其他包的维护者已与 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 lines22 - [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 lines342 function 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 lines434 you can instead use the following method.435 436 To configure a command, you can use `.argument()` to specify each expected command-argument. 437 You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.438+You can specify a default value for an optional command-argument.439 440+441 Example file: [argument.js](./examples/argument.js)442 443 ```js444 program445 .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 ```453 454 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you17 unmodified lines472 program473 .arguments('<username> <password>');474 ```475 476+### Custom argument processing477+478+You may specify a function to do custom processing of command-arguments before they are passed to the action handler.479+The callback function receives two parameters, the user specified command-argument and the previous value for the argument.480+It returns the new value for the argument.481+482+You can optionally specify the default/starting value for the argument after the function parameter.483+484+Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)485+486+```js487+program488+ .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+```496+497 ### Action handler498 499 The action handler gets passed a parameter for each command-argument you declared, and two additional parameters500 which are the parsed options and the command object itself. 446 unmodified lines