Skip to content
Myr

feat(option): allow to set options as conflicting (#1678)

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

Problem: I would like to configure options that are mutually exclusive. For example --json (to set the output type), conflicts with --silent (to suppress output).

authored by Erez Rokah · committed by GitHub · parent 997655d · Browse files · 9 files+383 added−2 removed
This commit

State

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

Trailers

  • Solution: Added a new option method conflicts that accepts an array of strings (or a single string) with options that conflicts with the configured option.

Diff stats

9 files+383 added−2 removed

  • tests:+279 added−0 removed
  • other:+104 added−2 removed

9 files+383 added−2 removed

modified:examples/options-extra.js+3 added-1 removed
modified:lib/command.js+69 added
1215 unmodified lines
1216 }12171218 outputHelpIfRequested(this, parsed.unknown);1219 this._checkForMissingMandatoryOptions();1220 this._checkForConflictingOptions();12211222 // We do not always call this check to avoid masking a "better" error, like unknown command.1223 const checkForUnknownOptions = () => {1224 if (parsed.unknown.length > 0) {
85 unmodified lines
1310 }1311 }13121313 /**1314 * Display an error message if conflicting options are used together.1315 *1316 * @api private1317 */1318 _checkForConflictingOptions() {1319 const definedNonDefaultOptions = this.options.filter(1320 (option) => {1321 const optionKey = option.attributeName();1322 if (this.getOptionValue(optionKey) === undefined) {1323 return false;1324 }1325 return this.getOptionValueSource(optionKey) !== 'default';1326 }1327 );13281329 const optionsWithConflicting = definedNonDefaultOptions.filter(1330 (option) => option.conflictsWith.length > 01331 );13321333 optionsWithConflicting.forEach((option) => {1334 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1335 option.conflictsWith.includes(defined.attributeName())1336 );1337 if (conflictingAndDefined) {1338 this._conflictingOption(option, conflictingAndDefined);1339 }1340 });1341 }13421343 /**1344 * Parse options from `argv` removing known options,1345 * and return argv split into operands and unknown arguments.1346 *1347 * Examples:
243 unmodified lines
1591 this.error(message, { code: 'commander.missingMandatoryOptionValue' });1592 }15931594 /**1595 * `Option` conflicts with another option.1596 *1597 * @param {Option} option1598 * @param {Option} conflictingOption1599 * @api private1600 */1601 _conflictingOption(option, conflictingOption) {1602 // The calling code does not know whether a negated option is the source of the1603 // value, so do some work to take an educated guess.1604 const findBestOptionFromValue = (option) => {1605 const optionKey = option.attributeName();1606 const optionValue = this.getOptionValue(optionKey);1607 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1608 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1609 if (negativeOption && (1610 (negativeOption.presetArg === undefined && optionValue === false) ||1611 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1612 )) {1613 return negativeOption;1614 }1615 return positiveOption || option;1616 };16171618 const getErrorMessage = (option) => {1619 const bestOption = findBestOptionFromValue(option);1620 const optionKey = bestOption.attributeName();1621 const source = this.getOptionValueSource(optionKey);1622 if (source === 'env') {1623 return `environment variable '${bestOption.envVar}'`;1624 }1625 return `option '${bestOption.flags}'`;1626 };16271628 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1629 this.error(message, { code: 'commander.conflictingOption' });1630 }16311632 /**1633 * Unknown option `flag`.1634 *1635 * @param {string} flag1636 * @api private
448 unmodified lines
modified:lib/option.js+17 added
31 unmodified lines
32 this.envVar = undefined;33 this.parseArg = undefined;34 this.hidden = false;35 this.argChoices = undefined;36 this.conflictsWith = [];37 }3839 /**40 * Set the default value, and optionally supply the description to be displayed in the help.
26 unmodified lines
67 return this;68 }6970 /**71 * Set options name(s) that conflict with this option.72 *73 * @param {string | string[]} names74 * @return {Option}75 */7677 conflicts(names) {78 if (!Array.isArray(names) && typeof names !== 'string') {79 throw new Error('conflicts() argument must be a string or an array of strings');80 }8182 this.conflictsWith = this.conflictsWith.concat(names);83 return this;84 }8586 /**87 * Set environment variable to check for option value.88 * Priority order of option values is default < env < cli89 *90 * @param {string} name
166 unmodified lines
added:tests/command.conflicts.test.js+256 added
1const commander = require('../');23describe('command with conflicting options', () => {4 function makeProgram() {5 const actionMock = jest.fn();6 const program = new commander.Command();7 program8 .exitOverride()9 .configureOutput({10 writeErr: () => {}11 })12 .command('foo')13 .addOption(new commander.Option('-s, --silent', "Don't print anything").env('SILENT'))14 .addOption(15 new commander.Option('-j, --json', 'Format output as json').env('JSON').conflicts([16 'silent'17 ])18 )19 .action(actionMock);2021 return { program, actionMock };22 }2324 beforeEach(() => {25 delete process.env.SILENT;26 delete process.env.JSON;27 delete process.env.DUAL;28 delete process.env.NO_DUAL;29 });3031 test('should call action if there are no explicit conflicting options set', () => {32 const { program, actionMock } = makeProgram();33 program.parse('node test.js foo --json'.split(' '));34 expect(actionMock).toHaveBeenCalledTimes(1);35 expect(actionMock).toHaveBeenCalledWith({ json: true }, expect.any(Object));36 });3738 test('should call action when there are no implicit conflicting options set', () => {39 const { program, actionMock } = makeProgram();40 program.parse('node test.js foo --silent'.split(' '));41 expect(actionMock).toHaveBeenCalledTimes(1);42 expect(actionMock).toHaveBeenCalledWith(43 { silent: true },44 expect.any(Object)45 );46 });4748 test('should exit with error if conflicting options were set', () => {49 const { program } = makeProgram();5051 expect(() => {52 program.parse('node test.js foo --silent --json'.split(' '));53 }).toThrow("error: option '-j, --json' cannot be used with option '-s, --silent'");54 });5556 test('should report the env variable as the conflicting option source, when conflicting option is set', () => {57 const { program } = makeProgram();5859 process.env.SILENT = true;6061 expect(() => {62 program.parse('node test.js foo --json'.split(' '));63 }).toThrow("error: option '-j, --json' cannot be used with environment variable 'SILENT'");64 });6566 test('should report the env variable as the configured option source, when configured option is set', () => {67 const { program } = makeProgram();6869 process.env.JSON = true;7071 expect(() => {72 program.parse('node test.js foo --silent'.split(' '));73 }).toThrow("error: environment variable 'JSON' cannot be used with option '-s, --silent'");74 });7576 test('should report both env variables as sources, when configured option and conflicting option are set', () => {77 const { program } = makeProgram();7879 process.env.SILENT = true;80 process.env.JSON = true;8182 expect(() => {83 program.parse('node test.js foo'.split(' '));84 }).toThrow("error: environment variable 'JSON' cannot be used with environment variable 'SILENT'");85 });8687 test('should allow default value with a conflicting option', () => {88 const { program, actionMock } = makeProgram();8990 program.commands[0].addOption(new commander.Option('-d, --debug', 'print debug logs').default(true).conflicts(['silent']));9192 program.parse('node test.js foo --silent'.split(' '));9394 expect(actionMock).toHaveBeenCalledTimes(1);95 expect(actionMock).toHaveBeenCalledWith({ debug: true, silent: true }, expect.any(Object));96 });9798 test('should report conflict on negated option flag', () => {99 const { program } = makeProgram();100101 program102 .command('bar')103 .addOption(new commander.Option('--red').conflicts(['color']))104 .addOption(new commander.Option('--color'))105 .addOption(new commander.Option('-N, --no-color'));106107 expect(() => {108 program.parse('node test.js bar --red -N'.split(' '));109 }).toThrow("error: option '--red' cannot be used with option '-N, --no-color'");110 });111112 test('should report conflict on negated option env variable', () => {113 const { program } = makeProgram();114115 process.env.NO_COLOR = true;116117 program118 .command('bar')119 .addOption(new commander.Option('--red').conflicts(['color']))120 .addOption(new commander.Option('--color'))121 .addOption(new commander.Option('-N, --no-color').env('NO_COLOR'));122123 expect(() => {124 program.parse('node test.js bar --red'.split(' '));125 }).toThrow("error: option '--red' cannot be used with environment variable 'NO_COLOR'");126 });127128 test('should report correct error for shorthand negated option', () => {129 const { program } = makeProgram();130131 program132 .command('bar')133 .addOption(new commander.Option('--red'))134 .addOption(new commander.Option('-N, --no-color').conflicts(['red']));135136 expect(() => {137 program.parse('node test.js bar --red -N'.split(' '));138 }).toThrow("error: option '-N, --no-color' cannot be used with option '--red'");139 });140141 test('should report correct error for positive option when negated is configured', () => {142 const { program } = makeProgram();143144 program145 .command('bar')146 .addOption(new commander.Option('--red'))147 .addOption(new commander.Option('--dual').env('DUAL').conflicts(['red']))148 .addOption(new commander.Option('--no-dual').env('NO_DUAL'));149150 expect(() => {151 program.parse('node test.js bar --red --dual'.split(' '));152 }).toThrow("error: option '--dual' cannot be used with option '--red'");153 });154155 test('should report correct error for negated option when positive is configured', () => {156 const { program } = makeProgram();157158 program159 .command('bar')160 .addOption(new commander.Option('--red'))161 .addOption(new commander.Option('--dual').env('DUAL').conflicts(['red']))162 .addOption(new commander.Option('--no-dual').env('NO_DUAL'));163164 expect(() => {165 program.parse('node test.js bar --red --no-dual'.split(' '));166 }).toThrow("error: option '--no-dual' cannot be used with option '--red'");167 });168169 test('should report correct error for positive env variable when negated is configured', () => {170 const { program } = makeProgram();171172 program173 .command('bar')174 .addOption(new commander.Option('--red'))175 .addOption(new commander.Option('--dual').env('DUAL').conflicts(['red']))176 .addOption(new commander.Option('--no-dual').env('NO_DUAL'));177178 process.env.DUAL = 'true';179 expect(() => {180 program.parse('node test.js bar --red'.split(' '));181 }).toThrow("error: environment variable 'DUAL' cannot be used with option '--red'");182 });183184 test('should report correct error for negated env variable when positive is configured', () => {185 const { program } = makeProgram();186187 program188 .command('bar')189 .addOption(new commander.Option('--red'))190 .addOption(new commander.Option('--dual').env('DUAL').conflicts(['red']))191 .addOption(new commander.Option('--no-dual').env('NO_DUAL'));192193 process.env.NO_DUAL = 'true';194 expect(() => {195 program.parse('node test.js bar --red'.split(' '));196 }).toThrow("error: environment variable 'NO_DUAL' cannot be used with option '--red'");197 });198199 test('should report correct error for positive option with string value when negated is configured', () => {200 const { program } = makeProgram();201202 program203 .command('bar')204 .addOption(new commander.Option('--red'))205 .addOption(new commander.Option('--dual2 <str>').conflicts(['red']))206 .addOption(new commander.Option('--no-dual2').preset('BAD'));207208 expect(() => {209 program.parse('node test.js bar --red --dual2 foo'.split(' '));210 }).toThrow("error: option '--dual2 <str>' cannot be used with option '--red'");211 });212213 test('should report correct error for negated option with preset when negated is configured', () => {214 const { program } = makeProgram();215216 program217 .command('bar')218 .addOption(new commander.Option('--red'))219 .addOption(new commander.Option('--dual2 <str>').conflicts(['red']))220 .addOption(new commander.Option('--no-dual2').preset('BAD'));221222 expect(() => {223 program.parse('node test.js bar --red --no-dual2'.split(' '));224 }).toThrow("error: option '--no-dual2' cannot be used with option '--red'");225 });226227 test('should not throw error when conflicts is invoked with a single string that includes another option', () => {228 const { program } = makeProgram();229230 const actionMock = jest.fn();231232 program233 .command('bar')234 .addOption(new commander.Option('--a'))235 .addOption(new commander.Option('--b').conflicts('aa'))236 .action(actionMock);237238 program.parse('node test.js bar --a --b'.split(' '));239240 expect(actionMock).toHaveBeenCalledTimes(1);241 expect(actionMock).toHaveBeenCalledWith({ a: true, b: true }, expect.any(Object));242 });243244 test('should throw error when conflicts is invoked with a single string that equals another option', () => {245 const { program } = makeProgram();246247 program248 .command('bar')249 .addOption(new commander.Option('--a'))250 .addOption(new commander.Option('--b').conflicts('a'));251252 expect(() => {253 program.parse('node test.js bar --a --b'.split(' '));254 }).toThrow("error: option '--b' cannot be used with option '--a'");255 });256});
modified:tests/command.exitOverride.test.js+17 added
330 unmodified lines
331332 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'n'. NO");333 });334335 test('when has conflicting option then throw CommanderError', () => {336 const program = new commander.Command();337 program338 .exitOverride()339 .addOption(new commander.Option('--silent'))340 .addOption(new commander.Option('--debug').conflicts(['silent']));341342 let caughtErr;343 try {344 program.parse(['--debug', '--silent'], { from: 'user' });345 } catch (err) {346 caughtErr = err;347 }348349 expectCommanderError(caughtErr, 1, 'commander.conflictingOption', "error: option '--debug' cannot be used with option '--silent'");350 });351352 test('when call error() then throw CommanderError', () => {353 const program = new commander.Command();354 program355 .exitOverride();
34 unmodified lines
modified:tests/option.chain.test.js+6 added
modified:typings/index.d.ts+5 added
117 unmodified lines
118 */119 preset(arg: unknown): this;120121 /**122 * Set options name(s) that conflict with this option.123 */124 conflicts(names: string | string[]): this;125126 /**127 * Set environment variable to check for option value.128 * Priority order of option values is default < env < cli129 */130 env(name: string): this;
718 unmodified lines
modified:typings/index.test-d.ts+4 added
412 unmodified lines
413// choices414expectType<commander.Option>(baseOption.choices(['a', 'b']));415expectType<commander.Option>(baseOption.choices(['a', 'b'] as const));416417// conflicts418expectType<commander.Option>(baseOption.conflicts('a'));419expectType<commander.Option>(baseOption.conflicts(['a', 'b']));420421// name422expectType<string>(baseOption.name());423424// attributeName
37 unmodified lines
modified:Readme.md+6 added-1 removed
395 unmodified lines
396 .addOption(new Option('-s, --secret').hideHelp())397 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))398 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))399 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))400 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat));400 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))401 .addOption(new Option('--disable-server', 'disables the server').conflicts(['port'])); // or `.conflicts('port')` for a single conflict402```403404```bash405$ extra --help
3 unmodified lines
409 -t, --timeout <delay> timeout in seconds (default: one minute)410 -d, --drink <size> drink cup size (choices: "small", "medium", "large")411 -p, --port <number> port number (env: PORT)412 --donate [amount] optional donation in dollars (preset: 20)413 --disable-server disables the server414 -h, --help display help for command415416$ extra --drink huge417error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.418419$ PORT=80 extra --donate420Options: { timeout: 60, donate: 20, port: '80' }421422$ extra --disable-server --port 8000423error: option '--disable-server' cannot be used with option '-p, --port <number>'424```425426### Custom option processing427
654 unmodified lines