Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)
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 68199e6 · Browse files · 3 files·+294 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+294 added−4 removed
- tests:+267 added−0 removed
- other:+27 added−4 removed
Provenance
- Commit
f6302de- Tree
256a73b- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
68199e6
3 files changed+294 added−4 removed
modified:lib/command.js+25 added-3 removed
1739 unmodified lines1740 function maybeOption(arg) {1741 return arg.length > 1 && arg[0] === '-';1742 }1743 1744+ const negativeNumberArg = (arg) => {1745+ // return false if not a negative number1746+ if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;1747+ // negative number is ok unless digit used as an option in command hierarchy1748+ return !this._getCommandAndAncestors().some((cmd) =>1749+ cmd.options1750+ .map((opt) => opt.short)1751+ .some((short) => /^-\d$/.test(short)),1752+ );1753+ };1754+1755 // parse options1756 let activeVariadicOption = null;1757 while (args.length) {1758 const arg = args.shift();4 unmodified lines1763 dest.push(...args);1764 break;1765 }1766 1756- if (activeVariadicOption && !maybeOption(arg)) {1767+ if (1768+ activeVariadicOption &&1769+ (!maybeOption(arg) || negativeNumberArg(arg))1770+ ) {1771 this.emit(`option:${activeVariadicOption.name()}`, arg);1772 continue;1773 }1774 activeVariadicOption = null;8 unmodified lines1783 this.emit(`option:${option.name()}`, value);1784 } else if (option.optional) {1785 let value = null;1786 // historical behaviour is optional value is following arg unless an option1773- if (args.length > 0 && !maybeOption(args[0])) {1787+ if (1788+ args.length > 0 &&1789+ (!maybeOption(args[0]) || negativeNumberArg(args[0]))1790+ ) {1791 value = args.shift();1792 }1793 this.emit(`option:${option.name()}`, value);1794 } else {37 unmodified lines1832 // Not a recognised option by this command.1833 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.1834 1835 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1819- if (maybeOption(arg)) {1836+ // A negative number in a leaf command is not an unknown option.1837+ if (1838+ dest === operands &&1839+ maybeOption(arg) &&1840+ !(this.commands.length === 0 && negativeNumberArg(arg))1841+ ) {1842 dest = unknown;1843 }1844 1845 // If using positionalOptions, stop processing our options at subcommand.843 unmodified linesadded:tests/negatives.test.js+267 added
1+const { Command } = require('../');2+3+// boolean is whether is a consumable argument when negative numbers allowed4+const negativeNumbers = [5+ ['-.1', true],6+ ['-123', true],7+ ['-123.45', true],8+ ['-1e3', true],9+ ['-1e+3', true],10+ ['-1e-3', true],11+ ['-1.2e3', true],12+ ['-1.2e+3', true],13+ ['-1.2e-3', true],14+ ['-1e-3.0', false], // invalid number format15+ ['--1 ', false], // invalid number format16+ ['-0', true],17+ ['1', true],18+ ['-1x', false], // whole string is not a number19+ ['-x-1 ', false], // whole string is not a number20+ ['', true],21+ ['-0x1234', false], // not a plain number22+];23+24+test.each(negativeNumbers)(25+ `when option-argument for short optional is %s then consumed=%s`,26+ (value, consume) => {27+ const program = new Command();28+ program.exitOverride().configureOutput({ writeErr: () => {} });29+ program.option('-o, --optional [value]', 'optional option');30+ const args = ['-o', value];31+ let thrown = '';32+ try {33+ program.parse(args, { from: 'user' });34+ } catch (err) {35+ thrown = err.code;36+ }37+38+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');39+ // throws after setting optional to true40+ expect(program.opts()['optional']).toBe(consume ? value : true);41+ },42+);43+44+test.each(negativeNumbers)(45+ `when option-argument for long optional is %s then consumed=%s`,46+ (value, consume) => {47+ const program = new Command();48+ program.exitOverride().configureOutput({ writeErr: () => {} });49+ program.option('-o, --optional [value]', 'optional option');50+ const args = ['--optional', value];51+ let thrown = '';52+ try {53+ program.parse(args, { from: 'user' });54+ } catch (err) {55+ thrown = err.code;56+ }57+58+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');59+ // throws after setting optional to true60+ expect(program.opts()['optional']).toBe(consume ? value : true);61+ },62+);63+64+test.each(negativeNumbers)(65+ `when option-argument for short optional... is %s then consumed=%s`,66+ (value, consume) => {67+ const program = new Command();68+ program69+ .exitOverride()70+ .configureOutput({ writeErr: () => {} })71+ .option('-o, --optional [value...]', 'optional option');72+ const args = ['-o', 'first', value];73+ let thrown = '';74+ try {75+ program.parse(args, { from: 'user' });76+ } catch (err) {77+ thrown = err.code;78+ }79+80+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');81+ // throws after consuming 'first'82+ expect(program.opts()['optional']).toEqual(83+ consume ? ['first', value] : ['first'],84+ );85+ },86+);87+88+test.each(negativeNumbers)(89+ `when option-argument for long optional... is %s then consumed=%s`,90+ (value, consume) => {91+ const program = new Command();92+ program93+ .exitOverride()94+ .configureOutput({ writeErr: () => {} })95+ .option('-o, --optional [value...]', 'optional option');96+ const args = ['--optional', 'first', value];97+ let thrown = '';98+ try {99+ program.parse(args, { from: 'user' });100+ } catch (err) {101+ thrown = err.code;102+ }103+104+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');105+ // throws after consuming 'first'106+ expect(program.opts()['optional']).toEqual(107+ consume ? ['first', value] : ['first'],108+ );109+ },110+);111+112+test.each(negativeNumbers)(113+ `when command-argument is %s then consumed=%s`,114+ (value, consume) => {115+ const program = new Command();116+ program117+ .exitOverride()118+ .configureOutput({ writeErr: () => {} })119+ .argument('<value>', 'argument');120+ const args = [value];121+ let thrown = '';122+ try {123+ program.parse(args, { from: 'user' });124+ } catch (err) {125+ thrown = err.code;126+ }127+128+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');129+ expect(consume ? program.args : undefined).toEqual(130+ consume ? [value] : undefined,131+ );132+ },133+);134+135+test.each(negativeNumbers)(136+ `when digit option defined and option-argument is %s then negative not consumed`,137+ (value, _ignore) => {138+ const program = new Command();139+ program140+ .exitOverride()141+ .configureOutput({ writeErr: () => {} })142+ .option('-o, --optional [value]', 'optional option')143+ .option('-9', 'register option using digit');144+ const args = ['-o', value];145+ let thrown = '';146+ try {147+ program.parse(args, { from: 'user' });148+ } catch (err) {149+ thrown = err.code;150+ }151+152+ let consume = value[0] !== '-';153+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');154+ expect(program.opts()['optional']).toBe(consume ? value : true);155+ },156+);157+158+test.each(negativeNumbers)(159+ `when digit option defined and command-argument is %s then negative not consumed`,160+ (value, _ignore) => {161+ const program = new Command();162+ program163+ .exitOverride()164+ .configureOutput({ writeErr: () => {} })165+ .argument('[value]')166+ .option('-9', 'register option using digit');167+ const args = [value];168+ let thrown = '';169+ try {170+ program.parse(args, { from: 'user' });171+ } catch (err) {172+ thrown = err.code;173+ }174+175+ let consume = value[0] !== '-';176+ expect(thrown).toEqual(consume ? '' : 'commander.unknownOption');177+ expect(consume ? program.args : undefined).toEqual(178+ consume ? [value] : undefined,179+ );180+ },181+);182+183+test('when complex example with negative numbers then all consumed', () => {184+ const program = new Command();185+ program186+ .option('-o [value]', 'optional')187+ .option('-m <value>', 'required option-argument')188+ .option('-O [value...]', 'optional')189+ .option('-M <value...>', 'required option-argument')190+ .argument('[value...]', 'argument');191+ const args = [192+ '-10',193+ '-O',194+ '-40',195+ '-41',196+ '-M',197+ '-50',198+ '-51',199+ '-o',200+ '-20',201+ '-m',202+ '-30',203+ '-11',204+ ];205+ program.parse(args, { from: 'user' });206+ expect(program.opts()).toEqual({207+ o: '-20',208+ m: '-30',209+ O: ['-40', '-41'],210+ M: ['-50', '-51'],211+ });212+ expect(program.args).toEqual(['-10', '-11']);213+});214+215+test('when program has digit option then negatives not allowed in leaf command', () => {216+ const program = new Command();217+ program218+ .exitOverride()219+ .configureOutput({ writeErr: () => {} })220+ .option('-2', 'double option');221+ let leafArgs;222+ program223+ .command('leaf')224+ .argument('[value...]')225+ .action((args) => {226+ leafArgs = args;227+ });228+ const args = ['leaf', '-1'];229+ expect(() => program.parse(args, { from: 'user' })).toThrow();230+});231+232+test('when default command without digit option then negatives accepted', () => {233+ const program = new Command();234+ let leafArgs;235+ program236+ .command('leaf', { isDefault: true })237+ .argument('[value...]')238+ .action((args) => {239+ leafArgs = args;240+ });241+ program.parse(['-1'], { from: 'user' });242+ expect(leafArgs).toEqual(['-1']);243+});244+245+test('when default command with digit option then negative throws', () => {246+ const program = new Command();247+ program.exitOverride().configureOutput({ writeErr: () => {} });248+ program249+ .command('leaf', { isDefault: true })250+ .option('-2')251+ .argument('[value...]')252+ .action(() => {});253+ expect(() => program.parse(['-1'], { from: 'user' })).toThrow();254+});255+256+test('when program has subcommand and action handler then negative command-argument unsupported', () => {257+ // Known limitation in parsing. Only allowed negative command-arguments in leaf commands258+ // to minimise changes to parsing when added support for negative numbers.259+ const program = new Command();260+ program261+ .exitOverride()262+ .configureOutput({ writeErr: () => {} })263+ .argument('[value...]')264+ .action(() => {});265+ program.command('leaf').action(() => {});266+ expect(() => program.parse(['-1'], { from: 'user' })).toThrow();267+});modified:Readme.md+2 added-1 removed
332 unmodified lines333 add cheese type mozzarella334 ```335 336 Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.337-So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`.337+So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`.338+Negative numbers are special and are accepted as an option-argument.339 340 For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).341 342 ### Required option808 unmodified lines