Skip to content
Myr

Add Option.implies() (#1724)

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

authored by John Gee · committed by GitHub · parent 1b492d9 · Browse files · 9 files+430 added−25 removed
This commit

State

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

Diff stats

9 files+430 added−25 removed

  • tests:+273 added−0 removed
  • other:+157 added−25 removed

9 files+430 added−25 removed

modified:examples/options-extra.js+3 added-1 removed
added:examples/options-implies.js+22 added
modified:lib/command.js+25 added-1 removed
5 unmodified lines
67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, splitOptionFlags } = require('./option.js');10const { Option, splitOptionFlags, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213// @ts-check14
1178 unmodified lines
11931194 _parseCommand(operands, unknown) {1195 const parsed = this.parseOptions(unknown);1196 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1197 this._parseOptionsImplied();1198 operands = operands.concat(parsed.operands);1199 unknown = parsed.unknown;1200 this.args = operands.concat(unknown);1201
368 unmodified lines
1570 });1571 }15721573 /**1574 * Apply any implied option values, if option is undefined or default value.1575 *1576 * @api private1577 */1578 _parseOptionsImplied() {1579 const dualHelper = new DualOptions(this.options);1580 const hasCustomOptionValue = (optionKey) => {1581 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1582 };1583 this.options1584 .filter(option => (option.implied !== undefined) &&1585 hasCustomOptionValue(option.attributeName()) &&1586 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1587 .forEach((option) => {1588 Object.keys(option.implied)1589 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1590 .forEach(impliedKey => {1591 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1592 });1593 });1594 }15951596 /**1597 * Argument `name` is missing.1598 *1599 * @param {string} name1600 * @api private
522 unmodified lines
modified:lib/option.js+67 added
32 unmodified lines
33 this.parseArg = undefined;34 this.hidden = false;35 this.argChoices = undefined;36 this.conflictsWith = [];37 this.implied = undefined;38 }3940 /**41 * Set the default value, and optionally supply the description to be displayed in the help.
43 unmodified lines
85 return this;86 }8788 /**89 * Specify implied option values for when this option is set and the implied options are not.90 *91 * The custom processing (parseArg) is not called on the implied values.92 *93 * @example94 * program95 * .addOption(new Option('--log', 'write logging information to file'))96 * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));97 *98 * @param {Object} impliedOptionValues99 * @return {Option}100 */101 implies(impliedOptionValues) {102 this.implied = Object.assign(this.implied || {}, impliedOptionValues);103 return this;104 }105106 /**107 * Set environment variable to check for option value.108 * Priority order of option values is default < env < cli109 *110 * @param {string} name
125 unmodified lines
236 }237}238239/**240 * This class is to make it easier to work with dual options, without changing the existing241 * implementation. We support separate dual options for separate positive and negative options,242 * like `--build` and `--no-build`, which share a single option value. This works nicely for some243 * use cases, but is tricky for others where we want separate behaviours despite244 * the single shared option value.245 */246class DualOptions {247 /**248 * @param {Option[]} options249 */250 constructor(options) {251 this.positiveOptions = new Map();252 this.negativeOptions = new Map();253 this.dualOptions = new Set();254 options.forEach(option => {255 if (option.negate) {256 this.negativeOptions.set(option.attributeName(), option);257 } else {258 this.positiveOptions.set(option.attributeName(), option);259 }260 });261 this.negativeOptions.forEach((value, key) => {262 if (this.positiveOptions.has(key)) {263 this.dualOptions.add(key);264 }265 });266 }267268 /**269 * Did the value come from the option, and not from possible matching dual option?270 *271 * @param {any} value272 * @param {Option} option273 * @returns {boolean}274 */275 valueFromOption(value, option) {276 const optionKey = option.attributeName();277 if (!this.dualOptions.has(optionKey)) return true;278279 // Use the value to deduce if (probably) came from the option.280 const preset = this.negativeOptions.get(optionKey).presetArg;281 const negativeValue = (preset !== undefined) ? preset : false;282 return option.negate === (negativeValue === value);283 }284}285286/**287 * Convert string from kebab-case to camelCase.288 *289 * @param {string} str290 * @return {string}
29 unmodified lines
320}321322exports.Option = Option;323exports.splitOptionFlags = splitOptionFlags;324exports.DualOptions = DualOptions;
added:tests/options.dual-options.test.js+101 added
1const { Option, DualOptions } = require('../lib/option.js');2const { Command } = require('../');34// This tests an internal helper class which is not currently exposed on the package.56test('when positive option then stored in positiveOptions', () => {7 const program = new Command();8 program.option('--one');9 const helper = new DualOptions(program.options);10 expect(helper.positiveOptions.size).toEqual(1);11 expect(helper.negativeOptions.size).toEqual(0);12 expect(helper.dualOptions.size).toEqual(0);13});1415test('when negative option then stored in negativeOptions', () => {16 const program = new Command();17 program.option('--no-one');18 const helper = new DualOptions(program.options);19 expect(helper.positiveOptions.size).toEqual(0);20 expect(helper.negativeOptions.size).toEqual(1);21 expect(helper.dualOptions.size).toEqual(0);22});2324test('when unrelated positive and negative options then no dual options', () => {25 const program = new Command();26 program27 .option('--one')28 .option('--no-two');29 const helper = new DualOptions(program.options);30 expect(helper.dualOptions.size).toEqual(0);31});3233test('when related positive and negative options then stored as dual option', () => {34 const program = new Command();35 program36 .option('--one')37 .option('--no-one');38 const helper = new DualOptions(program.options);39 expect(helper.dualOptions.size).toEqual(1);40});4142test('when related negative and positive options then stored as dual option', () => {43 const program = new Command();44 program45 .option('--no-one')46 .option('--one');47 const helper = new DualOptions(program.options);48 expect(helper.dualOptions.size).toEqual(1);49});5051describe('valueFromOption with boolean option', () => {52 const positiveOption = new Option('--one');53 const negativeOption = new Option('--no-one');54 const options = [positiveOption, negativeOption];5556 test('when negativeOption with false then return true', () => {57 const helper = new DualOptions(options);58 expect(helper.valueFromOption(false, negativeOption)).toBe(true);59 });6061 test('when negativeOption with true then return false', () => {62 const helper = new DualOptions(options);63 expect(helper.valueFromOption(true, negativeOption)).toBe(false);64 });6566 test('when positiveOption with false then return false', () => {67 const helper = new DualOptions(options);68 expect(helper.valueFromOption(false, positiveOption)).toBe(false);69 });7071 test('when positiveOption with true then return true', () => {72 const helper = new DualOptions(options);73 expect(helper.valueFromOption(true, positiveOption)).toBe(true);74 });75});7677describe('valueFromOption with option expecting value and negative with preset', () => {78 const positiveOption = new Option('--one <value>');79 const negativeOption = new Option('--no-one').preset('FALSE');80 const options = [positiveOption, negativeOption];8182 test('when negativeOption with FALSE then return true', () => {83 const helper = new DualOptions(options);84 expect(helper.valueFromOption('FALSE', negativeOption)).toBe(true);85 });8687 test('when negativeOption with string then return false', () => {88 const helper = new DualOptions(options);89 expect(helper.valueFromOption('foo', negativeOption)).toBe(false);90 });9192 test('when positiveOption with FALSE then return false', () => {93 const helper = new DualOptions(options);94 expect(helper.valueFromOption('FALSE', positiveOption)).toBe(false);95 });9697 test('when positiveOption with true then return true', () => {98 const helper = new DualOptions(options);99 expect(helper.valueFromOption('foo', positiveOption)).toBe(true);100 });101});
added:tests/options.implies.test.js+172 added
1const { Command, Option } = require('../');23describe('check priorities', () => {4 test('when source undefined and implied undefined then implied is undefined', () => {5 const program = new Command();6 program7 .addOption(new Option('--foo').implies({ bar: 'implied' }))8 .option('--bar');9 program.parse([], { from: 'user' });10 expect(program.opts()).toEqual({});11 });1213 test('when source default and implied undefined then implied is undefined', () => {14 const program = new Command();15 program16 .addOption(new Option('--foo').implies({ bar: 'implied' }).default('default'))17 .option('--bar');18 program.parse([], { from: 'user' });19 expect(program.opts()).toEqual({ foo: 'default' });20 });2122 test('when source from env and implied undefined then implied is implied', () => {23 const program = new Command();24 const envName = 'COMMANDER_TEST_DELETE_ME';25 process.env[envName] = 'env';26 program27 .addOption(new Option('--foo').implies({ bar: 'implied' }).env(envName))28 .option('--bar');29 program.parse([], { from: 'user' });30 expect(program.opts()).toEqual({ foo: true, bar: 'implied' });31 delete process.env[envName];32 });3334 test('when source from cli and implied undefined then implied is implied', () => {35 const program = new Command();36 program37 .addOption(new Option('--foo').implies({ bar: 'implied' }))38 .option('--bar');39 program.parse(['--foo'], { from: 'user' });40 expect(program.opts()).toEqual({ foo: true, bar: 'implied' });41 });4243 test('when source cli and implied default then implied is implied', () => {44 const program = new Command();45 program46 .addOption(new Option('--foo').implies({ bar: 'implied' }))47 .option('--bar', '', 'default');48 program.parse(['--foo'], { from: 'user' });49 expect(program.opts()).toEqual({ foo: true, bar: 'implied' });50 });5152 test('when source cli and env default then implied is env', () => {53 const program = new Command();54 const envName = 'COMMANDER_TEST_DELETE_ME';55 process.env[envName] = 'env';56 program57 .addOption(new Option('--foo').implies({ bar: 'implied' }))58 .addOption(new Option('--bar <value>').env(envName));59 program.parse(['--foo'], { from: 'user' });60 expect(program.opts()).toEqual({ foo: true, bar: 'env' });61 delete process.env[envName];62 });63});6465test('when imply non-option then ok and stored', () => {66 const program = new Command();67 program68 .addOption(new Option('--foo').implies({ bar: 'implied' }));69 program.parse(['--foo'], { from: 'user' });70 expect(program.opts()).toEqual({ foo: true, bar: 'implied' });71});7273test('when imply multiple values then store multiple values', () => {74 const program = new Command();75 program76 .addOption(new Option('--foo').implies({ one: 'ONE', two: 'TWO' }))77 .option('--one')78 .option('--two');79 program.parse(['--foo'], { from: 'user' });80 expect(program.opts()).toEqual({ foo: true, one: 'ONE', two: 'TWO' });81});8283test('when imply multiple times then store multiple values', () => {84 const program = new Command();85 program86 .addOption(new Option('--foo').implies({ one: 'ONE' }).implies({ two: 'TWO' }))87 .option('--one')88 .option('--two');89 program.parse(['--foo'], { from: 'user' });90 expect(program.opts()).toEqual({ foo: true, one: 'ONE', two: 'TWO' });91});9293test('when imply from positive option then positive implied', () => {94 const program = new Command();95 program96 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))97 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));98 program.parse(['--foo'], { from: 'user' });99 expect(program.opts()).toEqual({ foo: true, implied: 'POSITIVE' });100});101102test('when imply from negative option then negative implied', () => {103 const program = new Command();104 program105 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))106 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));107 program.parse(['--no-foo'], { from: 'user' });108 expect(program.opts()).toEqual({ foo: false, implied: 'NEGATIVE' });109});110111test('when imply from lone negative option then negative implied', () => {112 const program = new Command();113 program114 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));115 program.parse(['--no-foo'], { from: 'user' });116 expect(program.opts()).toEqual({ foo: false, implied: 'NEGATIVE' });117});118119test('when imply from negative option with preset then negative implied', () => {120 const program = new Command();121 program122 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))123 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }).preset('FALSE'));124 program.parse(['--no-foo'], { from: 'user' });125 expect(program.opts()).toEqual({ foo: 'FALSE', implied: 'NEGATIVE' });126});127128test('when chained implies then only explicitly trigger', () => {129 const program = new Command();130 program131 .addOption(new Option('--one').implies({ two: true }))132 .addOption(new Option('--two').implies({ three: true }))133 .addOption(new Option('--three'));134 program.parse(['--one'], { from: 'user' });135 expect(program.opts()).toEqual({ one: true, two: true });136});137138test('when looped implies then no infinite loop', () => {139 const program = new Command();140 program141 .addOption(new Option('--ying').implies({ yang: true }))142 .addOption(new Option('--yang').implies({ ying: true }));143 program.parse(['--ying'], { from: 'user' });144 expect(program.opts()).toEqual({ ying: true, yang: true });145});146147test('when conflict with implied value then throw', () => {148 const program = new Command();149 program150 .exitOverride()151 .configureOutput({152 writeErr: () => {}153 })154 .addOption(new Option('--unary'))155 .addOption(new Option('--binary').conflicts('unary'))156 .addOption(new Option('--one').implies({ unary: true }));157158 expect(() => {159 program.parse(['--binary', '--one'], { from: 'user' });160 }).toThrow();161});162163test('when requiredOption with implied value then not throw', () => {164 const program = new Command();165 program166 .requiredOption('--target <target-file>')167 .addOption(new Option('--default-target').implies({ target: 'default-file' }));168169 expect(() => {170 program.parse(['--default-target'], { from: 'user' });171 }).not.toThrow();172});
modified:typings/index.d.ts+12 added
129 unmodified lines
130 */131 conflicts(names: string | string[]): this;132133 /**134 * Specify implied option values for when this option is set and the implied options are not.135 *136 * The custom processing (parseArg) is not called on the implied values.137 *138 * @example139 * program140 * .addOption(new Option('--log', 'write logging information to file'))141 * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));142 */143 implies(optionValues: OptionValues): this;144145 /**146 * Set environment variable to check for option value.147 * Priority order of option values is default < env < cli148 */149 env(name: string): this;
718 unmodified lines
modified:typings/index.test-d.ts+3 added
416 unmodified lines
417// conflicts418expectType<commander.Option>(baseOption.conflicts('a'));419expectType<commander.Option>(baseOption.conflicts(['a', 'b']));420421// implies422expectType<commander.Option>(baseOption.implies({ option: 'VALUE', colour: false }));423424// name425expectType<string>(baseOption.name());426427// attributeName
37 unmodified lines
modified:Readme.md+25 added-23 removed
55 unmodified lines
56For information about terms used in this document see: [terminology](./docs/terminology.md)5758## Installation5960```bash60```sh61npm install commander62```6364## Quick Start
20 unmodified lines
85const limit = options.first ? 1 : undefined;86console.log(program.args[0].split(options.separator, limit));87```8889```sh89```console90$ node split.js -s / --fits a/b/c91error: unknown option '--fits'92(Did you mean --first?)93$ node split.js -s / --first a/b/c
25 unmodified lines
119120program.parse();121```122123```sh123```console124$ node string-util.js help split125Usage: string-util split [options] <string>126127Split a string into substrings and display as an array.
51 unmodified lines
179Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.180181An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option.182183```bash183```sh184serve -p 80185serve -p80186serve --port 80187serve --port=80
30 unmodified lines
218if (options.small) console.log('- small pizza size');219if (options.pizzaType) console.log(`- ${options.pizzaType}`);220```221222```bash222```console223$ pizza-options -p224error: option '-p, --pizza-type <type>' argument missing225$ pizza-options -d -s -p vegetarian226{ debug: true, small: true, pizzaType: 'vegetarian' }
27 unmodified lines
254255console.log(`cheese: ${program.opts().cheese}`);256```257258```bash258```console259$ pizza-options260cheese: blue261$ pizza-options --cheese stilton262cheese: stilton
21 unmodified lines
284const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;285console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);286```287288```bash288```console289$ pizza-options290You ordered a pizza with sauce and mozzarella cheese291$ pizza-options --sauce292error: unknown option '--sauce'
19 unmodified lines
312else if (options.cheese === true) console.log('add cheese');313else console.log(`add cheese type ${options.cheese}`);314```315316```bash316```console317$ pizza-options318no cheese319$ pizza-options --cheese320add cheese
18 unmodified lines
339340program.parse();341```342343```bash343```console344$ pizza345error: required option '-c, --cheese <type>' not specified346```347
16 unmodified lines
364console.log('Options: ', program.opts());365console.log('Remaining arguments: ', program.args);366```367368```bash368```console369$ collect -n 1 2 3 --letter a b c370Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }371Remaining arguments: []372$ collect --letter=A -n80 operand
13 unmodified lines
386```js387program.version('0.0.1');388```389390```bash390```console391$ ./examples/pizza -V3920.0.1393```394
8 unmodified lines
403404You can add most options using the `.option()` method, but there are some additional features available405by constructing an `Option` explicitly for less common cases.406407Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js)407Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js)408409```js410program411 .addOption(new Option('-s, --secret').hideHelp())412 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))413 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))414 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))415 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))416 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'));416 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))417 .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));418```419419```bash420```console421$ extra --help422Usage: help [options]423424Options:425 -t, --timeout <delay> timeout in seconds (default: one minute)426 -d, --drink <size> drink cup size (choices: "small", "medium", "large")427 -p, --port <number> port number (env: PORT)427 --donate [amount] optional donation in dollars (preset: 20)428 --donate [amount] optional donation in dollars (preset: "20")429 --disable-server disables the server430 --free-drink small drink included free431 -h, --help display help for command432433$ extra --drink huge434error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.435434$ PORT=80 extra --donate435Options: { timeout: 60, donate: 20, port: '80' }436$ PORT=80 extra --donate --free-drink437Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }438439$ extra --disable-server --port 8000440error: option '--disable-server' cannot be used with option '-p, --port <number>'441```
48 unmodified lines
490if (options.collect.length > 0) console.log(options.collect);491if (options.list !== undefined) console.log(options.list);492```493492```bash494```console495$ custom -f 1e2496float: 100497$ custom --integer 2498integer: 2
230 unmodified lines
729help option is `-h,--help`.730731Example file: [pizza](./examples/pizza)732731```bash733```console734$ node ./examples/pizza --help735Usage: pizza [options]736737An application for pizza ordering
7 unmodified lines
745746A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show747further help for the subcommand. These are effectively the same if the `shell` program has implicit help:748747```bash749```sh750shell help751shell --help752753shell help spawn
53 unmodified lines
807// or808program.showHelpAfterError('(add --help for additional information)');809```810809```sh811```console812$ pizza --unknown813error: unknown option '--unknown'814(add --help for additional information)815```
3 unmodified lines
819```js820program.showSuggestionAfterError();821```822821```sh823```console824$ pizza --hepl825error: unknown option '--hepl'826(Did you mean --help?)827```
164 unmodified lines
992### TypeScript993994If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.995994```bash996```sh997node -r ts-node/register pm.ts998```9991000### createCommand()
98 unmodified lines