Disallow excess arguments (#2223)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Change default allowExcessArguments to false and fix tests * Add migration tips for allowExcessArguments change
authored by John Gee · committed by GitHub · parent 4fcb276 · Browse files · 11 files·+95 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+95 added−16 removed
- tests:+46 added−15 removed
- other:+49 added−1 removed
Provenance
- Commit
58c28eb- Tree
7164865- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
4fcb276
11 files changed+95 added−16 removed
modified:lib/command.js+1 added-1 removed
23 unmodified lines24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;28- this._allowExcessArguments = true;28+ this._allowExcessArguments = false;29 /** @type {Argument[]} */30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old name32 /** @type {string[]} */2477 unmodified linesmodified:tests/args.literal.test.js+4 added-2 removed
7 unmodified lines891011121213141516174 unmodified lines222324252526272829307 unmodified linestest('when arguments includes -- then stop processing options', () => { const program = new commander.Command(); program .option('-f, --foo', 'add some foo') .option('-b, --bar', 'add some bar'); .option('-b, --bar', 'add some bar') .argument('[args...]'); program.parse(['node', 'test', '--foo', '--', '--bar', 'baz']); // More than one assert, ported from legacy test const opts = program.opts(); expect(opts.foo).toBe(true);4 unmodified linestest('when arguments include -- then more literals are passed-through as args', () => { const program = new commander.Command(); program .option('-f, --foo', 'add some foo') .option('-b, --bar', 'add some bar'); .option('-b, --bar', 'add some bar') .argument('[args...]'); program.parse(['node', 'test', '--', 'cmd', '--', '--arg']); expect(program.args).toEqual(['cmd', '--', '--arg']);});modified:tests/command.allowExcessArguments.test.js+4 added-4 removed
12 unmodified lines131415161717181920212223232425262724 unmodified lines52535455565657585960616263636465666749 unmodified lines12 unmodified lines cmd.action(() => {}); } }
test('when specify excess program argument then no error by default', () => { test('when specify excess program argument then error by default', () => { const program = new commander.Command(); configureCommand(program);
expect(() => { program.parse(['excess'], { from: 'user' }); }).not.toThrow(); }).toThrow(); });
test('when specify excess program argument and allowExcessArguments(false) then error', () => { const program = new commander.Command();24 unmodified lines program.parse(['excess'], { from: 'user' }); }).not.toThrow(); });
test('when specify excess command argument then no error (by default)', () => { test('when specify excess command argument then error (by default)', () => { const program = new commander.Command(); const sub = program.command('sub'); configureCommand(sub);
expect(() => { program.parse(['sub', 'excess'], { from: 'user' }); }).not.toThrow(); }).toThrow(); });
test('when specify excess command argument and allowExcessArguments(false) then error', () => { const program = new commander.Command();49 unmodified linesmodified:tests/command.allowUnknownOption.test.js+2 added
44 unmodified lines45 const program = new commander.Command();46 program47 .exitOverride()48 .allowUnknownOption()49+ .argument('[args...]') // unknown option will be passed as an argument50 .option('-p, --pepper', 'add pepper');51 52 expect(() => {53 program.parse(['node', 'test', '-m']);4 unmodified lines58 const program = new commander.Command();59 program60 .exitOverride()61 .allowUnknownOption(true)62+ .argument('[args...]') // unknown option will be passed as an argument63 .option('-p, --pepper', 'add pepper');64 65 expect(() => {66 program.parse(['node', 'test', '-m']);31 unmodified linesmodified:tests/command.copySettings.test.js+3 added-3 removed
117 unmodified lines118 test('when copyInheritedSettings then copies allowExcessArguments()', () => {119 const source = new commander.Command();120 const cmd = new commander.Command();121 122- expect(cmd._allowExcessArguments).toBeTruthy();123- source.allowExcessArguments(false);124- cmd.copyInheritedSettings(source);122 expect(cmd._allowExcessArguments).toBeFalsy();123+ source.allowExcessArguments();124+ cmd.copyInheritedSettings(source);125+ expect(cmd._allowExcessArguments).toBeTruthy();126 });127 128 test('when copyInheritedSettings then copies enablePositionalOptions()', () => {129 const source = new commander.Command();18 unmodified linesmodified:tests/command.hook.test.js+8 added-2 removed
194 unmodified lines195 const program = new commander.Command();196 program.argument('[arg]').hook('preAction', (thisCommand) => {197 expect(thisCommand.args).toEqual(['sub', 'value']);198 });199- program.command('sub').action(() => {});199+ program200+ .command('sub')201+ .argument('<arg>')202+ .action(() => {});203 program.parse(['sub', 'value'], { from: 'user' });204 });205 206 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {1 unmodified line208 const program = new commander.Command();209 program.hook('preAction', (thisCommand, actionCommand) => {210 expect(actionCommand.args).toEqual(['value']);211 });209- program.command('sub').action(() => {});212+ program213+ .command('sub')214+ .argument('<arg>')215+ .action(() => {});216 program.parse(['sub', 'value'], { from: 'user' });217 });218 });219 176 unmodified linesmodified:tests/command.parse.test.js+18 added
8 unmodified lines9 10 describe('.parse() args from', () => {11 test('when no args then use process.argv and app/script/args', () => {12 const program = new commander.Command();13+ program.argument('[args...]');14 const hold = process.argv;15 process.argv = 'node script.js user'.split(' ');16 program.parse();17 process.argv = hold;1 unmodified line19 });20 21 test('when no args and electron properties and not default app then use process.argv and app/args', () => {22 const program = new commander.Command();23+ program.argument('[args...]');24 const holdArgv = process.argv;25 process.versions.electron = '1.2.3';26 process.argv = 'node user'.split(' ');27 program.parse();3 unmodified lines31 });32 33 test('when args then app/script/args', () => {34 const program = new commander.Command();35+ program.argument('[args...]');36 program.parse('node script.js user'.split(' '));37 expect(program.args).toEqual(['user']);38 });39 40 test('when args from "node" then app/script/args', () => {41 const program = new commander.Command();42+ program.argument('[args...]');43 program.parse('node script.js user'.split(' '), { from: 'node' });44 expect(program.args).toEqual(['user']);45 });46 47 test('when args from "electron" and not default app then app/args', () => {48 const program = new commander.Command();49+ program.argument('[args...]');50 const hold = process.defaultApp;51 process.defaultApp = undefined;52 program.parse('customApp user'.split(' '), { from: 'electron' });53 process.defaultApp = hold;1 unmodified line55 });56 57 test('when args from "electron" and default app then app/script/args', () => {58 const program = new commander.Command();59+ program.argument('[args...]');60 const hold = process.defaultApp;61 process.defaultApp = true;62 program.parse('electron script user'.split(' '), { from: 'electron' });63 process.defaultApp = hold;1 unmodified line65 });66 67 test('when args from "user" then args', () => {68 const program = new commander.Command();69+ program.argument('[args...]');70 program.parse('user'.split(' '), { from: 'user' });71 expect(program.args).toEqual(['user']);72 });73 74 test('when args from "silly" then throw', () => {75 const program = new commander.Command();76+ program.argument('[args...]');77 expect(() => {78 program.parse(['node', 'script.js'], { from: 'silly' });79 }).toThrow();80 });1 unmodified line82 test.each(['-e', '--eval', '-p', '--print'])(83 'when node execArgv includes %s then app/args',84 (flag) => {85 const program = new commander.Command();86+ program.argument('[args...]');87 const holdExecArgv = process.execArgv;88 const holdArgv = process.argv;89 process.argv = ['node', 'user-arg'];90 process.execArgv = [flag, 'console.log("hello, world")'];8 unmodified lines99 100 describe('return type', () => {101 test('when call .parse then returns program', () => {102 const program = new commander.Command();103+ program.argument('[args...]');104 program.action(() => {});105 106 const result = program.parse(['node', 'test']);107 expect(result).toBe(program);108 });109 110 test('when await .parseAsync then returns program', async () => {111 const program = new commander.Command();112+ program.argument('[args...]');113 program.action(() => {});114 115 const result = await program.parseAsync(['node', 'test']);116 expect(result).toBe(program);2 unmodified lines119 120 // Easy mistake to make when writing unit tests121 test('when parse strings instead of array then throw', () => {122 const program = new commander.Command();123+ program.argument('[args...]');124 expect(() => {125 program.parse('node', 'test');126 }).toThrow();127 });128 129 describe('parse parameter is treated as readonly, per TypeScript declaration', () => {130 test('when parse called then parameter does not change', () => {131 const program = new commander.Command();132+ program.argument('[args...]');133 program.option('--debug');134 const original = ['node', '--debug', 'arg'];135 const param = original.slice();136 program.parse(param);1 unmodified line138 });139 140 test('when parse called and parsed args later changed then parameter does not change', () => {141 const program = new commander.Command();142+ program.argument('[args...]');143 program.option('--debug');144 const original = ['node', '--debug', 'arg'];145 const param = original.slice();146 program.parse(param);3 unmodified lines150 });151 152 test('when parse called and param later changed then parsed args do not change', () => {153 const program = new commander.Command();154+ program.argument('[args...]');155 program.option('--debug');156 const param = ['node', '--debug', 'arg'];157 program.parse(param);158 const oldArgs = program.args.slice();6 unmodified lines165 166 describe('parseAsync parameter is treated as readonly, per TypeScript declaration', () => {167 test('when parse called then parameter does not change', async () => {168 const program = new commander.Command();169+ program.argument('[args...]');170 program.option('--debug');171 const original = ['node', '--debug', 'arg'];172 const param = original.slice();173 await program.parseAsync(param);1 unmodified line175 });176 177 test('when parseAsync called and parsed args later changed then parameter does not change', async () => {178 const program = new commander.Command();179+ program.argument('[args...]');180 program.option('--debug');181 const original = ['node', '--debug', 'arg'];182 const param = original.slice();183 await program.parseAsync(param);3 unmodified lines187 });188 189 test('when parseAsync called and param later changed then parsed args do not change', async () => {190 const program = new commander.Command();191+ program.argument('[args...]');192 program.option('--debug');193 const param = ['node', '--debug', 'arg'];194 await program.parseAsync(param);195 const oldArgs = program.args.slice();6 unmodified linesmodified:tests/command.parseOptions.test.js+3 added-2 removed
168 unmodified lines169 // parse now sets program.args to the result of parseOptions (operands + unknown). Some limited testing.170 describe('parse and program.args', () => {171 test('when program has known flag and operand then option removed and operand returned', () => {172 const program = new commander.Command();173- program.option('--global-flag');173+ program.option('--global-flag').argument('[arg...]');174 program.parse('node test.js --global-flag arg'.split(' '));175 expect(program.args).toEqual(['arg']);176 });177 1 unmodified line179 const program = new commander.Command();180 program181 .allowUnknownOption()182 .option('--global-flag')183- .option('--global-value <value>');183+ .option('--global-value <value>')184+ .argument('[arg...]');185 program.parse(186 'node test.js aaa --global-flag bbb --unknown ccc --global-value value'.split(187 ' ',188 ),142 unmodified linesmodified:tests/command.positionalOptions.test.js+2 added
437 unmodified lines438 describe('program with allowUnknownOption', () => {439 test('when passThroughOptions and unknown option then arguments from unknown passed through', () => {440 const program = new commander.Command();441 program.passThroughOptions().allowUnknownOption().option('--debug');442+ program.argument('[args...]');443 444 program.parse(['--unknown', '--debug'], { from: 'user' });445 expect(program.args).toEqual(['--unknown', '--debug']);446 });447 448 test('when positionalOptions and unknown option then known options then known option parsed', () => {449 const program = new commander.Command();450 program.enablePositionalOptions().allowUnknownOption().option('--debug');451+ program.argument('[args...]');452 453 program.parse(['--unknown', '--debug'], { from: 'user' });454 expect(program.opts().debug).toBe(true);455 expect(program.args).toEqual(['--unknown']);67 unmodified linesmodified:tests/command.unknownCommand.test.js+2 added-2 removed
16 unmodified lines17 afterAll(() => {18 writeErrorSpy.mockRestore();19 });20 21- test('when unknown argument in simple program then no error', () => {21+ test('when unknown argument in simple program then error', () => {22 const program = new commander.Command();23 program.exitOverride();24 expect(() => {25 program.parse('node test.js unknown'.split(' '));26- }).not.toThrow();26+ }).toThrow();27 });28 29 test('when unknown command but action handler taking arg then no error', () => {30 const program = new commander.Command();42 unmodified linesmodified:CHANGELOG.md+48 added
6 unmodified lines7 8 <!-- markdownlint-disable MD024 -->9 <!-- markdownlint-disable MD004 -->10 11+## [13.x] (date goes here)12+13+### Changed14+15+- *Breaking*: excess command-arguments cause an error by default16+17+### Migration Tips18+19+**Excess command-arguments**20+21+It is now an error to pass more command-arguments than are expected.22+23+Old code:24+25+```js26+program.option('-p, --port <number>', 'port number');27+program.action((options) => {28+ console.log(program.args);29+});30+```31+32+```console33+$ node example.js a b c34+error: too many arguments. Expected 0 arguments but got 3.35+```36+37+You can declare the expected arguments. The help will then be more accurate too. Note that declaring38+new arguments will change what is passed to the action handler.39+40+```js41+program.option('-p, --port <number>', 'port number');42+program.argument('[args...]', 'remote command and arguments'); // expecting zero or more arguments43+program.action((args, options) => {44+ console.log(args);45+});46+```47+48+Or you could suppress the error without changing the rest of the code:49+50+```js51+program.option('-p, --port', 'port number');52+program.allowExcessArguments();53+program.action((options) => {54+ console.log(program.args);55+});56+```57+58+59 ## [12.1.0] (2024-05-18)60 61 ### Added62 1404 unmodified lines