Skip to content
Myr

Add .requiredOption() for mandatory options (#1071)

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

* Add declaration of requiredOption and mandatory property * Add initial implementation for error detection for mandatory options * Add unit tests for mandatory options * Add detailed test for exitOverride intercept for missing mandatory option * Add .requiredOption to README * Reword mandatory description. * Lookup option value using attributeName, not name * Expand tests - option name different than property name - both of option/requiredOption for negated option - add exitOverride to allow Jest to catch unexpected errors * Add .requiredOption calls to TypeScript dummy program * Tweak requiredOption example file

authored by John Gee · committed by GitHub · parent 57e9d98 · Browse files · 7 files+416 added−49 removed
This commit

State

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

Diff stats

7 files+416 added−49 removed

  • tests:+243 added−0 removed
  • other:+173 added−49 removed

7 files+416 added−49 removed

added:examples/options-required.js+19 added
modified:tests/command.exitOverride.test.js+17 added
208 unmodified lines
209 .command('does-not-exist', 'fail');210211 program.parse(['node', pm, 'does-not-exist']);212 });213214 test('when mandatory program option missing then throw CommanderError', () => {215 const optionFlags = '-p, --pepper <type>';216 const program = new commander.Command();217 program218 .exitOverride()219 .requiredOption(optionFlags, 'add pepper');220221 let caughtErr;222 try {223 program.parse(['node', 'test']);224 } catch (err) {225 caughtErr = err;226 }227228 expectCommanderError(caughtErr, 1, 'commander.missingMandatoryOptionValue', `error: required option '${optionFlags}' not specified`);229 });230});
added:tests/options.mandatory.test.js+226 added
1const commander = require('../');23// Assuming mandatory options behave as normal options apart from the mandatory aspect, not retesting all behaviour.45describe('required program option with mandatory value specified', () => {6 test('when program has required value specified then value as specified', () => {7 const program = new commander.Command();8 program9 .exitOverride()10 .requiredOption('--cheese <type>', 'cheese type');11 program.parse(['node', 'test', '--cheese', 'blue']);12 expect(program.cheese).toBe('blue');13 });1415 test('when program has option with name different than property then still recognised', () => {16 const program = new commander.Command();17 program18 .exitOverride()19 .requiredOption('--cheese-type <type>', 'cheese type');20 program.parse(['node', 'test', '--cheese-type', 'blue']);21 expect(program.cheeseType).toBe('blue');22 });2324 test('when program has required value default then default value', () => {25 const program = new commander.Command();26 program27 .exitOverride()28 .requiredOption('--cheese <type>', 'cheese type', 'default');29 program.parse(['node', 'test']);30 expect(program.cheese).toBe('default');31 });3233 test('when program has optional value flag specified then true', () => {34 const program = new commander.Command();35 program36 .exitOverride()37 .requiredOption('--cheese [type]', 'cheese type');38 program.parse(['node', 'test', '--cheese']);39 expect(program.cheese).toBe(true);40 });4142 test('when program has optional value default then default value', () => {43 const program = new commander.Command();44 program45 .exitOverride()46 .requiredOption('--cheese [type]', 'cheese type', 'default');47 program.parse(['node', 'test']);48 expect(program.cheese).toBe('default');49 });5051 test('when program has value/no flag specified with value then specified value', () => {52 const program = new commander.Command();53 program54 .exitOverride()55 .requiredOption('--cheese <type>', 'cheese type')56 .requiredOption('--no-cheese', 'no cheese thanks');57 program.parse(['node', 'test', '--cheese', 'blue']);58 expect(program.cheese).toBe('blue');59 });6061 test('when program has mandatory-yes/no flag specified with flag then true', () => {62 const program = new commander.Command();63 program64 .exitOverride()65 .requiredOption('--cheese', 'cheese type')66 .option('--no-cheese', 'no cheese thanks');67 program.parse(['node', 'test', '--cheese']);68 expect(program.cheese).toBe(true);69 });7071 test('when program has mandatory-yes/mandatory-no flag specified with flag then true', () => {72 const program = new commander.Command();73 program74 .exitOverride()75 .requiredOption('--cheese', 'cheese type')76 .requiredOption('--no-cheese', 'no cheese thanks');77 program.parse(['node', 'test', '--cheese']);78 expect(program.cheese).toBe(true);79 });8081 test('when program has yes/no flag specified negated then false', () => {82 const program = new commander.Command();83 program84 .exitOverride()85 .requiredOption('--cheese <type>', 'cheese type')86 .option('--no-cheese', 'no cheese thanks');87 program.parse(['node', 'test', '--no-cheese']);88 expect(program.cheese).toBe(false);89 });9091 test('when program has required value specified and subcommand then specified value', () => {92 const program = new commander.Command();93 program94 .exitOverride()95 .requiredOption('--cheese <type>', 'cheese type')96 .command('sub')97 .action(() => {});98 program.parse(['node', 'test', '--cheese', 'blue', 'sub']);99 expect(program.cheese).toBe('blue');100 });101});102103describe('required program option with mandatory value not specified', () => {104 // Optional. Use internal knowledge to suppress output to keep test output clean.105 let consoleErrorSpy;106107 beforeAll(() => {108 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });109 });110111 afterEach(() => {112 consoleErrorSpy.mockClear();113 });114115 afterAll(() => {116 consoleErrorSpy.mockRestore();117 });118119 test('when program has required option not specified then error', () => {120 const program = new commander.Command();121 program122 .exitOverride()123 .requiredOption('--cheese <type>', 'cheese type');124125 expect(() => {126 program.parse(['node', 'test']);127 }).toThrow();128 });129130 test('when program has optional option not specified then error', () => {131 const program = new commander.Command();132 program133 .exitOverride()134 .requiredOption('--cheese [type]', 'cheese type');135136 expect(() => {137 program.parse(['node', 'test']);138 }).toThrow();139 });140141 test('when program has yes/no not specified then error', () => {142 const program = new commander.Command();143 program144 .exitOverride()145 .requiredOption('--cheese', 'cheese type')146 .option('--no-cheese', 'no cheese thanks');147148 expect(() => {149 program.parse(['node', 'test']);150 }).toThrow();151 });152153 test('when program has required value not specified and subcommand then error', () => {154 const program = new commander.Command();155 program156 .exitOverride()157 .requiredOption('--cheese <type>', 'cheese type')158 .command('sub')159 .action(() => {});160161 expect(() => {162 program.parse(['node', 'test', 'sub']);163 }).toThrow();164 });165});166167describe('required command option with mandatory value specified', () => {168 test('when command has required value specified then specified value', () => {169 const program = new commander.Command();170 let cmdOptions;171 program172 .exitOverride()173 .command('sub')174 .requiredOption('--subby <type>', 'description')175 .action((cmd) => {176 cmdOptions = cmd;177 });178179 program.parse(['node', 'test', 'sub', '--subby', 'blue']);180181 expect(cmdOptions.subby).toBe('blue');182 });183});184185describe('required command option with mandatory value not specified', () => {186 // Optional. Use internal knowledge to suppress output to keep test output clean.187 let consoleErrorSpy;188189 beforeAll(() => {190 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });191 });192193 afterEach(() => {194 consoleErrorSpy.mockClear();195 });196197 afterAll(() => {198 consoleErrorSpy.mockRestore();199 });200201 test('when command has required value not specified then eror', () => {202 const program = new commander.Command();203 program204 .exitOverride()205 .command('sub')206 .requiredOption('--subby <type>', 'description')207 .action((cmd) => {});208209 expect(() => {210 program.parse(['node', 'test', 'sub']);211 }).toThrow();212 });213214 test('when command has required value but not called then no error', () => {215 const program = new commander.Command();216 program217 .exitOverride()218 .command('sub')219 .requiredOption('--subby <type>', 'description')220 .action((cmd) => {});221222 expect(() => {223 program.parse(['node', 'test']);224 }).not.toThrow();225 });226});
modified:typings/commander-tests.ts+10 added
modified:typings/index.d.ts+12 added-2 removed
16 unmodified lines
17 }1819 class Option {20 flags: string;21 required: boolean;22 optional: boolean;21 required: boolean; // A value must be supplied when the option is specified.22 optional: boolean; // A value is optional when the option is specified.23 mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.24 bool: boolean;25 short?: string;26 long: string;27 description: string;
159 unmodified lines
187 option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;188 option(flags: string, description?: string, defaultValue?: any): Command;189190 /**191 * Define a required option, which must have a value after parsing. This usually means192 * the option must be specified on the command line. (Otherwise the same as .option().)193 *194 * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.195 */196 requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;197 requiredOption(flags: string, description?: string, defaultValue?: any): Command;198199 /**200 * Allow unknown options on the command line.201 *202 * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.203 * @returns {Command} for chaining
122 unmodified lines
modified:index.js+113 added-47 removed
41 unmodified lines
42 */4344function Option(flags, description) {45 this.flags = flags;46 this.required = flags.indexOf('<') >= 0;47 this.optional = flags.indexOf('[') >= 0;46 this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified.47 this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified.48 this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.49 this.negate = flags.indexOf('-no-') !== -1;50 flags = flags.split(/[ ,|]+/);51 if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();52 this.long = flags.shift();
312 unmodified lines
365 return this;366};367368/**368 * Define option with `flags`, `description` and optional369 * coercion `fn`.369 * Internal implementation shared by .option() and .requiredOption()370 *371 * The `flags` string should contain both the short and long flags,372 * separated by comma, a pipe or space. The following are all valid373 * all will output this way when `--help` is used.374 *375 * "-p, --pepper"376 * "-p|--pepper"377 * "-p --pepper"378 *379 * Examples:380 *381 * // simple boolean defaulting to undefined382 * program.option('-p, --pepper', 'add pepper');383 *384 * program.pepper385 * // => undefined386 *387 * --pepper388 * program.pepper389 * // => true390 *391 * // simple boolean defaulting to true (unless non-negated option is also defined)392 * program.option('-C, --no-cheese', 'remove cheese');393 *394 * program.cheese395 * // => true396 *397 * --no-cheese398 * program.cheese399 * // => false400 *401 * // required argument402 * program.option('-C, --chdir <path>', 'change the working directory');403 *404 * --chdir /tmp405 * program.chdir406 * // => "/tmp"407 *408 * // optional argument409 * program.option('-c, --cheese [type]', 'add cheese [marble]');410 *371 * @param {Object} config372 * @param {String} flags373 * @param {String} description413 * @param {Function|*} [fn] or default374 * @param {Function|*} [fn] - custom option processing function or default vaue375 * @param {*} [defaultValue]376 * @return {Command} for chaining416 * @api public377 * @api private378 */379419Command.prototype.option = function(flags, description, fn, defaultValue) {380Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) {381 var self = this,382 option = new Option(flags, description),383 oname = option.name(),384 name = option.attributeName();385 option.mandatory = !!config.mandatory;386387 // default as 3rd arg388 if (typeof fn !== 'function') {389 if (fn instanceof RegExp) {
54 unmodified lines
444 return this;445};446447/**448 * Define option with `flags`, `description` and optional449 * coercion `fn`.450 *451 * The `flags` string should contain both the short and long flags,452 * separated by comma, a pipe or space. The following are all valid453 * all will output this way when `--help` is used.454 *455 * "-p, --pepper"456 * "-p|--pepper"457 * "-p --pepper"458 *459 * Examples:460 *461 * // simple boolean defaulting to undefined462 * program.option('-p, --pepper', 'add pepper');463 *464 * program.pepper465 * // => undefined466 *467 * --pepper468 * program.pepper469 * // => true470 *471 * // simple boolean defaulting to true (unless non-negated option is also defined)472 * program.option('-C, --no-cheese', 'remove cheese');473 *474 * program.cheese475 * // => true476 *477 * --no-cheese478 * program.cheese479 * // => false480 *481 * // required argument482 * program.option('-C, --chdir <path>', 'change the working directory');483 *484 * --chdir /tmp485 * program.chdir486 * // => "/tmp"487 *488 * // optional argument489 * program.option('-c, --cheese [type]', 'add cheese [marble]');490 *491 * @param {String} flags492 * @param {String} description493 * @param {Function|*} [fn] - custom option processing function or default vaue494 * @param {*} [defaultValue]495 * @return {Command} for chaining496 * @api public497 */498499Command.prototype.option = function(flags, description, fn, defaultValue) {500 return this._optionEx({}, flags, description, fn, defaultValue);501};502503/*504 * Add a required option which must have a value after parsing. This usually means505 * the option must be specified on the command line. (Otherwise the same as .option().)506 *507 * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.508 *509 * @param {String} flags510 * @param {String} description511 * @param {Function|*} [fn] - custom option processing function or default vaue512 * @param {*} [defaultValue]513 * @return {Command} for chaining514 * @api public515 */516517Command.prototype.requiredOption = function(flags, description, fn, defaultValue) {518 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);519};520521/**522 * Allow unknown options on the command line.523 *524 * @param {Boolean} arg if `true` or omitted, no error will be thrown525 * for unknown options.
299 unmodified lines
825 }826};827828/**829 * Display an error message if a mandatory option does not have a value.830 *831 * @api private832 */833834Command.prototype._checkForMissingMandatoryOptions = function() {835 const self = this;836 this.options.forEach((anOption) => {837 if (anOption.mandatory && (self[anOption.attributeName()] === undefined)) {838 self.missingMandatoryOptionValue(anOption);839 }840 });841};842843/**844 * Parse options from `argv` returning `argv`845 * void of these options.846 *847 * @param {Array} argv
67 unmodified lines
915 // arg916 args.push(arg);917 }918919 this._checkForMissingMandatoryOptions();920921 return { args: args, unknown: unknownOptions };922};923924/**
45 unmodified lines
970 this._exit(1, 'commander.optionMissingArgument', message);971};972973/**974 * `Option` does not have a value, and is a mandatory option.975 *976 * @param {String} option977 * @api private978 */979980Command.prototype.missingMandatoryOptionValue = function(option) {981 const message = `error: required option '${option.flags}' not specified`;982 console.error(message);983 this._exit(1, 'commander.missingMandatoryOptionValue', message);984};985986/**987 * Unknown option `flag`.988 *989 * @param {String} flag990 * @api private
552 unmodified lines
modified:Readme.md+19 added
13 unmodified lines
14 - [Common option types, boolean and value](#common-option-types-boolean-and-value)15 - [Default option value](#default-option-value)16 - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)17 - [Custom option processing](#custom-option-processing)18 - [Required option](#required-option)19 - [Version option](#version-option)20 - [Commands](#commands)21 - [Specify the argument syntax](#specify-the-argument-syntax)22 - [Action handler (sub)commands](#action-handler-subcommands)
219 unmodified lines
242$ custom --list x,y,z243[ 'x', 'y', 'z' ]244```245246### Required option247248You may specify a required (mandatory) option using `.requiredOption`. The option must be specified on the command line, or by having a default value. The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.249250```js251const program = require('commander');252253program254 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');255256program.parse(process.argv);257```258259```260$ pizza261error: required option '-c, --cheese <type>' not specified262```263264### Version option265266The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.267
387 unmodified lines