Enhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add .addOption and use as bottleneck. Make all Option properties private. * Desription for object is optional * Add support for hidden options * Try setFoo for booleans so less ambiguous what no parameter means * Renamed method * Restore Option property names to reduce churn * Try more fluent names for non-property methods * Avoid renaming existing members of Option * Add default description for help * Fix return JSDoc * First cut at choices * Throw CommanderError for easier detection * Add catch for tidy coercion failure handing * Add tests for Option.choices * Rename custom option processing property * Add run script for TypeScript checkJS * Add tests for chaining routines * More consistent name for custom option arg processing * Add choices to help * .default() now expects parameter * Fixed return type * Separate out argumentRejected for possible reuse * Add back support for RegExp which accidentally dropped. * Add test for obsolete regexp * Add TypeScript definitions for new Option properties * Switch from obsolete to deprecated, clearer meaning * Fix left-over edit * Add comment * Simplify the comments * Add README and example file * Remove example covered elsewhere * Restore example, leave change for a separate PR * Fix example output to match changed code * Add language to code blocks * Rename getFullDescription, not using get much * Add chaining test for addHelpText * Describe as legacy rather than deprecated in comments, add @deprecated for editor feedback to discourage use * Do not have to have both should and long flags these days * Eliminate duplicate code using internal knowledge * Rename parseArgWith to argParser * Improve JSDoc for help * Make code and declarations consistent to pass tsc checks * Match up write signature to fix linting error * Restore "deprecated", it is the right word
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+603 added−104 removed
- tests:+266 added−45 removed
- other:+337 added−59 removed
Provenance
- Commit
a05a8bc- Tree
de9bdae- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
8afc0ba
14 files changed+603 added−104 removed
added:examples/options-extra.js+20 added
1234567891011121314151617181920#!/usr/bin/env node
// This is used as an example in the README for extra option features.
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
program .addOption(new commander.Option('-s, --secret').hideHelp()) .addOption(new commander.Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')) .addOption(new commander.Option('-d, --drink <size>', 'drink cup size').choices(['small', 'medium', 'large']));
program.parse();
console.log('Options: ', program.opts());
// Try the following:// node options-extra.js --help// node options-extra.js --drink hugeadded:tests/command.chain.test.js+132 added
1+const { Command, Option } = require('../');2+3+// Testing the functions which should chain.4+// parse and parseAsync are tested in command.parse.test.js5+6+describe('Command methods that should return this for chaining', () => {7+ test('when call .command() with description for stand-alone executable then returns this', () => {8+ const program = new Command();9+ const result = program.command('foo', 'foo description');10+ expect(result).toBe(program);11+ });12+13+ test('when call .addCommand() then returns this', () => {14+ const program = new Command();15+ const result = program.addCommand(new Command('name'));16+ expect(result).toBe(program);17+ });18+19+ test('when set .arguments() then returns this', () => {20+ const program = new Command();21+ const result = program.arguments('<file>');22+ expect(result).toBe(program);23+ });24+25+ test('when call .addHelpCommand() then returns this', () => {26+ const program = new Command();27+ const result = program.addHelpCommand(false);28+ expect(result).toBe(program);29+ });30+31+ test('when call .exitOverride() then returns this', () => {32+ const program = new Command();33+ const result = program.exitOverride(() => { });34+ expect(result).toBe(program);35+ });36+37+ test('when call .action() then returns this', () => {38+ const program = new Command();39+ const result = program.action(() => { });40+ expect(result).toBe(program);41+ });42+43+ test('when call .addOption() then returns this', () => {44+ const program = new Command();45+ const result = program.addOption(new Option('-e'));46+ expect(result).toBe(program);47+ });48+49+ test('when call .option() then returns this', () => {50+ const program = new Command();51+ const result = program.option('-e');52+ expect(result).toBe(program);53+ });54+55+ test('when call .requiredOption() then returns this', () => {56+ const program = new Command();57+ const result = program.requiredOption('-r');58+ expect(result).toBe(program);59+ });60+61+ test('when call .combineFlagAndOptionalValue() then returns this', () => {62+ const program = new Command();63+ const result = program.combineFlagAndOptionalValue();64+ expect(result).toBe(program);65+ });66+67+ test('when call .allowUnknownOption() then returns this', () => {68+ const program = new Command();69+ const result = program.allowUnknownOption();70+ expect(result).toBe(program);71+ });72+73+ test('when call .storeOptionsAsProperties() then returns this', () => {74+ const program = new Command();75+ const result = program.storeOptionsAsProperties();76+ expect(result).toBe(program);77+ });78+79+ test('when call .passCommandToAction() then returns this', () => {80+ const program = new Command();81+ const result = program.passCommandToAction();82+ expect(result).toBe(program);83+ });84+85+ test('when call .version() then returns this', () => {86+ const program = new Command();87+ const result = program.version('1.2.3');88+ expect(result).toBe(program);89+ });90+91+ test('when set .description() then returns this', () => {92+ const program = new Command();93+ const result = program.description('description');94+ expect(result).toBe(program);95+ });96+97+ test('when set .alias() then returns this', () => {98+ const program = new Command();99+ const result = program.alias('alias');100+ expect(result).toBe(program);101+ });102+103+ test('when set .aliases() then returns this', () => {104+ const program = new Command();105+ const result = program.aliases(['foo', 'bar']);106+ expect(result).toBe(program);107+ });108+109+ test('when set .usage() then returns this', () => {110+ const program = new Command();111+ const result = program.usage('[options]');112+ expect(result).toBe(program);113+ });114+115+ test('when set .name() then returns this', () => {116+ const program = new Command();117+ const result = program.name('easy');118+ expect(result).toBe(program);119+ });120+121+ test('when call .helpOption() then returns this', () => {122+ const program = new Command();123+ const result = program.helpOption(false);124+ expect(result).toBe(program);125+ });126+127+ test('when call .addHelpText() then returns this', () => {128+ const program = new Command();129+ const result = program.addHelpText('before', 'example');130+ expect(result).toBe(program);131+ });132+});modified:tests/command.exitOverride.test.js+17 added
203 unmodified lines204 }205 206 expectCommanderError(caughtErr, 1, 'commander.missingMandatoryOptionValue', `error: required option '${optionFlags}' not specified`);207 });208+209+ test('when option argument not in choices then throw CommanderError', () => {210+ const optionFlags = '--colour <shade>';211+ const program = new commander.Command();212+ program213+ .exitOverride()214+ .addOption(new commander.Option(optionFlags).choices(['red', 'blue']));215+216+ let caughtErr;217+ try {218+ program.parse(['--colour', 'green'], { from: 'user' });219+ } catch (err) {220+ caughtErr = err;221+ }222+223+ expectCommanderError(caughtErr, 1, 'commander.optionArgumentRejected', `error: option '${optionFlags}' argument of 'green' not in allowed choices: red, blue`);224+ });225 });modified:tests/command.help.test.js+42 added-3 removed
86 unmodified lines878889909192919293949557 unmodified lines15315415515615815715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320486 unmodified lines expect(writeSpy).toHaveBeenCalledWith(helpReplacement); writeSpy.mockClear();});
// noHelp is now named hidden, not officially deprecated yettest('when command sets noHelp then not displayed in helpInformation', () => {test('when command sets deprecated noHelp then not displayed in helpInformation', () => { const program = new commander.Command(); program .command('secret', 'secret description', { noHelp: true }); const helpInformation = program.helpInformation();57 unmodified lines expect(writeSpy).toHaveBeenCalledWith(program.helpInformation()); writeSpy.mockClear();});
test('when no options then Options not includes in helpInformation', () => {test('when no options then Options not included in helpInformation', () => { const program = new commander.Command(); // No custom options, no version option, no help option program .helpOption(false); const helpInformation = program.helpInformation(); expect(helpInformation).not.toMatch('Options');});
test('when option hidden then option not included in helpInformation', () => { const program = new commander.Command(); program .addOption(new commander.Option('-s,--secret', 'secret option').hideHelp()); const helpInformation = program.helpInformation(); expect(helpInformation).not.toMatch('secret');});
test('when option has default value then default included in helpInformation', () => { const program = new commander.Command(); program .option('-p, --port <portNumber>', 'port number', 80); const helpInformation = program.helpInformation(); expect(helpInformation).toMatch('(default: 80)');});
test('when option has default value description then default description included in helpInformation', () => { const program = new commander.Command(); program .addOption(new commander.Option('-a, --address <dotted>', 'ip address').default('127.0.0.1', 'home')); const helpInformation = program.helpInformation(); expect(helpInformation).toMatch('(default: home)');});
test('when option has choices then choices included in helpInformation', () => { const program = new commander.Command(); program .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue'])); const helpInformation = program.helpInformation(); expect(helpInformation).toMatch('(choices: "red", "blue")');});
test('when option has choices and default then both included in helpInformation', () => { const program = new commander.Command(); program .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue']).default('red')); const helpInformation = program.helpInformation(); expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');});added:tests/deprecated.test.js+31 added
1+const commander = require('../');2+3+// Test for backwards compatible behaviour of deprecated features that don't fit in elsewhere.4+// We keep deprecated features working (when not too difficult) to avoid breaking existing code5+// and reduce barriers to updating to latest version of Commander.6+7+describe('option with regular expression instead of custom processing function', () => {8+ test('when option not given then value is default', () => {9+ const program = new commander.Command();10+ program11+ .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');12+ program.parse([], { from: 'user' });13+ expect(program.cheese).toEqual('mild');14+ });15+16+ test('when argument matches regexp then value is as specified', () => {17+ const program = new commander.Command();18+ program19+ .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');20+ program.parse(['--cheese', 'tasty'], { from: 'user' });21+ expect(program.cheese).toEqual('tasty');22+ });23+24+ test('when argument does mot matches regexp then value is default', () => {25+ const program = new commander.Command();26+ program27+ .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');28+ program.parse(['--cheese', 'other'], { from: 'user' });29+ expect(program.cheese).toEqual('mild');30+ });31+});added:tests/option.chain.test.js+33 added
1+const { Option } = require('../');2+3+describe('Option methods that should return this for chaining', () => {4+ test('when call .default() then returns this', () => {5+ const option = new Option('-e,--example <value>');6+ const result = option.default(3);7+ expect(result).toBe(option);8+ });9+10+ test('when call .argParser() then returns this', () => {11+ const option = new Option('-e,--example <value>');12+ const result = option.argParser(() => { });13+ expect(result).toBe(option);14+ });15+16+ test('when call .makeOptionMandatory() then returns this', () => {17+ const option = new Option('-e,--example <value>');18+ const result = option.makeOptionMandatory();19+ expect(result).toBe(option);20+ });21+22+ test('when call .hideHelp() then returns this', () => {23+ const option = new Option('-e,--example <value>');24+ const result = option.hideHelp();25+ expect(result).toBe(option);26+ });27+28+ test('when call .choices() then returns this', () => {29+ const option = new Option('-e,--example <value>');30+ const result = option.choices(['a']);31+ expect(result).toBe(option);32+ });33+});modified:tests/options.custom-processing.test.js+10 added
96 unmodified lines97 expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined);98 expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');99 });100 101+// this is the happy path, testing failure case in command.exitOverride.test.js102+test('when option argument in choices then option set', () => {103+ const program = new commander.Command();104+ program105+ .exitOverride()106+ .addOption(new commander.Option('--colour <shade>').choices(['red', 'blue']));107+ program.parse(['--colour', 'red'], { from: 'user' });108+ expect(program.colour).toBe('red');109+});110+111 // Now some functional tests like the examples in the README!112 113 test('when parseFloat "1e2" then value is 100', () => {114 const program = new commander.Command();37 unmodified linesdeleted:tests/options.regex.test.js-41 removed
1-const commander = require('../');2-3-// NB: regex support is deprecated, and deliberately not documented in README.4-5-describe('option with optional value and regex', () => {6- test('when option regex fails then value is true [sic]', () => {7- const program = new commander.Command();8- program9- .option('-d, --drink [drink]', 'Drink', /^(Water|Wine)$/i);10- program.parse(['node', 'test', '--drink', 'does-not-match']);11- expect(program.drink).toBe(true);12- });13-14- test('when option regex matches then value is as specified', () => {15- const drinkValue = 'water';16- const program = new commander.Command();17- program18- .option('-d, --drink [drink]', 'Drink', /^(Water|Wine)$/i);19- program.parse(['node', 'test', '--drink', drinkValue]);20- expect(program.drink).toBe(drinkValue);21- });22-});23-24-describe('option with required value and regex', () => {25- test('when option regex fails then value is true [sic]', () => {26- const program = new commander.Command();27- program28- .option('-d, --drink <drink>', 'Drink', /^(Water|Wine)$/i);29- program.parse(['node', 'test', '--drink', 'does-not-match']);30- expect(program.drink).toBe(true);31- });32-33- test('when option regex matches then value is as specified', () => {34- const drinkValue = 'water';35- const program = new commander.Command();36- program37- .option('-d, --drink [drink]', 'Drink', /^(Water|Wine)$/i);38- program.parse(['node', 'test', '--drink', drinkValue]);39- expect(program.drink).toBe(drinkValue);40- });41-});modified:tests/program.test.js+1 added-1 removed
1 unmodified line2 3 // Do some testing of the default export(s).4 5 test('when require commander then is a Command (default export of global)', () => {6- // Legacy global command6+ // Deprecated global command7 const program = commander;8 expect(program.constructor.name).toBe('Command');9 });10 10 unmodified linesmodified:typings/commander-tests.ts+41 added-2 removed
79 unmodified lines80 const optionThis1: commander.Command = program.option('-a,--alpha');81 const optionThis2: commander.Command = program.option('-p, --peppers', 'Add peppers');82 const optionThis3: commander.Command = program.option('-s, --string [value]', 'default string', 'value');83 const optionThis4: commander.Command = program.option('-b, --boolean', 'default boolean', false);84+program.option('--drink <size', 'drink size', /small|medium|large/);85 86 // example coercion functions from README87 88 function range(val: string): Number[] {28 unmodified lines117 const requiredOptionThis1: commander.Command = program.requiredOption('-a,--alpha');118 const requiredOptionThis2: commander.Command = program.requiredOption('-p, --peppers', 'Add peppers');119 const requiredOptionThis3: commander.Command = program.requiredOption('-s, --string [value]', 'default string', 'value');120 const requiredOptionThis4: commander.Command = program.requiredOption('-b, --boolean', 'default boolean', false);121+program.requiredOption('--drink <size', 'drink size', /small|medium|large/);122 123 const requiredOptionThis5: commander.Command = program.requiredOption('-f, --float <number>', 'float argument', parseFloat);124 const requiredOptionThis6: commander.Command = program.requiredOption('-f, --float <number>', 'float argument', parseFloat, 3.2);125 const requiredOptionThis7: commander.Command = program.requiredOption('-i, --integer <number>', 'integer argument', myParseInt);1 unmodified line127 const requiredOptionThis9: commander.Command = program.requiredOption('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0);128 const requiredOptionThis10: commander.Command = program.requiredOption('-c, --collect <value>', 'repeatable value', collect, []);129 const requiredOptionThis11: commander.Command = program.requiredOption('-l, --list <items>', 'comma separated list', commaSeparatedList);130 131+// addOption132+const addOptionThis: commander.Command = program.addOption(new commander.Option('-s,--simple'));133+134 // storeOptionsAsProperties135 const storeOptionsAsPropertiesThis1: commander.Command = program.storeOptionsAsProperties();136 const storeOptionsAsPropertiesThis2: commander.Command = program.storeOptionsAsProperties(false);137 53 unmodified lines191 const nameValue: string = program.name();192 193 // outputHelp194 program.outputHelp();190-program.outputHelp((str: string) => { return str; }); // deprecated195+program.outputHelp((str: string) => { return str; });196 program.outputHelp({ error: true });197 198 // help199 program.help();195-program.help((str: string) => { return str; }); // Deprecated200+program.help((str: string) => { return str; });201 program.help({ error: true });202 203 // helpInformation204 const helpInformnationValue: string = program.helpInformation();37 unmodified lines242 const myProgram = new MyCommand();243 myProgram.myFunction();244 const mySub = myProgram.command('sub');245 mySub.myFunction();246+247+// Option methods248+249+const baseOption = new commander.Option('-f,--foo', 'foo description');250+251+// default252+const myOptionThis1: commander.Option = baseOption.default(3);253+const myOptionThis2: commander.Option = baseOption.default(60, 'one minute');254+255+// fullDescription256+const optionDescription: string = baseOption.fullDescription();257+258+// argParser259+const myOptionThis3: commander.Option = baseOption.argParser((value: string) => parseInt(value));260+const myOptionThis4: commander.Option = baseOption.argParser((value: string, previous: string[]) => { return previous.concat(value); });261+262+// makeOptionMandatory263+const myOptionThis5: commander.Option = baseOption.makeOptionMandatory();264+const myOptionThis6: commander.Option = baseOption.makeOptionMandatory(true);265+266+// hideHelp267+const myOptionThis7: commander.Option = baseOption.hideHelp();268+const myOptionThis8: commander.Option = baseOption.hideHelp(true);269+270+// argumentRejected271+function goodbye(): never {272+ return baseOption.argumentRejected('failed');273+};274+275+// choices276+const myOptionThis9: commander.Option = baseOption.choices(['a', 'b']);277+278+// name279+const optionName: string = baseOption.name();modified:typings/index.d.ts+69 added-9 removed
11 unmodified lines12 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;13 14 interface Option {15 flags: string;16+ description: string;17+18 required: boolean; // A value must be supplied when the option is specified.19 optional: boolean; // A value is optional when the option is specified.20+ variadic: boolean;21 mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.19- bool: boolean;22+ optionFlags: string;23 short?: string;21- long: string;22- description: string;24+ long?: string;25+ negate: boolean;26+ defaultValue?: any;27+ defaultValueDescription?: string;28+ parseArg?: <T>(value: string, previous: T) => T;29+ hidden: boolean;30+ argChoices?: string[];31+32+ /**33+ * Set the default value, and optionally supply the description to be displayed in the help.34+ */35+ default(value: any, description?: string): this;36+37+ /**38+ * Calculate the full description, including defaultValue etc.39+ */40+ fullDescription(): string;41+42+ /**43+ * Set the custom handler for processing CLI option arguments into option values.44+ */45+ argParser<T>(fn: (value: string, previous: T) => T): this;46+47+ /**48+ * Whether the option is mandatory and must have a value after parsing.49+ */50+ makeOptionMandatory(value?: boolean): this;51+52+ /**53+ * Hide option in help.54+ */55+ hideHelp(value?: boolean): this;56+57+ /**58+ * Validation of option argument failed.59+ * Intended for use from custom argument processing functions.60+ */61+ argumentRejected(messsage: string): never;62+63+ /**64+ * Only allow option value to be one of choices.65+ */66+ choices(values: string[]): this;67+68+ /**69+ * Return option name.70+ */71+ name(): string;72 }73 type OptionConstructor = new (flags: string, description?: string) => Option;74 75 interface ParseOptions {114 unmodified lines190 /**191 * Define option with `flags`, `description` and optional192 * coercion `fn`.193 *145- * The `flags` string should contain both the short and long flags,194+ * The `flags` string contains the short and/or long flags,195 * separated by comma, a pipe or space. The following are all valid196 * all will output this way when `--help` is used.197 *198 * "-p, --pepper"30 unmodified lines229 *230 * @returns `this` command for chaining231 */232 option(flags: string, description?: string, defaultValue?: string | boolean): this;184- option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;233 option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;234+ /** @deprecated since v7, instead use choices or a custom function */235+ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;236 237 /**238 * Define a required option, which must have a value after parsing. This usually means239 * the option must be specified on the command line. (Otherwise the same as .option().)240 *191- * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.241+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.242 */243 requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;194- requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;244 requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;245+ /** @deprecated since v7, instead use choices or a custom function */246+ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;247 248 /**249+ * Add a prepared Option.250+ *251+ * See .option() and .requiredOption() for creating and attaching an option in a single call.252+ */253+ addOption(option: Option): this;254+255+ /**256 * Whether to store option values as properties on command object,257 * or store separately (specify false). In both cases the option values can be accessed using .opts().258 *259 * @returns `this` command for chaining145 unmodified lines405 * Outputs built-in help, and custom text added using `.addHelpText()`.406 *407 */408 outputHelp(context?: HelpContext): void;409+ /** @deprecated since v7 */351- outputHelp(cb?: (str: string) => string): void; // callback deprecated410+ outputHelp(cb?: (str: string) => string): void;411 412 /**413 * Return command help documentation.414 */11 unmodified lines426 *427 * Outputs built-in help, and custom text added using `.addHelpText()`.428 */429 help(context?: HelpContext): never;430+ /** @deprecated since v7 */371- help(cb?: (str: string) => string): never; // callback deprecated431+ help(cb?: (str: string) => string): never;432 433 /**434 * Add additional text to be displayed with the built-in help.435 *40 unmodified linesmodified:index.js+177 added-47 removed
12 unmodified lines13 /**14 * Initialize a new `Option` with the given `flags` and `description`.15 *16 * @param {string} flags17- * @param {string} description17+ * @param {string} [description]18 * @api public19 */20 21 constructor(flags, description) {22 this.flags = flags;23+ this.description = description || '';24+25 this.required = flags.includes('<'); // A value must be supplied when the option is specified.26 this.optional = flags.includes('['); // A value is optional when the option is specified.27 // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument28 this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.4 unmodified lines33 this.negate = false;34 if (this.long) {35 this.negate = this.long.startsWith('--no-');36 }35- this.description = description || '';37 this.defaultValue = undefined;38+ this.defaultValueDescription = undefined;39+ this.parseArg = undefined;40+ this.hidden = false;41+ this.argChoices = undefined;42 }43 44 /**45+ * Set the default value, and optionally supply the description to be displayed in the help.46+ *47+ * @param {any} value48+ * @param {string} [description]49+ * @return {Option}50+ * @api public51+ */52+53+ default(value, description) {54+ this.defaultValue = value;55+ this.defaultValueDescription = description;56+ return this;57+ };58+59+ /**60+ * Calculate the full description, including defaultValue etc.61+ *62+ * @return {string}63+ * @api public64+ */65+66+ fullDescription() {67+ if (this.negate) {68+ return this.description;69+ }70+ const extraInfo = [];71+ if (this.argChoices) {72+ extraInfo.push(73+ // use stringify to match the display of the default value74+ `choices: ${this.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);75+ }76+ if (this.defaultValue !== undefined) {77+ extraInfo.push(`default: ${this.defaultValueDescription || JSON.stringify(this.defaultValue)}`);78+ }79+ if (extraInfo.length > 0) {80+ return `${this.description} (${extraInfo.join(', ')})`;81+ }82+ return this.description;83+ };84+85+ /**86+ * Set the custom handler for processing CLI option arguments into option values.87+ *88+ * @param {Function} [fn]89+ * @return {Option}90+ * @api public91+ */92+93+ argParser(fn) {94+ this.parseArg = fn;95+ return this;96+ };97+98+ /**99+ * Whether the option is mandatory and must have a value after parsing.100+ *101+ * @param {boolean} [value]102+ * @return {Option}103+ * @api public104+ */105+106+ makeOptionMandatory(value) {107+ this.mandatory = (value === undefined) || value;108+ return this;109+ };110+111+ /**112+ * Hide option in help.113+ *114+ * @param {boolean} [value]115+ * @return {Option}116+ * @api public117+ */118+119+ hideHelp(value) {120+ this.hidden = (value === undefined) || value;121+ return this;122+ };123+124+ /**125+ * Validation of option argument failed.126+ * Intended for use from custom argument processing functions.127+ *128+ * @param {string} message129+ * @api public130+ */131+ argumentRejected(message) {132+ throw new CommanderError(1, 'commander.optionArgumentRejected', message);133+ }134+135+ /**136+ * Only allow option value to be one of choices.137+ *138+ * @param {string[]} values139+ * @return {Option}140+ * @api public141+ */142+143+ choices(values) {144+ this.argChoices = values;145+ this.parseArg = (arg) => {146+ if (!values.includes(arg)) {147+ this.argumentRejected(`error: option '${this.flags}' argument of '${arg}' not in allowed choices: ${values.join(', ')}`);148+ }149+ return arg;150+ };151+ return this;152+ };153+154+ /**155 * Return option name.156 *157 * @return {string}43- * @api private158+ * @api public159 */160 161 name() {162 if (this.long) {430 unmodified lines593 }594 };595 596 /**482- * Internal implementation shared by .option() and .requiredOption()597+ * Add an option.598 *484- * @param {Object} config485- * @param {string} flags486- * @param {string} description487- * @param {Function|*} [fn] - custom option processing function or default value488- * @param {*} [defaultValue]599+ * @param {Option} option600 * @return {Command} `this` command for chaining490- * @api private601 */492-493- _optionEx(config, flags, description, fn, defaultValue) {494- const option = new Option(flags, description);602+ addOption(option) {603 const oname = option.name();604 const name = option.attributeName();497- option.mandatory = !!config.mandatory;605 606 this._checkForOptionNameClash(option);607 501- // default as 3rd arg502- if (typeof fn !== 'function') {503- if (fn instanceof RegExp) {504- // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.505- // No longer documented in README, but still present for backwards compatibility.506- const regex = fn;507- fn = (val, def) => {508- const m = regex.exec(val);509- return m ? m[0] : def;510- };511- } else {512- defaultValue = fn;513- fn = null;514- }515- }608+ let defaultValue = option.defaultValue;609 610 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value611 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {612 // when --no-foo we make sure default is true, unless a --foo option is already defined3 unmodified lines616 }617 // preassign only if we have a default618 if (defaultValue !== undefined) {619 this._setOptionValue(name, defaultValue);527- option.defaultValue = defaultValue;620 }621 }622 623 // register the option4 unmodified lines628 this.on('option:' + oname, (val) => {629 const oldValue = this._getOptionValue(name);630 631 // custom processing540- if (val !== null && fn) {541- val = fn(val, oldValue === undefined ? defaultValue : oldValue);632+ if (val !== null && option.parseArg) {633+ try {634+ val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);635+ } catch (err) {636+ if (err.code === 'commander.optionArgumentRejected') {637+ console.error(err.message);638+ this._exit(err.exitCode, err.code, err.message);639+ }640+ throw err;641+ }642 } else if (val !== null && option.variadic) {643 if (oldValue === defaultValue || !Array.isArray(oldValue)) {644 val = [val];645 } else {17 unmodified lines663 }664 });665 666 return this;567- };667+ }668 669 /**670 * Define option with `flags`, `description` and optional671 * coercion `fn`.672 *573- * The `flags` string should contain both the short and long flags,673+ * The `flags` string contains the short and/or long flags,674 * separated by comma, a pipe or space. The following are all valid675 * all will output this way when `--help` is used.676 *677 * "-p, --pepper"40 unmodified lines718 * @api public719 */720 721 option(flags, description, fn, defaultValue) {622- return this._optionEx({}, flags, description, fn, defaultValue);722+ const option = new Option(flags, description);723+ if (typeof fn === 'function') {724+ option.default(defaultValue).argParser(fn);725+ } else if (fn instanceof RegExp) {726+ // deprecated727+ const regex = fn;728+ fn = (val, def) => {729+ const m = regex.exec(val);730+ return m ? m[0] : def;731+ };732+ option.default(defaultValue).argParser(fn);733+ } else {734+ option.default(fn);735+ }736+737+ return this.addOption(option);738 };739 740 /**741 * Add a required option which must have a value after parsing. This usually means742 * the option must be specified on the command line. (Otherwise the same as .option().)743 *629- * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.744+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.745 *746 * @param {string} flags747 * @param {string} description748 * @param {Function|*} [fn] - custom option processing function or default value2 unmodified lines751 * @api public752 */753 754 requiredOption(flags, description, fn, defaultValue) {640- return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);755+ this.option(flags, description, fn, defaultValue);756+ this.options[this.options.length - 1].makeOptionMandatory();757+ return this;758 };759 760 /**761 * Alter parsing of short flags with optional values.144 unmodified lines906 break;907 default:908 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);909 }910+ // @ts-ignore911 if (!this._scriptPath && process.mainModule) {912+ // @ts-ignore913 this._scriptPath = process.mainModule.filename;914 }915 916 // Guess name, used in usage in help.47 unmodified lines964 965 // Want the entry script as the reference for command name and directory for searching for other files.966 let scriptPath = this._scriptPath;967 // Fallback in case not set, due to how Command created or called.968+ // @ts-ignore969 if (!scriptPath && process.mainModule) {970+ // @ts-ignore971 scriptPath = process.mainModule.filename;972 }973 974 let baseDir;637 unmodified lines1612 return width;1613 };1614 1615 /**1616+ * Any visible options?1617+ *1618+ * @return {boolean}1619+ * @api private1620+ */1621+ _hasVisibleOptions() {1622+ return this._hasHelpOption || this.options.some((option) => !option.hidden);1623+ }1624+1625+ /**1626 * Return help for options.1627 *1628 * @return {string}1629 * @api private7 unmodified lines1637 return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);1638 };1639 1640 // Explicit options (including version)1510- const help = this.options.map((option) => {1511- const fullDesc = option.description +1512- ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');1513- return padOptionDetails(option.flags, fullDesc);1641+ const visibleOptions = this.options.filter((option) => !option.hidden);1642+ const help = visibleOptions.map((option) => {1643+ return padOptionDetails(option.flags, option.fullDescription());1644 });1645 1646 // Implicit help1647 const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);83 unmodified lines1731 const commandHelp = this.commandHelp();1732 if (commandHelp) cmds = [commandHelp];1733 1734 let options = [];1605- if (this._hasHelpOption || this.options.length > 0) {1735+ if (this._hasVisibleOptions()) {1736 options = [1737 'Options:',1738 '' + this.optionHelp().replace(/^/gm, ' '),1739 ''15 unmodified lines1755 contextOptions = contextOptions || {};1756 const context = { error: !!contextOptions.error };1757 let write;1758 if (context.error) {1629- write = (...args) => process.stderr.write(...args);1759+ write = (arg, ...args) => process.stderr.write(arg, ...args);1760 } else {1631- write = (...args) => process.stdout.write(...args);1761+ write = (arg, ...args) => process.stdout.write(arg, ...args);1762 }1763 context.write = contextOptions.write || write;1764 context.command = this;1765 return context;3 unmodified lines1769 * Output help information for this command.1770 *1771 * Outputs built-in help, and custom text added using `.addHelpText()`.1772 *1773+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1774 * @api public1644- * @param {Object} [contextOptions] - Can optionally pass in `{ error: true }` to write to stderr1775 */1776 1777 outputHelp(contextOptions) {1778 let deprecatedCallback;1779 if (typeof contextOptions === 'function') {1780 deprecatedCallback = contextOptions;1651- contextOptions = {};1781+ contextOptions = undefined;1782 }1783 const context = this._getHelpContext(contextOptions);1784 1785 const groupListeners = [];50 unmodified lines1836 * Output help information and exit.1837 *1838 * Outputs built-in help, and custom text added using `.addHelpText()`.1839 *1710- * @param {Object} [contextOptions] - optionally pass in `{ error: true }` to write to stderr1840+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1841 * @api public1842 */1843 1844 help(contextOptions) {229 unmodified linesmodified:package.json+2 added-1 removed
20 unmodified lines21 "scripts": {22 "lint": "eslint index.js \"tests/**/*.js\"",23 "typescript-lint": "eslint typings/*.ts",24 "test": "jest && npm run test-typings",25- "test-typings": "tsc -p tsconfig.json"25+ "test-typings": "tsc -p tsconfig.json",26+ "typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit"27 },28 "main": "index",29 "files": [30 "index.js",19 unmodified linesmodified:Readme.md+28 added
14 unmodified lines15 - [Options](#options)16 - [Common option types, boolean and value](#common-option-types-boolean-and-value)17 - [Default option value](#default-option-value)18 - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)19+ - [Extra option features](#extra-option-features)20 - [Custom option processing](#custom-option-processing)21 - [Required option](#required-option)22 - [Variadic option](#variadic-option)23 - [Version option](#version-option)178 unmodified lines202 $ pizza-options --cheese mozzarella203 add cheese type mozzarella204 ```205 206+### Extra option features207+208+You can add most options using the `.option()` method, but there are some additional features available209+by constructing an `Option` explicitly for less common cases.210+211+Example file: [options-extra.js](./examples/options-extra.js)212+213+```js214+program215+ .addOption(new Option('-s, --secret').hideHelp())216+ .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))217+ .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']));218+```219+220+```bash221+$ extra --help222+Usage: help [options]223+224+Options:225+ -t, --timeout <delay> timeout in seconds (default: one minute)226+ -d, --drink <size> drink cup size (choices: "small", "medium", "large")227+ -h, --help display help for command228+229+$ extra --drink huge230+error: option '-d, --drink <size>' argument of 'huge' not in allowed choices: small, medium, large231+```232+233 ### Custom option processing234 235 You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the236 previous value for the option. It returns the new value for the option.576 unmodified lines