Choices for arguments (#1525)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add Argument choices, and missing types and tests for default and argParse * Only make arguments visible if some description, not just default or choices * Improve format for partial argument descriptions * Add argument choices to README * Add test for edge case in argumentDescription
authored by John Gee · committed by GitHub · parent d282f20 · Browse files · 12 files·+213 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+213 added−11 removed
- tests:+94 added−0 removed
- other:+119 added−11 removed
Provenance
- Commit
708527e- Tree
897b25d- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
d282f20
12 files changed+213 added−11 removed
added:examples/arguments-extra.js+23 added
1234567891011121314151617181920212223#!/usr/bin/env node
// This is used as an example in the README for extra argument features.
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
program .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large'])) .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute')) .action((drinkSize, timeout) => { console.log(`Drink size: ${drinkSize}`); console.log(`Timeout (s): ${timeout}`); });
program.parse();
// Try the following:// node arguments-extra.js --help// node arguments-extra.js huge// node arguments-extra.js small// node arguments-extra.js medium 30modified:lib/argument.js+36 added
12345610 unmodified lines17181920212223242525 unmodified lines515253545556575859606162636465666768697016 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411516 unmodified linesconst { InvalidArgumentError } = require('./error.js');
// @ts-check
class Argument { /**10 unmodified lines this.variadic = false; this.parseArg = undefined; this.defaultValue = undefined; this.defaultValueDescription = undefined; this.argChoices = undefined;
switch (name[0]) { case '<': // e.g. <required> this.required = true;25 unmodified lines return this._name; };
/** * @api private */
_concatValue(value, previous) { if (previous === this.defaultValue || !Array.isArray(previous)) { return [value]; }
return previous.concat(value); }
/** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {any} value * @param {string} [description]16 unmodified lines argParser(fn) { this.parseArg = fn; return this; };
/** * Only allow option value to be one of choices. * * @param {string[]} values * @return {Argument} */
choices(values) { this.argChoices = values; this.parseArg = (arg, previous) => { if (!values.includes(arg)) { throw new InvalidArgumentError(`Allowed choices are ${values.join(', ')}.`); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; };}
/** * Takes an argument and returns its human readable equivalent for help usage.16 unmodified linesmodified:lib/help.js+10 added-1 removed
258 unmodified lines259 */260 261 argumentDescription(argument) {262 const extraInfo = [];263+ if (argument.argChoices) {264+ extraInfo.push(265+ // use stringify to match the display of the default value266+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);267+ }268 if (argument.defaultValue !== undefined) {269 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);270 }271 if (extraInfo.length > 0) {267- return `${argument.description} (${extraInfo.join(', ')})`;272+ const extraDescripton = `(${extraInfo.join(', ')})`;273+ if (argument.description) {274+ return `${argument.description} ${extraDescripton}`;275+ }276+ return extraDescripton;277 }278 return argument.description;279 }280 112 unmodified linesadded:tests/argument.chain.test.js+21 added
123456789101112131415161718192021const { Argument } = require('../');
describe('Argument methods that should return this for chaining', () => { test('when call .default() then returns this', () => { const argument = new Argument('<value>'); const result = argument.default(3); expect(result).toBe(argument); });
test('when call .argParser() then returns this', () => { const argument = new Argument('<value>'); const result = argument.argParser(() => { }); expect(result).toBe(argument); });
test('when call .choices() then returns this', () => { const argument = new Argument('<value>'); const result = argument.choices(['a']); expect(result).toBe(argument); });});modified:tests/argument.custom-processing.test.js+12 added
161 unmodified lines162 163 expect(caughtErr).toBeInstanceOf(Error);164 expect(caughtErr).not.toBeInstanceOf(commander.CommanderError);165 });166+167+// this is the happy path, testing failure case in command.exitOverride.test.js168+test('when argument argument in choices then argument set', () => {169+ const program = new commander.Command();170+ let shade;171+ program172+ .exitOverride()173+ .addArgument(new commander.Argument('<shade>').choices(['red', 'blue']))174+ .action((shadeParam) => { shade = shadeParam; });175+ program.parse(['red'], { from: 'user' });176+ expect(shade).toBe('red');177+});modified:tests/argument.variadic.test.js+22 added
79 unmodified lines80 .argument('[args...]');81 82 expect(program.usage()).toBe('[options] [args...]');83 });84+85+ test('when variadic used with choices and one value then set in array', () => {86+ const program = new commander.Command();87+ let passedArg;88+ program89+ .addArgument(new commander.Argument('<value...>').choices(['one', 'two']))90+ .action((value) => { passedArg = value; });91+92+ program.parse(['one'], { from: 'user' });93+ expect(passedArg).toEqual(['one']);94+ });95+96+ test('when variadic used with choices and two values then set in array', () => {97+ const program = new commander.Command();98+ let passedArg;99+ program100+ .addArgument(new commander.Argument('<value...>').choices(['one', 'two']))101+ .action((value) => { passedArg = value; });102+103+ program.parse(['one', 'two'], { from: 'user' });104+ expect(passedArg).toEqual(['one', 'two']);105+ });106 });modified:tests/command.exitOverride.test.js+17 added
273 unmodified lines274 275 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");276 });277 278+ test('when command argument not in choices then throw CommanderError', () => {279+ const program = new commander.Command();280+ program281+ .exitOverride()282+ .addArgument(new commander.Argument('<shade>').choices(['red', 'blue']))283+ .action(() => {});284+285+ let caughtErr;286+ try {287+ program.parse(['green'], { from: 'user' });288+ } catch (err) {289+ caughtErr = err;290+ }291+292+ expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'shade'. Allowed choices are red, blue.");293+ });294+295 test('when custom processing for option throws InvalidArgumentError then catch CommanderError', () => {296 function justSayNo(value) {297 throw new commander.InvalidArgumentError('NO');298 }59 unmodified linesmodified:tests/command.help.test.js+16 added
279 unmodified lines280 .description('', { file: 'input source' });281 const helpInformation = program.helpInformation();282 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);283 });284+285+test('when argument has choices then choices included in helpInformation', () => {286+ const program = new commander.Command();287+ program288+ .addArgument(new commander.Argument('<colour>', 'preferred colour').choices(['red', 'blue']));289+ const helpInformation = program.helpInformation();290+ expect(helpInformation).toMatch('(choices: "red", "blue")');291+});292+293+test('when argument has choices and default then both included in helpInformation', () => {294+ const program = new commander.Command();295+ program296+ .addArgument(new commander.Argument('<colour>', 'preferred colour').choices(['red', 'blue']).default('red'));297+ const helpInformation = program.helpInformation();298+ expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');299+});modified:tests/help.argumentDescription.test.js+6 added
25 unmodified lines26 const argument = new commander.Argument('[n]', 'description').default('default value', 'custom');27 const helper = new commander.Help();28 expect(helper.argumentDescription(argument)).toEqual('description (default: custom)');29 });30+31+ test('when an argument has default value and no description then still return default value', () => {32+ const argument = new commander.Argument('[n]').default('default');33+ const helper = new commander.Help();34+ expect(helper.argumentDescription(argument)).toEqual('(default: "default")');35+ });36 });modified:typings/index.d.ts+20 added-4 removed
44 unmodified lines45 * @param {string} [description]46 */47 constructor(arg: string, description?: string);48 49- /**50- * Return argument name.51- */52- name(): string;49+ /**50+ * Return argument name.51+ */52+ name(): string;53+54+ /**55+ * Set the default value, and optionally supply the description to be displayed in the help.56+ */57+ default(value: unknown, description?: string): this;58+59+ /**60+ * Set the custom handler for processing CLI command arguments into argument values.61+ */62+ argParser<T>(fn: (value: string, previous: T) => T): this;63+64+ /**65+ * Only allow argument value to be one of choices.66+ */67+ choices(values: string[]): this;68+69 }70 71 export class Option {72 flags: string;654 unmodified linesmodified:typings/index.test-d.ts+12 added
359 unmodified lines360 expectType<boolean>(baseArgument.required);361 expectType<boolean>(baseArgument.variadic);362 363 // Argument methods364+365 // name366 expectType<string>(baseArgument.name());367 368+// default369+expectType<commander.Argument>(baseArgument.default(3));370+expectType<commander.Argument>(baseArgument.default(60, 'one minute'));371+372+// argParser373+expectType<commander.Argument>(baseArgument.argParser((value: string) => parseInt(value)));374+expectType<commander.Argument>(baseArgument.argParser((value: string, previous: string[]) => { return previous.concat(value); }));375+376+// choices377+expectType<commander.Argument>(baseArgument.choices(['a', 'b']));378+379 // createArgument380 expectType<commander.Argument>(program.createArgument('<name>'));381 expectType<commander.Argument>(program.createArgument('<name>', 'description'));modified:Readme.md+18 added-6 removed
20 unmodified lines21 - [Version option](#version-option)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)25+ - [Command-arguments](#command-arguments)26+ - [More configuration](#more-configuration-1)27+ - [Custom argument processing](#custom-argument-processing)28 - [Action handler](#action-handler)29 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)30 - [Life cycle hooks](#life-cycle-hooks)31 - [Automated help](#automated-help)1 unmodified line33 - [Display help from code](#display-help-from-code)34 - [.usage and .name](#usage-and-name)35 - [.helpOption(flags, description)](#helpoptionflags-description)36 - [.addHelpCommand()](#addhelpcommand)36- - [More configuration](#more-configuration-1)37+ - [More configuration](#more-configuration-2)38 - [Custom event listeners](#custom-event-listeners)39 - [Bits and pieces](#bits-and-pieces)40 - [.parse() and .parseAsync()](#parse-and-parseasync)41 - [Parsing Configuration](#parsing-configuration)386 unmodified lines428 Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will 429 remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other430 subcommand is specified ([example](./examples/defaultCommand.js)).431 431-### Specify the argument syntax432+### Command-arguments433 434 For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This435 is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands436 you can instead use the following method.1 unmodified line438 To configure a command, you can use `.argument()` to specify each expected command-argument. 439 You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.440 You can specify a default value for an optional command-argument.441 441-442 Example file: [argument.js](./examples/argument.js)443 444 ```js445 program27 unmodified lines473 program474 .arguments('<username> <password>');475 ```476 477-### Custom argument processing477+#### More configuration478 479+There are some additional features available by constructing an `Argument` explicitly for less common cases.480+481+Example file: [arguments-extra.js](./examples/arguments-extra.js)482+483+```js484+program485+ .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))486+ .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))487+```488+489+#### Custom argument processing490+491 You may specify a function to do custom processing of command-arguments before they are passed to the action handler.492 The callback function receives two parameters, the user specified command-argument and the previous value for the argument.493 It returns the new value for the argument.494 492 unmodified lines