Skip to content
Myr

Add .allowExcessArguments() and error message (#1407)

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

* Fix test file name * Add initial support for allowExcessArguments * Add TypeScript * Add tests * Refine error for program * Remove exception for legacy asterisk command, can disable if needed * Use defaulr parameters and simplify code

authored by John Gee · committed by GitHub · parent bd538aa · Browse files · 8 files+278 added−45 removed
This commit

State

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

Diff stats

8 files+278 added−45 removed

  • tests:+215 added−27 removed
  • other:+63 added−18 removed

8 files+278 added−45 removed

added:tests/command.allowExcessArguments.test.js+145 added
1const commander = require('../');23// Not testing output, just testing whether an error is detected.45describe('allowUnknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let writeErrorSpy;89 beforeAll(() => {10 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11 });1213 afterEach(() => {14 writeErrorSpy.mockClear();15 });1617 afterAll(() => {18 writeErrorSpy.mockRestore();19 });2021 test('when specify excess program argument then ignored by default', () => {22 const program = new commander.Command();23 program24 .exitOverride()25 .action(() => {});2627 expect(() => {28 program.parse(['excess'], { from: 'user' });29 }).not.toThrow();30 });3132 test('when specify excess program argument and allowExcessArguments(false) then error', () => {33 const program = new commander.Command();34 program35 .exitOverride()36 .allowExcessArguments(false)37 .action(() => {});3839 expect(() => {40 program.parse(['excess'], { from: 'user' });41 }).toThrow();42 });4344 test('when specify excess program argument and allowExcessArguments() then no error', () => {45 const program = new commander.Command();46 program47 .exitOverride()48 .allowExcessArguments()49 .action(() => {});5051 expect(() => {52 program.parse(['excess'], { from: 'user' });53 }).not.toThrow();54 });5556 test('when specify excess program argument and allowExcessArguments(true) then no error', () => {57 const program = new commander.Command();58 program59 .exitOverride()60 .allowExcessArguments(true)61 .action(() => {});6263 expect(() => {64 program.parse(['excess'], { from: 'user' });65 }).not.toThrow();66 });6768 test('when specify excess command argument then no error (by default)', () => {69 const program = new commander.Command();70 program71 .exitOverride()72 .command('sub')73 .action(() => { });7475 expect(() => {76 program.parse(['sub', 'excess'], { from: 'user' });77 }).not.toThrow();78 });7980 test('when specify excess command argument and allowExcessArguments(false) then error', () => {81 const program = new commander.Command();82 program83 .exitOverride()84 .command('sub')85 .allowUnknownOption()86 .allowExcessArguments(false)87 .action(() => { });8889 expect(() => {90 program.parse(['sub', 'excess'], { from: 'user' });91 }).toThrow();92 });9394 test('when specify expected arg and allowExcessArguments(false) then no error', () => {95 const program = new commander.Command();96 program97 .arguments('<file>')98 .exitOverride()99 .allowExcessArguments(false)100 .action(() => {});101102 expect(() => {103 program.parse(['file'], { from: 'user' });104 }).not.toThrow();105 });106107 test('when specify excess after <arg> and allowExcessArguments(false) then error', () => {108 const program = new commander.Command();109 program110 .arguments('<file>')111 .exitOverride()112 .allowExcessArguments(false)113 .action(() => {});114115 expect(() => {116 program.parse(['file', 'excess'], { from: 'user' });117 }).toThrow();118 });119120 test('when specify excess after [arg] and allowExcessArguments(false) then error', () => {121 const program = new commander.Command();122 program123 .arguments('[file]')124 .exitOverride()125 .allowExcessArguments(false)126 .action(() => {});127128 expect(() => {129 program.parse(['file', 'excess'], { from: 'user' });130 }).toThrow();131 });132133 test('when specify args for [args...] and allowExcessArguments(false) then no error', () => {134 const program = new commander.Command();135 program136 .arguments('[files...]')137 .exitOverride()138 .allowExcessArguments(false)139 .action(() => {});140141 expect(() => {142 program.parse(['file1', 'file2', 'file3'], { from: 'user' });143 }).not.toThrow();144 });145});
modified:tests/command.chain.test.js+6 added
modified:tests/command.exitOverride.test.js+37 added
118 unmodified lines
119 expect(stderrSpy).toHaveBeenCalled();120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");121 });122123 test('when specify excess argument then throw CommanderError', () => {124 const program = new commander.Command();125 program126 .exitOverride()127 .allowExcessArguments(false)128 .action(() => { });129130 let caughtErr;131 try {132 program.parse(['node', 'test', 'excess']);133 } catch (err) {134 caughtErr = err;135 }136137 expect(stderrSpy).toHaveBeenCalled();138 expectCommanderError(caughtErr, 1, 'commander.excessArguments', 'error: too many arguments. Expected 0 arguments but got 1.');139 });140141 test('when specify command with excess argument then throw CommanderError', () => {142 const program = new commander.Command();143 program144 .exitOverride()145 .command('speak')146 .allowExcessArguments(false)147 .action(() => { });148149 let caughtErr;150 try {151 program.parse(['node', 'test', 'speak', 'excess']);152 } catch (err) {153 caughtErr = err;154 }155156 expect(stderrSpy).toHaveBeenCalled();157 expectCommanderError(caughtErr, 1, 'commander.excessArguments', "error: too many arguments for 'speak'. Expected 0 arguments but got 1.");158 });159160 test('when specify --help then throw CommanderError', () => {161 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });162 const program = new commander.Command();163 program
117 unmodified lines
added:tests/help.visibleArguments.test.js+27 added
deleted:tests/help.visibleArgumnets.test.js-27 removed
modified:typings/commander-tests.ts+4 added
157 unmodified lines
158// allowUnknownOption159const allowUnknownOptionThis1: commander.Command = program.allowUnknownOption();160const allowUnknownOptionThis2: commander.Command = program.allowUnknownOption(false);161162// allowExcessArguments163const allowExcessArgumentsThis1: commander.Command = program.allowExcessArguments();164const allowExcessArgumentsThis2: commander.Command = program.allowExcessArguments(false);165166// parse167const parseThis1: commander.Command = program.parse();168const parseThis2: commander.Command = program.parse(process.argv);169const parseThis3: commander.Command = program.parse(['node', 'script.js'], { from: 'node' });
177 unmodified lines
modified:typings/index.d.ts+7 added
402 unmodified lines
403 */404 allowUnknownOption(allowUnknown?: boolean): this;405406 /**407 * Allow excess arguments on the command line.408 *409 * @returns `this` command for chaining410 */411 allowExcessArguments(allowExcess?: boolean): this;412413 /**414 * Parse `argv`, setting options and invoking commands when defined.415 *416 * The default expectation is that the arguments are from node and have the application as argv[0]417 * and the script being run in argv[1], with user parameters after that.
183 unmodified lines
modified:index.js+52 added-18 removed
402 unmodified lines
403404 /**405 * Whether the option is mandatory and must have a value after parsing.406 *407 * @param {boolean} [mandatory]407 * @param {boolean} [mandatory=true]408 * @return {Option}409 */410411 makeOptionMandatory(mandatory) {412 this.mandatory = (mandatory === undefined) || !!mandatory;411 makeOptionMandatory(mandatory = true) {412 this.mandatory = !!mandatory;413 return this;414 };415416 /**417 * Hide option in help.418 *419 * @param {boolean} [hide]419 * @param {boolean} [hide=true]420 * @return {Option}421 */422423 hideHelp(hide) {424 this.hidden = (hide === undefined) || !!hide;423 hideHelp(hide = true) {424 this.hidden = !!hide;425 return this;426 };427428 /**
105 unmodified lines
534 this.commands = [];535 this.options = [];536 this.parent = null;537 this._allowUnknownOption = false;538 this._allowExcessArguments = true;539 this._args = [];540 this.rawArgs = null;541 this._scriptPath = null;542 this._name = name || '';
609 unmodified lines
1152 * // for `.option('-f,--flag [value]'):1153 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour1154 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`1155 *1155 * @param {Boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.1156 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.1157 */1157 combineFlagAndOptionalValue(combine) {1158 this._combineFlagAndOptionalValue = (combine === undefined) || !!combine;1158 combineFlagAndOptionalValue(combine = true) {1159 this._combineFlagAndOptionalValue = !!combine;1160 return this;1161 };11621163 /**1164 * Allow unknown options on the command line.1165 *1165 * @param {Boolean} [allowUnknown] - if `true` or omitted, no error will be thrown1166 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown1167 * for unknown options.1168 */1168 allowUnknownOption(allowUnknown) {1169 this._allowUnknownOption = (allowUnknown === undefined) || !!allowUnknown;1169 allowUnknownOption(allowUnknown = true) {1170 this._allowUnknownOption = !!allowUnknown;1171 return this;1172 };11731174 /**1175 * Allow excess arguments on the command line.1176 *1177 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown1178 * for excess arguments.1179 */1180 allowExcessArguments(allowExcess = true) {1181 this._allowExcessArguments = !!allowExcess;1182 return this;1183 };11841185 /**1186 * Whether to store option values as properties on command object,1187 * or store separately (specify false). In both cases the option values can be accessed using .opts().1188 *1177 * @param {boolean} storeAsProperties1189 * @param {boolean} [storeAsProperties=true]1190 * @return {Command} `this` command for chaining1191 */11921181 storeOptionsAsProperties(storeAsProperties) {1193 storeOptionsAsProperties(storeAsProperties = true) {1194 this._storeOptionsAsPropertiesCalled = true;1183 this._storeOptionsAsProperties = (storeAsProperties === undefined) || !!storeAsProperties;1195 this._storeOptionsAsProperties = !!storeAsProperties;1196 if (this.options.length) {1197 throw new Error('call .storeOptionsAsProperties() before adding options');1198 }1199 return this;
2 unmodified lines
1202 /**1203 * Whether to pass command to action handler,1204 * or just the options (specify false).1205 *1194 * @param {boolean} passCommand1206 * @param {boolean} [passCommand=true]1207 * @return {Command} `this` command for chaining1208 */12091198 passCommandToAction(passCommand) {1199 this._passCommandToAction = (passCommand === undefined) || !!passCommand;1210 passCommandToAction(passCommand = true) {1211 this._passCommandToAction = !!passCommand;1212 return this;1213 };12141215 /**
287 unmodified lines
1503 }15041505 const commandEvent = `command:${this.name()}`;1506 if (this._actionHandler) {1507 // Check expected arguments and collect variadic together.1508 const args = this.args.slice();1509 this._args.forEach((arg, i) => {1510 if (arg.required && args[i] == null) {1511 this.missingArgument(arg.name);1512 } else if (arg.variadic) {1513 args[i] = args.splice(i);1514 args.length = Math.min(i + 1, args.length);1515 }1516 });1517 if (args.length > this._args.length) {1518 this._excessArguments(args);1519 }15201521 this._actionHandler(args);1522 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1523 } else if (this.parent && this.parent.listenerCount(commandEvent)) {
246 unmodified lines
1770 this._displayError(1, 'commander.unknownOption', message);1771 };17721773 /**1774 * Excess arguments, more than expected.1775 *1776 * @param {string[]} receivedArgs1777 * @api private1778 */17791780 _excessArguments(receivedArgs) {1781 if (this._allowExcessArguments) return;17821783 const expected = this._args.length;1784 const s = (expected === 1) ? '' : 's';1785 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1786 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1787 this._displayError(1, 'commander.excessArguments', message);1788 };17891790 /**1791 * Unknown command.1792 *1793 * @api private1794 */
415 unmodified lines