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
Provenance
- Commit
689d7a0- Tree
d128bcc- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
e1a6cf4
6 files changed+64 added−18 removed
modified:examples/options-custom-processing.js+7 added-1 removed
14 unmodified lines151617181920212223242526272628293031323334353624 unmodified lines14 unmodified lines// $ custom -c a -c b -c c// [ 'a', 'b', 'c' ]// $ custom --list x,y,z// [ 'x', 'y', 'z' ]// $ custom --integer oops// error: option '-i, --integer <number>' argument 'oops' is invalid. Not a number.
// 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 return parseInt(value, 10); const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidOptionArgumentError('Not a number.'); } return parsedValue;}
function increaseVerbosity(dummyValue, previous) { return previous + 1;24 unmodified linesmodified:tests/command.exitOverride.test.js+21 added-1 removed
216 unmodified lines217 } catch (err) {218 caughtErr = err;219 }220 221- 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 });223+224+ 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);233+234+ let caughtErr;235+ try {236+ program.parse(['--colour', 'green'], { from: 'user' });237+ } catch (err) {238+ caughtErr = err;239+ }240+241+ 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 lines29 const commandInstance1 = new commander.Command();30 const commandInstance2 = new commander.Command('name');31 const optionsInstance = new commander.Option('-f');32 const errorInstance = new commander.CommanderError(1, 'code', 'message');33+const invalidOptionErrorInstance = new commander.InvalidOptionArgumentError('message');34 35 // Command properties36 console.log(programWithOptions.someOption);37 // eslint-disable-next-line @typescript-eslint/dot-notation305 unmodified linesmodified:typings/index.d.ts+5 added
12 unmodified lines13 nestedError?: string;14 }15 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;16 17+ interface InvalidOptionArgumentError extends CommanderError {18+ }19+ type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;20+21 interface Option {22 flags: string;23 description: string;24 555 unmodified lines580 program: Command;581 Command: CommandConstructor;582 Option: OptionConstructor;583 CommanderError: CommanderErrorConstructor;584+ InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;585 Help: HelpConstructor;586 }587 588 }5 unmodified linesmodified:index.js+23 added-13 removed
424 unmodified lines425 return this;426 };427 428 /**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- }437-438- /**429 * Only allow option value to be one of choices.430 *431 * @param {string[]} values432 * @return {Option}2 unmodified lines435 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 lines503 this.nestedError = undefined;504 }505 }506 507+/**508+ * InvalidOptionArgumentError class509+ * @class510+ */511+class 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+}524+525 class Command extends EventEmitter {526 /**527 * Initialize a new `Command`.528 *483 unmodified lines1012 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 lines2051 2052 exports.Command = Command;2053 exports.Option = Option;2054 exports.CommanderError = CommanderError;2055+exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2056 exports.Help = Help;2057 2058 /**2059 * Camel-case the given `flag`113 unmodified linesmodified:Readme.md+7 added-3 removed
301 unmodified lines302 -d, --drink <size> drink cup size (choices: "small", "medium", "large")303 -h, --help display help for command304 305 $ extra --drink huge306-error: option '-d, --drink <size>' argument of 'huge' not in allowed choices: small, medium, large306+error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.307 ```308 309 ### Custom option processing310 7 unmodified lines318 Example file: [options-custom-processing.js](./examples/options-custom-processing.js)319 320 ```js321 function 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 }329 330 function increaseVerbosity(dummyValue, previous) {331 return previous + 1;547 unmodified lines