Skip to content
Myr

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

11 files+95 added−16 removed

modified:lib/command.js+1 added-1 removed
23 unmodified lines
24 /** @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 lines
modified:tests/args.literal.test.js+4 added-2 removed
modified:tests/command.allowExcessArguments.test.js+4 added-4 removed
modified:tests/command.allowUnknownOption.test.js+2 added
44 unmodified lines
45 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');5152 expect(() => {53 program.parse(['node', 'test', '-m']);
4 unmodified lines
58 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');6465 expect(() => {66 program.parse(['node', 'test', '-m']);
31 unmodified lines
modified:tests/command.copySettings.test.js+3 added-3 removed
117 unmodified lines
118 test('when copyInheritedSettings then copies allowExcessArguments()', () => {119 const source = new commander.Command();120 const cmd = new commander.Command();121122 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 });127128 test('when copyInheritedSettings then copies enablePositionalOptions()', () => {129 const source = new commander.Command();
18 unmodified lines
modified:tests/command.hook.test.js+8 added-2 removed
194 unmodified lines
195 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 });205206 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {
1 unmodified line
208 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 lines
modified:tests/command.parse.test.js+18 added
8 unmodified lines
910describe('.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 line
19 });2021 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 lines
31 });3233 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 });3940 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 });4647 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 line
55 });5657 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 line
65 });6667 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 });7374 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 line
82 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 lines
99100describe('return type', () => {101 test('when call .parse then returns program', () => {102 const program = new commander.Command();103 program.argument('[args...]');104 program.action(() => {});105106 const result = program.parse(['node', 'test']);107 expect(result).toBe(program);108 });109110 test('when await .parseAsync then returns program', async () => {111 const program = new commander.Command();112 program.argument('[args...]');113 program.action(() => {});114115 const result = await program.parseAsync(['node', 'test']);116 expect(result).toBe(program);
2 unmodified lines
119120// Easy mistake to make when writing unit tests121test('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});128129describe('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 line
138 });139140 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 lines
150 });151152 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 lines
165166describe('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 line
175 });176177 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 lines
187 });188189 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 lines
modified:tests/command.parseOptions.test.js+3 added-2 removed
168 unmodified lines
169// parse now sets program.args to the result of parseOptions (operands + unknown). Some limited testing.170describe('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 line
179 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 lines
modified:tests/command.positionalOptions.test.js+2 added
437 unmodified lines
438describe('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...]');443444 program.parse(['--unknown', '--debug'], { from: 'user' });445 expect(program.args).toEqual(['--unknown', '--debug']);446 });447448 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...]');452453 program.parse(['--unknown', '--debug'], { from: 'user' });454 expect(program.opts().debug).toBe(true);455 expect(program.args).toEqual(['--unknown']);
67 unmodified lines
modified:tests/command.unknownCommand.test.js+2 added-2 removed
16 unmodified lines
17 afterAll(() => {18 writeErrorSpy.mockRestore();19 });2021 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 });2829 test('when unknown command but action handler taking arg then no error', () => {30 const program = new commander.Command();
42 unmodified lines
modified:CHANGELOG.md+48 added
6 unmodified lines
78<!-- markdownlint-disable MD024 -->9<!-- markdownlint-disable MD004 -->1011## [13.x] (date goes here)1213### Changed1415- *Breaking*: excess command-arguments cause an error by default1617### Migration Tips1819**Excess command-arguments**2021It is now an error to pass more command-arguments than are expected.2223Old code:2425```js26program.option('-p, --port <number>', 'port number');27program.action((options) => {28 console.log(program.args);29});30```3132```console33$ node example.js a b c34error: too many arguments. Expected 0 arguments but got 3.35```3637You can declare the expected arguments. The help will then be more accurate too. Note that declaring38new arguments will change what is passed to the action handler.3940```js41program.option('-p, --port <number>', 'port number');42program.argument('[args...]', 'remote command and arguments'); // expecting zero or more arguments43program.action((args, options) => {44 console.log(args);45});46```4748Or you could suppress the error without changing the rest of the code:4950```js51program.option('-p, --port', 'port number');52program.allowExcessArguments();53program.action((options) => {54 console.log(program.args);55});56```575859## [12.1.0] (2024-05-18)6061### Added62
1404 unmodified lines