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
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
Provenance
- Commit
7f9edba- Tree
4692152- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
57e9d98
7 files changed+416 added−49 removed
added:examples/options-required.js+19 added
12345678910111213141516171819#!/usr/bin/env node
// This is used as an example in the README for:// Required option// You may specify a required (mandatory) option using `.requiredOption`.// The option must be specified on the command line, or by having a default value.//// Example output pretending command called pizza (or try directly with `node options-required.js`)//// $ pizza// error: required option '-c, --cheese <type>' not specified
const commander = require('..'); // For running direct from git clone of commander repoconst program = new commander.Command();
program .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
program.parse(process.argv);modified:tests/command.exitOverride.test.js+17 added
208 unmodified lines209 .command('does-not-exist', 'fail');210 211 program.parse(['node', pm, 'does-not-exist']);212 });213+214+ 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');220+221+ let caughtErr;222+ try {223+ program.parse(['node', 'test']);224+ } catch (err) {225+ caughtErr = err;226+ }227+228+ expectCommanderError(caughtErr, 1, 'commander.missingMandatoryOptionValue', `error: required option '${optionFlags}' not specified`);229+ });230 });added:tests/options.mandatory.test.js+226 added
1+const commander = require('../');2+3+// Assuming mandatory options behave as normal options apart from the mandatory aspect, not retesting all behaviour.4+5+describe('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+ });14+15+ 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+ });23+24+ 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+ });32+33+ 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+ });41+42+ 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+ });50+51+ 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+ });60+61+ 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+ });70+71+ 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+ });80+81+ 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+ });90+91+ 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+});102+103+describe('required program option with mandatory value not specified', () => {104+ // Optional. Use internal knowledge to suppress output to keep test output clean.105+ let consoleErrorSpy;106+107+ beforeAll(() => {108+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });109+ });110+111+ afterEach(() => {112+ consoleErrorSpy.mockClear();113+ });114+115+ afterAll(() => {116+ consoleErrorSpy.mockRestore();117+ });118+119+ 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');124+125+ expect(() => {126+ program.parse(['node', 'test']);127+ }).toThrow();128+ });129+130+ 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');135+136+ expect(() => {137+ program.parse(['node', 'test']);138+ }).toThrow();139+ });140+141+ 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');147+148+ expect(() => {149+ program.parse(['node', 'test']);150+ }).toThrow();151+ });152+153+ 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(() => {});160+161+ expect(() => {162+ program.parse(['node', 'test', 'sub']);163+ }).toThrow();164+ });165+});166+167+describe('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+ });178+179+ program.parse(['node', 'test', 'sub', '--subby', 'blue']);180+181+ expect(cmdOptions.subby).toBe('blue');182+ });183+});184+185+describe('required command option with mandatory value not specified', () => {186+ // Optional. Use internal knowledge to suppress output to keep test output clean.187+ let consoleErrorSpy;188+189+ beforeAll(() => {190+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });191+ });192+193+ afterEach(() => {194+ consoleErrorSpy.mockClear();195+ });196+197+ afterAll(() => {198+ consoleErrorSpy.mockRestore();199+ });200+201+ 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) => {});208+209+ expect(() => {210+ program.parse(['node', 'test', 'sub']);211+ }).toThrow();212+ });213+214+ 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) => {});221+222+ expect(() => {223+ program.parse(['node', 'test']);224+ }).not.toThrow();225+ });226+});modified:typings/commander-tests.ts+10 added
88 unmodified lines899091929394959697989910010110210310410510627 unmodified lines88 unmodified lines console.log('unknown option is allowed'); });
program .requiredOption('-a,--aaa', 'description') .requiredOption('-b,--bbb <value>', 'description') .requiredOption('-c,--ccc [value]', 'description') .requiredOption('-d,--ddd <value>', 'description', 'default value') .requiredOption('-e,--eee <value>', 'description', (value, memo) => { return value; }) .requiredOption('-f,--fff <value>', 'description', (value, memo) => { return value; }, 'starting value') .requiredOption('-g,--ggg <value>', 'description') .requiredOption('-G,--no-ggg <value>', 'description for negation');
program .version('0.0.1') .arguments('<cmd> [env]') .action((cmd, env) => { console.log(cmd, env);27 unmodified linesmodified:typings/index.d.ts+12 added-2 removed
16 unmodified lines17 }18 19 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 lines187 option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;188 option(flags: string, description?: string, defaultValue?: any): Command;189 190 /**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;198+199+ /**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 chaining122 unmodified linesmodified:index.js+113 added-47 removed
41 unmodified lines42 */43 44 function 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 lines365 return this;366 };367 368 /**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 */379 419-Command.prototype.option = function(flags, description, fn, defaultValue) {380+Command.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;386 387 // default as 3rd arg388 if (typeof fn !== 'function') {389 if (fn instanceof RegExp) {54 unmodified lines444 return this;445 };446 447 /**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+ */498+499+Command.prototype.option = function(flags, description, fn, defaultValue) {500+ return this._optionEx({}, flags, description, fn, defaultValue);501+};502+503+/*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+ */516+517+Command.prototype.requiredOption = function(flags, description, fn, defaultValue) {518+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);519+};520+521+/**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 lines825 }826 };827 828 /**829+ * Display an error message if a mandatory option does not have a value.830+ *831+ * @api private832+ */833+834+Command.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+};842+843+/**844 * Parse options from `argv` returning `argv`845 * void of these options.846 *847 * @param {Array} argv67 unmodified lines915 // arg916 args.push(arg);917 }918 919+ this._checkForMissingMandatoryOptions();920+921 return { args: args, unknown: unknownOptions };922 };923 924 /**45 unmodified lines970 this._exit(1, 'commander.optionMissingArgument', message);971 };972 973 /**974+ * `Option` does not have a value, and is a mandatory option.975+ *976+ * @param {String} option977+ * @api private978+ */979+980+Command.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+};985+986+/**987 * Unknown option `flag`.988 *989 * @param {String} flag990 * @api private552 unmodified linesmodified:Readme.md+19 added
13 unmodified lines14 - [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 lines242 $ custom --list x,y,z243 [ 'x', 'y', 'z' ]244 ```245 246+### Required option247+248+You 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.249+250+```js251+const program = require('commander');252+253+program254+ .requiredOption('-c, --cheese <type>', 'pizza must have cheese');255+256+program.parse(process.argv);257+```258+259+```260+$ pizza261+error: required option '-c, --cheese <type>' not specified262+```263+264 ### Version option265 266 The 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