Skip to content
Myr

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

authored by John Gee · committed by GitHub · parent 8afc0ba · Browse files · 14 files+603 added−104 removed
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

14 files+603 added−104 removed

added:examples/options-extra.js+20 added
added:tests/command.chain.test.js+132 added
1const { Command, Option } = require('../');23// Testing the functions which should chain.4// parse and parseAsync are tested in command.parse.test.js56describe('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 });1213 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 });1819 test('when set .arguments() then returns this', () => {20 const program = new Command();21 const result = program.arguments('<file>');22 expect(result).toBe(program);23 });2425 test('when call .addHelpCommand() then returns this', () => {26 const program = new Command();27 const result = program.addHelpCommand(false);28 expect(result).toBe(program);29 });3031 test('when call .exitOverride() then returns this', () => {32 const program = new Command();33 const result = program.exitOverride(() => { });34 expect(result).toBe(program);35 });3637 test('when call .action() then returns this', () => {38 const program = new Command();39 const result = program.action(() => { });40 expect(result).toBe(program);41 });4243 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 });4849 test('when call .option() then returns this', () => {50 const program = new Command();51 const result = program.option('-e');52 expect(result).toBe(program);53 });5455 test('when call .requiredOption() then returns this', () => {56 const program = new Command();57 const result = program.requiredOption('-r');58 expect(result).toBe(program);59 });6061 test('when call .combineFlagAndOptionalValue() then returns this', () => {62 const program = new Command();63 const result = program.combineFlagAndOptionalValue();64 expect(result).toBe(program);65 });6667 test('when call .allowUnknownOption() then returns this', () => {68 const program = new Command();69 const result = program.allowUnknownOption();70 expect(result).toBe(program);71 });7273 test('when call .storeOptionsAsProperties() then returns this', () => {74 const program = new Command();75 const result = program.storeOptionsAsProperties();76 expect(result).toBe(program);77 });7879 test('when call .passCommandToAction() then returns this', () => {80 const program = new Command();81 const result = program.passCommandToAction();82 expect(result).toBe(program);83 });8485 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 });9091 test('when set .description() then returns this', () => {92 const program = new Command();93 const result = program.description('description');94 expect(result).toBe(program);95 });9697 test('when set .alias() then returns this', () => {98 const program = new Command();99 const result = program.alias('alias');100 expect(result).toBe(program);101 });102103 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 });108109 test('when set .usage() then returns this', () => {110 const program = new Command();111 const result = program.usage('[options]');112 expect(result).toBe(program);113 });114115 test('when set .name() then returns this', () => {116 const program = new Command();117 const result = program.name('easy');118 expect(result).toBe(program);119 });120121 test('when call .helpOption() then returns this', () => {122 const program = new Command();123 const result = program.helpOption(false);124 expect(result).toBe(program);125 });126127 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 lines
204 }205206 expectCommanderError(caughtErr, 1, 'commander.missingMandatoryOptionValue', `error: required option '${optionFlags}' not specified`);207 });208209 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']));215216 let caughtErr;217 try {218 program.parse(['--colour', 'green'], { from: 'user' });219 } catch (err) {220 caughtErr = err;221 }222223 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
added:tests/deprecated.test.js+31 added
1const commander = require('../');23// 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.67describe('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 });1516 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 });2324 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
1const { Option } = require('../');23describe('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 });910 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 });1516 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 });2122 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 });2728 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 lines
97 expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined);98 expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');99});100101// this is the happy path, testing failure case in command.exitOverride.test.js102test('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});110111// Now some functional tests like the examples in the README!112113test('when parseFloat "1e2" then value is 100', () => {114 const program = new commander.Command();
37 unmodified lines
deleted:tests/options.regex.test.js-41 removed
1const commander = require('../');23// NB: regex support is deprecated, and deliberately not documented in README.45describe('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 });1314 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});2324describe('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 });3233 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 line
23// Do some testing of the default export(s).45test('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 lines
modified:typings/commander-tests.ts+41 added-2 removed
79 unmodified lines
80const optionThis1: commander.Command = program.option('-a,--alpha');81const optionThis2: commander.Command = program.option('-p, --peppers', 'Add peppers');82const optionThis3: commander.Command = program.option('-s, --string [value]', 'default string', 'value');83const optionThis4: commander.Command = program.option('-b, --boolean', 'default boolean', false);84program.option('--drink <size', 'drink size', /small|medium|large/);8586// example coercion functions from README8788function range(val: string): Number[] {
28 unmodified lines
117const requiredOptionThis1: commander.Command = program.requiredOption('-a,--alpha');118const requiredOptionThis2: commander.Command = program.requiredOption('-p, --peppers', 'Add peppers');119const requiredOptionThis3: commander.Command = program.requiredOption('-s, --string [value]', 'default string', 'value');120const requiredOptionThis4: commander.Command = program.requiredOption('-b, --boolean', 'default boolean', false);121program.requiredOption('--drink <size', 'drink size', /small|medium|large/);122123const requiredOptionThis5: commander.Command = program.requiredOption('-f, --float <number>', 'float argument', parseFloat);124const requiredOptionThis6: commander.Command = program.requiredOption('-f, --float <number>', 'float argument', parseFloat, 3.2);125const requiredOptionThis7: commander.Command = program.requiredOption('-i, --integer <number>', 'integer argument', myParseInt);
1 unmodified line
127const requiredOptionThis9: commander.Command = program.requiredOption('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0);128const requiredOptionThis10: commander.Command = program.requiredOption('-c, --collect <value>', 'repeatable value', collect, []);129const requiredOptionThis11: commander.Command = program.requiredOption('-l, --list <items>', 'comma separated list', commaSeparatedList);130131// addOption132const addOptionThis: commander.Command = program.addOption(new commander.Option('-s,--simple'));133134// storeOptionsAsProperties135const storeOptionsAsPropertiesThis1: commander.Command = program.storeOptionsAsProperties();136const storeOptionsAsPropertiesThis2: commander.Command = program.storeOptionsAsProperties(false);137
53 unmodified lines
191const nameValue: string = program.name();192193// outputHelp194program.outputHelp();190program.outputHelp((str: string) => { return str; }); // deprecated195program.outputHelp((str: string) => { return str; });196program.outputHelp({ error: true });197198// help199program.help();195program.help((str: string) => { return str; }); // Deprecated200program.help((str: string) => { return str; });201program.help({ error: true });202203// helpInformation204const helpInformnationValue: string = program.helpInformation();
37 unmodified lines
242const myProgram = new MyCommand();243myProgram.myFunction();244const mySub = myProgram.command('sub');245mySub.myFunction();246247// Option methods248249const baseOption = new commander.Option('-f,--foo', 'foo description');250251// default252const myOptionThis1: commander.Option = baseOption.default(3);253const myOptionThis2: commander.Option = baseOption.default(60, 'one minute');254255// fullDescription256const optionDescription: string = baseOption.fullDescription();257258// argParser259const myOptionThis3: commander.Option = baseOption.argParser((value: string) => parseInt(value));260const myOptionThis4: commander.Option = baseOption.argParser((value: string, previous: string[]) => { return previous.concat(value); });261262// makeOptionMandatory263const myOptionThis5: commander.Option = baseOption.makeOptionMandatory();264const myOptionThis6: commander.Option = baseOption.makeOptionMandatory(true);265266// hideHelp267const myOptionThis7: commander.Option = baseOption.hideHelp();268const myOptionThis8: commander.Option = baseOption.hideHelp(true);269270// argumentRejected271function goodbye(): never {272 return baseOption.argumentRejected('failed');273};274275// choices276const myOptionThis9: commander.Option = baseOption.choices(['a', 'b']);277278// name279const optionName: string = baseOption.name();
modified:typings/index.d.ts+69 added-9 removed
11 unmodified lines
12 type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;1314 interface Option {15 flags: string;16 description: string;1718 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[];3132 /**33 * Set the default value, and optionally supply the description to be displayed in the help.34 */35 default(value: any, description?: string): this;3637 /**38 * Calculate the full description, including defaultValue etc.39 */40 fullDescription(): string;4142 /**43 * Set the custom handler for processing CLI option arguments into option values.44 */45 argParser<T>(fn: (value: string, previous: T) => T): this;4647 /**48 * Whether the option is mandatory and must have a value after parsing.49 */50 makeOptionMandatory(value?: boolean): this;5152 /**53 * Hide option in help.54 */55 hideHelp(value?: boolean): this;5657 /**58 * Validation of option argument failed.59 * Intended for use from custom argument processing functions.60 */61 argumentRejected(messsage: string): never;6263 /**64 * Only allow option value to be one of choices.65 */66 choices(values: string[]): this;6768 /**69 * Return option name.70 */71 name(): string;72 }73 type OptionConstructor = new (flags: string, description?: string) => Option;7475 interface ParseOptions {
114 unmodified lines
190 /**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 lines
229 *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;236237 /**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;247248 /**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;254255 /**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 chaining
145 unmodified lines
405 * 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;411412 /**413 * Return command help documentation.414 */
11 unmodified lines
426 *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;432433 /**434 * Add additional text to be displayed with the built-in help.435 *
40 unmodified lines
modified:index.js+177 added-47 removed
12 unmodified lines
13 /**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 */2021 constructor(flags, description) {22 this.flags = flags;23 this.description = description || '';2425 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 lines
33 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 }4344 /**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 */5253 default(value, description) {54 this.defaultValue = value;55 this.defaultValueDescription = description;56 return this;57 };5859 /**60 * Calculate the full description, including defaultValue etc.61 *62 * @return {string}63 * @api public64 */6566 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 };8485 /**86 * Set the custom handler for processing CLI option arguments into option values.87 *88 * @param {Function} [fn]89 * @return {Option}90 * @api public91 */9293 argParser(fn) {94 this.parseArg = fn;95 return this;96 };9798 /**99 * Whether the option is mandatory and must have a value after parsing.100 *101 * @param {boolean} [value]102 * @return {Option}103 * @api public104 */105106 makeOptionMandatory(value) {107 this.mandatory = (value === undefined) || value;108 return this;109 };110111 /**112 * Hide option in help.113 *114 * @param {boolean} [value]115 * @return {Option}116 * @api public117 */118119 hideHelp(value) {120 this.hidden = (value === undefined) || value;121 return this;122 };123124 /**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 }134135 /**136 * Only allow option value to be one of choices.137 *138 * @param {string[]} values139 * @return {Option}140 * @api public141 */142143 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 };153154 /**155 * Return option name.156 *157 * @return {string}43 * @api private158 * @api public159 */160161 name() {162 if (this.long) {
430 unmodified lines
593 }594 };595596 /**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 */492493 _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;605606 this._checkForOptionNameClash(option);607501 // 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;609610 // 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 defined
3 unmodified lines
616 }617 // preassign only if we have a default618 if (defaultValue !== undefined) {619 this._setOptionValue(name, defaultValue);527 option.defaultValue = defaultValue;620 }621 }622623 // register the option
4 unmodified lines
628 this.on('option:' + oname, (val) => {629 const oldValue = this._getOptionValue(name);630631 // 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 lines
663 }664 });665666 return this;567 };667 }668669 /**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 lines
718 * @api public719 */720721 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 }736737 return this.addOption(option);738 };739740 /**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 value
2 unmodified lines
751 * @api public752 */753754 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 };759760 /**761 * Alter parsing of short flags with optional values.
144 unmodified lines
906 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 }915916 // Guess name, used in usage in help.
47 unmodified lines
964965 // 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 }973974 let baseDir;
637 unmodified lines
1612 return width;1613 };16141615 /**1616 * Any visible options?1617 *1618 * @return {boolean}1619 * @api private1620 */1621 _hasVisibleOptions() {1622 return this._hasHelpOption || this.options.some((option) => !option.hidden);1623 }16241625 /**1626 * Return help for options.1627 *1628 * @return {string}1629 * @api private
7 unmodified lines
1637 return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);1638 };16391640 // 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 });16451646 // Implicit help1647 const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);
83 unmodified lines
1731 const commandHelp = this.commandHelp();1732 if (commandHelp) cmds = [commandHelp];17331734 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 lines
1755 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 lines
1769 * 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 */17761777 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);17841785 const groupListeners = [];
50 unmodified lines
1836 * 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 */18431844 help(contextOptions) {
229 unmodified lines
modified:package.json+2 added-1 removed
20 unmodified lines
21 "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 lines
modified:Readme.md+28 added
14 unmodified lines
15 - [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 lines
202$ pizza-options --cheese mozzarella203add cheese type mozzarella204```205206### Extra option features207208You can add most options using the `.option()` method, but there are some additional features available209by constructing an `Option` explicitly for less common cases.210211Example file: [options-extra.js](./examples/options-extra.js)212213```js214program215 .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```219220```bash221$ extra --help222Usage: help [options]223224Options: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 command228229$ extra --drink huge230error: option '-d, --drink <size>' argument of 'huge' not in allowed choices: small, medium, large231```232233### Custom option processing234235You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the236previous value for the option. It returns the new value for the option.
576 unmodified lines