Skip to content
Myr

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

12 files+213 added−11 removed

added:examples/arguments-extra.js+23 added
modified:lib/argument.js+36 added
modified:lib/help.js+10 added-1 removed
258 unmodified lines
259 */260261 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 lines
added:tests/argument.chain.test.js+21 added
modified:tests/argument.custom-processing.test.js+12 added
161 unmodified lines
162163 expect(caughtErr).toBeInstanceOf(Error);164 expect(caughtErr).not.toBeInstanceOf(commander.CommanderError);165});166167// this is the happy path, testing failure case in command.exitOverride.test.js168test('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 lines
80 .argument('[args...]');8182 expect(program.usage()).toBe('[options] [args...]');83 });8485 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; });9192 program.parse(['one'], { from: 'user' });93 expect(passedArg).toEqual(['one']);94 });9596 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; });102103 program.parse(['one', 'two'], { from: 'user' });104 expect(passedArg).toEqual(['one', 'two']);105 });106});
modified:tests/command.exitOverride.test.js+17 added
273 unmodified lines
274275 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");276 });277278 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(() => {});284285 let caughtErr;286 try {287 program.parse(['green'], { from: 'user' });288 } catch (err) {289 caughtErr = err;290 }291292 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'shade'. Allowed choices are red, blue.");293 });294295 test('when custom processing for option throws InvalidArgumentError then catch CommanderError', () => {296 function justSayNo(value) {297 throw new commander.InvalidArgumentError('NO');298 }
59 unmodified lines
modified:tests/command.help.test.js+16 added
279 unmodified lines
280 .description('', { file: 'input source' });281 const helpInformation = program.helpInformation();282 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);283});284285test('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});292293test('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 lines
26 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 });3031 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 lines
45 * @param {string} [description]46 */47 constructor(arg: string, description?: string);4849 /**50 * Return argument name.51 */52 name(): string;49 /**50 * Return argument name.51 */52 name(): string;5354 /**55 * Set the default value, and optionally supply the description to be displayed in the help.56 */57 default(value: unknown, description?: string): this;5859 /**60 * Set the custom handler for processing CLI command arguments into argument values.61 */62 argParser<T>(fn: (value: string, previous: T) => T): this;6364 /**65 * Only allow argument value to be one of choices.66 */67 choices(values: string[]): this;6869 }7071export class Option {72 flags: string;
654 unmodified lines
modified:typings/index.test-d.ts+12 added
359 unmodified lines
360expectType<boolean>(baseArgument.required);361expectType<boolean>(baseArgument.variadic);362363// Argument methods364365// name366expectType<string>(baseArgument.name());367368// default369expectType<commander.Argument>(baseArgument.default(3));370expectType<commander.Argument>(baseArgument.default(60, 'one minute'));371372// argParser373expectType<commander.Argument>(baseArgument.argParser((value: string) => parseInt(value)));374expectType<commander.Argument>(baseArgument.argParser((value: string, previous: string[]) => { return previous.concat(value); }));375376// choices377expectType<commander.Argument>(baseArgument.choices(['a', 'b']));378379// createArgument380expectType<commander.Argument>(program.createArgument('<name>'));381expectType<commander.Argument>(program.createArgument('<name>', 'description'));
modified:Readme.md+18 added-6 removed
20 unmodified lines
21 - [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 line
33 - [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 lines
428Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will 429remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other430subcommand is specified ([example](./examples/defaultCommand.js)).431431### Specify the argument syntax432### Command-arguments433434For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This435is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands436you can instead use the following method.
1 unmodified line
438To configure a command, you can use `.argument()` to specify each expected command-argument. 439You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.440You can specify a default value for an optional command-argument.441441442Example file: [argument.js](./examples/argument.js)443444```js445program
27 unmodified lines
473program474 .arguments('<username> <password>');475```476477### Custom argument processing477#### More configuration478479There are some additional features available by constructing an `Argument` explicitly for less common cases.480481Example file: [arguments-extra.js](./examples/arguments-extra.js)482483```js484program485 .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```488489#### Custom argument processing490491You may specify a function to do custom processing of command-arguments before they are passed to the action handler.492The callback function receives two parameters, the user specified command-argument and the previous value for the argument.493It returns the new value for the argument.494
492 unmodified lines