Skip to content
Myr

Support custom error messages for option argument coercion failures (#1392)

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

* Make commander.optionArgumentRejected reusable * Add InvalidOptionArgumentError to simplify usage * Add TypeScript for InvalidOptionArgumentError * Add test for InvalidOptionArgumentError from custom option processing * Add InvalidOptionArgumentError to example and README

authored by John Gee · committed by GitHub · parent e1a6cf4 · Browse files · 6 files+64 added−18 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+64 added−18 removed

  • tests:+21 added−1 removed
  • other:+43 added−17 removed

6 files+64 added−18 removed

modified:examples/options-custom-processing.js+7 added-1 removed
modified:tests/command.exitOverride.test.js+21 added-1 removed
216 unmodified lines
217 } catch (err) {218 caughtErr = err;219 }220221 expectCommanderError(caughtErr, 1, 'commander.optionArgumentRejected', `error: option '${optionFlags}' argument of 'green' not in allowed choices: red, blue`);221 expectCommanderError(caughtErr, 1, 'commander.invalidOptionArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");222 });223224 test('when custom processing throws InvalidOptionArgumentError then throw CommanderError', () => {225 function justSayNo(value) {226 throw new commander.InvalidOptionArgumentError('NO');227 }228 const optionFlags = '--colour <shade>';229 const program = new commander.Command();230 program231 .exitOverride()232 .option(optionFlags, 'specify shade', justSayNo);233234 let caughtErr;235 try {236 program.parse(['--colour', 'green'], { from: 'user' });237 } catch (err) {238 caughtErr = err;239 }240241 expectCommanderError(caughtErr, 1, 'commander.invalidOptionArgument', "error: option '--colour <shade>' argument 'green' is invalid. NO");242 });243});
modified:typings/commander-tests.ts+1 added
28 unmodified lines
29const commandInstance1 = new commander.Command();30const commandInstance2 = new commander.Command('name');31const optionsInstance = new commander.Option('-f');32const errorInstance = new commander.CommanderError(1, 'code', 'message');33const invalidOptionErrorInstance = new commander.InvalidOptionArgumentError('message');3435// Command properties36console.log(programWithOptions.someOption);37// eslint-disable-next-line @typescript-eslint/dot-notation
305 unmodified lines
modified:typings/index.d.ts+5 added
12 unmodified lines
13 nestedError?: string;14 }15 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;1617 interface InvalidOptionArgumentError extends CommanderError {18 }19 type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;2021 interface Option {22 flags: string;23 description: string;24
555 unmodified lines
580 program: Command;581 Command: CommandConstructor;582 Option: OptionConstructor;583 CommanderError: CommanderErrorConstructor;584 InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;585 Help: HelpConstructor;586 }587588}
5 unmodified lines
modified:index.js+23 added-13 removed
424 unmodified lines
425 return this;426 };427428 /**429 * Validation of option argument failed.430 * Intended for use from custom argument processing functions.431 *432 * @param {string} message433 */434 argumentRejected(message) {435 throw new CommanderError(1, 'commander.optionArgumentRejected', message);436 }437438 /**429 * Only allow option value to be one of choices.430 *431 * @param {string[]} values432 * @return {Option}
2 unmodified lines
435 choices(values) {436 this.argChoices = values;437 this.parseArg = (arg) => {438 if (!values.includes(arg)) {449 this.argumentRejected(`error: option '${this.flags}' argument of '${arg}' not in allowed choices: ${values.join(', ')}`);439 throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);440 }441 return arg;442 };443 return this;
59 unmodified lines
503 this.nestedError = undefined;504 }505}506507/**508 * InvalidOptionArgumentError class509 * @class510 */511class InvalidOptionArgumentError extends CommanderError {512 /**513 * Constructs the InvalidOptionArgumentError class514 * @param {string} [message] explanation of why argument is invalid515 * @constructor516 */517 constructor(message) {518 super(1, 'commander.invalidOptionArgument', message);519 // properly capture stack trace in Node.js520 Error.captureStackTrace(this, this.constructor);521 this.name = this.constructor.name;522 }523}524525class Command extends EventEmitter {526 /**527 * Initialize a new `Command`.528 *
483 unmodified lines
1012 if (val !== null && option.parseArg) {1013 try {1014 val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);1015 } catch (err) {1008 if (err.code === 'commander.optionArgumentRejected') {1009 this._displayError(err.exitCode, err.code, err.message);1016 if (err.code === 'commander.invalidOptionArgument') {1017 const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;1018 this._displayError(err.exitCode, err.code, message);1019 }1020 throw err;1021 }1022 } else if (val !== null && option.variadic) {
1028 unmodified lines
20512052exports.Command = Command;2053exports.Option = Option;2054exports.CommanderError = CommanderError;2055exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2056exports.Help = Help;20572058/**2059 * Camel-case the given `flag`
113 unmodified lines
modified:Readme.md+7 added-3 removed
301 unmodified lines
302 -d, --drink <size> drink cup size (choices: "small", "medium", "large")303 -h, --help display help for command304305$ extra --drink huge306error: option '-d, --drink <size>' argument of 'huge' not in allowed choices: small, medium, large306error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.307```308309### Custom option processing310
7 unmodified lines
318Example file: [options-custom-processing.js](./examples/options-custom-processing.js)319320```js321function myParseInt(value, dummyPrevious) {322 // parseInt takes a string and an optional radix323 return parseInt(value);322 // parseInt takes a string and a radix323 const parsedValue = parseInt(value, 10);324 if (isNaN(parsedValue)) {325 throw new commander.InvalidOptionArgumentError('Not a number.');326 }327 return parsedValue;328}329330function increaseVerbosity(dummyValue, previous) {331 return previous + 1;
547 unmodified lines