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
Provenance
- Commit
fc4fd41- Tree
d98ad61- Author
Erez Rokah <erezrokah@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
997655d
9 files changed+383 added−2 removed
modified:examples/options-extra.js+3 added-1 removed
10 unmodified lines11121314151516171819203 unmodified lines242526272810 unmodified lines .addOption(new Option('-s, --secret').hideHelp()) .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')) .addOption(new Option('-d, --drink <size>', 'drink cup size').choices(['small', 'medium', 'large'])) .addOption(new Option('-p, --port <number>', 'port number').env('PORT')) .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)); .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)) .addOption(new Option('--disable-server', 'disables the server').conflicts(['port'])); // or `.conflicts('port')` for a single conflict
program.parse();
console.log('Options: ', program.opts());3 unmodified lines// node options-extra.js --drink huge// PORT=80 node options-extra.js// node options-extra.js --donate// node options-extra.js --donate 30.50// node options-extra.js --disable-server --port 8000modified:lib/command.js+69 added
1215 unmodified lines1216 }1217 1218 outputHelpIfRequested(this, parsed.unknown);1219 this._checkForMissingMandatoryOptions();1220+ this._checkForConflictingOptions();1221 1222 // 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 lines1310 }1311 }1312 1313 /**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+ );1328+1329+ const optionsWithConflicting = definedNonDefaultOptions.filter(1330+ (option) => option.conflictsWith.length > 01331+ );1332+1333+ 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+ }1342+1343+ /**1344 * Parse options from `argv` removing known options,1345 * and return argv split into operands and unknown arguments.1346 *1347 * Examples:243 unmodified lines1591 this.error(message, { code: 'commander.missingMandatoryOptionValue' });1592 }1593 1594 /**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+ };1617+1618+ 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+ };1627+1628+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1629+ this.error(message, { code: 'commander.conflictingOption' });1630+ }1631+1632+ /**1633 * Unknown option `flag`.1634 *1635 * @param {string} flag1636 * @api private448 unmodified linesmodified:lib/option.js+17 added
31 unmodified lines32 this.envVar = undefined;33 this.parseArg = undefined;34 this.hidden = false;35 this.argChoices = undefined;36+ this.conflictsWith = [];37 }38 39 /**40 * Set the default value, and optionally supply the description to be displayed in the help.26 unmodified lines67 return this;68 }69 70 /**71+ * Set options name(s) that conflict with this option.72+ *73+ * @param {string | string[]} names74+ * @return {Option}75+ */76+77+ 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+ }81+82+ this.conflictsWith = this.conflictsWith.concat(names);83+ return this;84+ }85+86+ /**87 * Set environment variable to check for option value.88 * Priority order of option values is default < env < cli89 *90 * @param {string} name166 unmodified linesadded:tests/command.conflicts.test.js+256 added
1+const commander = require('../');2+3+describe('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);20+21+ return { program, actionMock };22+ }23+24+ beforeEach(() => {25+ delete process.env.SILENT;26+ delete process.env.JSON;27+ delete process.env.DUAL;28+ delete process.env.NO_DUAL;29+ });30+31+ 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+ });37+38+ 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+ });47+48+ test('should exit with error if conflicting options were set', () => {49+ const { program } = makeProgram();50+51+ 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+ });55+56+ test('should report the env variable as the conflicting option source, when conflicting option is set', () => {57+ const { program } = makeProgram();58+59+ process.env.SILENT = true;60+61+ expect(() => {62+ program.parse('node test.js foo --json'.split(' '));63+ }).toThrow("error: option '-j, --json' cannot be used with environment variable 'SILENT'");64+ });65+66+ test('should report the env variable as the configured option source, when configured option is set', () => {67+ const { program } = makeProgram();68+69+ process.env.JSON = true;70+71+ expect(() => {72+ program.parse('node test.js foo --silent'.split(' '));73+ }).toThrow("error: environment variable 'JSON' cannot be used with option '-s, --silent'");74+ });75+76+ test('should report both env variables as sources, when configured option and conflicting option are set', () => {77+ const { program } = makeProgram();78+79+ process.env.SILENT = true;80+ process.env.JSON = true;81+82+ expect(() => {83+ program.parse('node test.js foo'.split(' '));84+ }).toThrow("error: environment variable 'JSON' cannot be used with environment variable 'SILENT'");85+ });86+87+ test('should allow default value with a conflicting option', () => {88+ const { program, actionMock } = makeProgram();89+90+ program.commands[0].addOption(new commander.Option('-d, --debug', 'print debug logs').default(true).conflicts(['silent']));91+92+ program.parse('node test.js foo --silent'.split(' '));93+94+ expect(actionMock).toHaveBeenCalledTimes(1);95+ expect(actionMock).toHaveBeenCalledWith({ debug: true, silent: true }, expect.any(Object));96+ });97+98+ test('should report conflict on negated option flag', () => {99+ const { program } = makeProgram();100+101+ 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'));106+107+ 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+ });111+112+ test('should report conflict on negated option env variable', () => {113+ const { program } = makeProgram();114+115+ process.env.NO_COLOR = true;116+117+ 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'));122+123+ expect(() => {124+ program.parse('node test.js bar --red'.split(' '));125+ }).toThrow("error: option '--red' cannot be used with environment variable 'NO_COLOR'");126+ });127+128+ test('should report correct error for shorthand negated option', () => {129+ const { program } = makeProgram();130+131+ program132+ .command('bar')133+ .addOption(new commander.Option('--red'))134+ .addOption(new commander.Option('-N, --no-color').conflicts(['red']));135+136+ 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+ });140+141+ test('should report correct error for positive option when negated is configured', () => {142+ const { program } = makeProgram();143+144+ 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'));149+150+ expect(() => {151+ program.parse('node test.js bar --red --dual'.split(' '));152+ }).toThrow("error: option '--dual' cannot be used with option '--red'");153+ });154+155+ test('should report correct error for negated option when positive is configured', () => {156+ const { program } = makeProgram();157+158+ 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'));163+164+ 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+ });168+169+ test('should report correct error for positive env variable when negated is configured', () => {170+ const { program } = makeProgram();171+172+ 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'));177+178+ 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+ });183+184+ test('should report correct error for negated env variable when positive is configured', () => {185+ const { program } = makeProgram();186+187+ 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'));192+193+ 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+ });198+199+ test('should report correct error for positive option with string value when negated is configured', () => {200+ const { program } = makeProgram();201+202+ 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'));207+208+ 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+ });212+213+ test('should report correct error for negated option with preset when negated is configured', () => {214+ const { program } = makeProgram();215+216+ 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'));221+222+ 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+ });226+227+ test('should not throw error when conflicts is invoked with a single string that includes another option', () => {228+ const { program } = makeProgram();229+230+ const actionMock = jest.fn();231+232+ program233+ .command('bar')234+ .addOption(new commander.Option('--a'))235+ .addOption(new commander.Option('--b').conflicts('aa'))236+ .action(actionMock);237+238+ program.parse('node test.js bar --a --b'.split(' '));239+240+ expect(actionMock).toHaveBeenCalledTimes(1);241+ expect(actionMock).toHaveBeenCalledWith({ a: true, b: true }, expect.any(Object));242+ });243+244+ test('should throw error when conflicts is invoked with a single string that equals another option', () => {245+ const { program } = makeProgram();246+247+ program248+ .command('bar')249+ .addOption(new commander.Option('--a'))250+ .addOption(new commander.Option('--b').conflicts('a'));251+252+ 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 lines331 332 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'n'. NO");333 });334 335+ 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']));341+342+ let caughtErr;343+ try {344+ program.parse(['--debug', '--silent'], { from: 'user' });345+ } catch (err) {346+ caughtErr = err;347+ }348+349+ expectCommanderError(caughtErr, 1, 'commander.conflictingOption', "error: option '--debug' cannot be used with option '--silent'");350+ });351+352 test('when call error() then throw CommanderError', () => {353 const program = new commander.Command();354 program355 .exitOverride();34 unmodified linesmodified:tests/option.chain.test.js+6 added
34 unmodified lines353637383940414243444534 unmodified lines const option = new Option('-e,--example <value>'); const result = option.env('e'); expect(result).toBe(option); });
test('when call .conflicts() then returns this', () => { const option = new Option('-e,--example <value>'); const result = option.conflicts(['a']); expect(result).toBe(option); });});modified:typings/index.d.ts+5 added
117 unmodified lines118 */119 preset(arg: unknown): this;120 121 /**122+ * Set options name(s) that conflict with this option.123+ */124+ conflicts(names: string | string[]): this;125+126+ /**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 linesmodified:typings/index.test-d.ts+4 added
412 unmodified lines413 // choices414 expectType<commander.Option>(baseOption.choices(['a', 'b']));415 expectType<commander.Option>(baseOption.choices(['a', 'b'] as const));416 417+// conflicts418+expectType<commander.Option>(baseOption.conflicts('a'));419+expectType<commander.Option>(baseOption.conflicts(['a', 'b']));420+421 // name422 expectType<string>(baseOption.name());423 424 // attributeName37 unmodified linesmodified:Readme.md+6 added-1 removed
395 unmodified lines396 .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 ```403 404 ```bash405 $ extra --help3 unmodified lines409 -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 command415 416 $ extra --drink huge417 error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.418 419 $ PORT=80 extra --donate420 Options: { timeout: 60, donate: 20, port: '80' }421+422+$ extra --disable-server --port 8000423+error: option '--disable-server' cannot be used with option '-p, --port <number>'424 ```425 426 ### Custom option processing427 654 unmodified lines