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
Provenance
- Commit
09f277a- Tree
e462deb- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
bd538aa
8 files changed+278 added−45 removed
added:tests/command.allowExcessArguments.test.js+145 added
1+const commander = require('../');2+3+// Not testing output, just testing whether an error is detected.4+5+describe('allowUnknownOption', () => {6+ // Optional. Use internal knowledge to suppress output to keep test output clean.7+ let writeErrorSpy;8+9+ beforeAll(() => {10+ writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11+ });12+13+ afterEach(() => {14+ writeErrorSpy.mockClear();15+ });16+17+ afterAll(() => {18+ writeErrorSpy.mockRestore();19+ });20+21+ test('when specify excess program argument then ignored by default', () => {22+ const program = new commander.Command();23+ program24+ .exitOverride()25+ .action(() => {});26+27+ expect(() => {28+ program.parse(['excess'], { from: 'user' });29+ }).not.toThrow();30+ });31+32+ 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(() => {});38+39+ expect(() => {40+ program.parse(['excess'], { from: 'user' });41+ }).toThrow();42+ });43+44+ test('when specify excess program argument and allowExcessArguments() then no error', () => {45+ const program = new commander.Command();46+ program47+ .exitOverride()48+ .allowExcessArguments()49+ .action(() => {});50+51+ expect(() => {52+ program.parse(['excess'], { from: 'user' });53+ }).not.toThrow();54+ });55+56+ 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(() => {});62+63+ expect(() => {64+ program.parse(['excess'], { from: 'user' });65+ }).not.toThrow();66+ });67+68+ 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(() => { });74+75+ expect(() => {76+ program.parse(['sub', 'excess'], { from: 'user' });77+ }).not.toThrow();78+ });79+80+ 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(() => { });88+89+ expect(() => {90+ program.parse(['sub', 'excess'], { from: 'user' });91+ }).toThrow();92+ });93+94+ 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(() => {});101+102+ expect(() => {103+ program.parse(['file'], { from: 'user' });104+ }).not.toThrow();105+ });106+107+ 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(() => {});114+115+ expect(() => {116+ program.parse(['file', 'excess'], { from: 'user' });117+ }).toThrow();118+ });119+120+ 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(() => {});127+128+ expect(() => {129+ program.parse(['file', 'excess'], { from: 'user' });130+ }).toThrow();131+ });132+133+ 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(() => {});140+141+ expect(() => {142+ program.parse(['file1', 'file2', 'file3'], { from: 'user' });143+ }).not.toThrow();144+ });145+});modified:tests/command.chain.test.js+6 added
68 unmodified lines697071727374757677787980818268 unmodified lines68 unmodified lines const result = program.allowUnknownOption(); expect(result).toBe(program); });
test('when call .allowExcessArguments() then returns this', () => { const program = new Command(); const result = program.allowExcessArguments(); expect(result).toBe(program); });
test('when call .storeOptionsAsProperties() then returns this', () => { const program = new Command(); const result = program.storeOptionsAsProperties(); expect(result).toBe(program);68 unmodified linesmodified:tests/command.exitOverride.test.js+37 added
118 unmodified lines119 expect(stderrSpy).toHaveBeenCalled();120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");121 });122 123+ test('when specify excess argument then throw CommanderError', () => {124+ const program = new commander.Command();125+ program126+ .exitOverride()127+ .allowExcessArguments(false)128+ .action(() => { });129+130+ let caughtErr;131+ try {132+ program.parse(['node', 'test', 'excess']);133+ } catch (err) {134+ caughtErr = err;135+ }136+137+ expect(stderrSpy).toHaveBeenCalled();138+ expectCommanderError(caughtErr, 1, 'commander.excessArguments', 'error: too many arguments. Expected 0 arguments but got 1.');139+ });140+141+ 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(() => { });148+149+ let caughtErr;150+ try {151+ program.parse(['node', 'test', 'speak', 'excess']);152+ } catch (err) {153+ caughtErr = err;154+ }155+156+ expect(stderrSpy).toHaveBeenCalled();157+ expectCommanderError(caughtErr, 1, 'commander.excessArguments', "error: too many arguments for 'speak'. Expected 0 arguments but got 1.");158+ });159+160 test('when specify --help then throw CommanderError', () => {161 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });162 const program = new commander.Command();163 program117 unmodified linesadded:tests/help.visibleArguments.test.js+27 added
123456789101112131415161718192021222324252627const commander = require('../');
// These are tests of the Help class, not of the Command help.// There is some overlap with the higher level Command tests (which predate Help).
describe('visibleArguments', () => { test('when no arguments then empty array', () => { const program = new commander.Command(); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([]); });
test('when argument but no argument description then empty array', () => { const program = new commander.Command(); program.arguments('<file>'); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([]); });
test('when argument and argument description then returned', () => { const program = new commander.Command(); program.arguments('<file>'); program.description('dummy', { file: 'file description' }); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([{ term: 'file', description: 'file description' }]); });});deleted:tests/help.visibleArgumnets.test.js-27 removed
123456789101112131415161718192021222324252627const commander = require('../');
// These are tests of the Help class, not of the Command help.// There is some overlap with the higher level Command tests (which predate Help).
describe('visibleArguments', () => { test('when no arguments then empty array', () => { const program = new commander.Command(); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([]); });
test('when argument but no argument description then empty array', () => { const program = new commander.Command(); program.arguments('<file>'); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([]); });
test('when argument and argument description then returned', () => { const program = new commander.Command(); program.arguments('<file>'); program.description('dummy', { file: 'file description' }); const helper = new commander.Help(); expect(helper.visibleArguments(program)).toEqual([{ term: 'file', description: 'file description' }]); });});modified:typings/commander-tests.ts+4 added
157 unmodified lines158 // allowUnknownOption159 const allowUnknownOptionThis1: commander.Command = program.allowUnknownOption();160 const allowUnknownOptionThis2: commander.Command = program.allowUnknownOption(false);161 162+// allowExcessArguments163+const allowExcessArgumentsThis1: commander.Command = program.allowExcessArguments();164+const allowExcessArgumentsThis2: commander.Command = program.allowExcessArguments(false);165+166 // parse167 const parseThis1: commander.Command = program.parse();168 const parseThis2: commander.Command = program.parse(process.argv);169 const parseThis3: commander.Command = program.parse(['node', 'script.js'], { from: 'node' });177 unmodified linesmodified:typings/index.d.ts+7 added
402 unmodified lines403 */404 allowUnknownOption(allowUnknown?: boolean): this;405 406 /**407+ * Allow excess arguments on the command line.408+ *409+ * @returns `this` command for chaining410+ */411+ allowExcessArguments(allowExcess?: boolean): this;412+413+ /**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 linesmodified:index.js+52 added-18 removed
402 unmodified lines403 404 /**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 */410 411- makeOptionMandatory(mandatory) {412- this.mandatory = (mandatory === undefined) || !!mandatory;411+ makeOptionMandatory(mandatory = true) {412+ this.mandatory = !!mandatory;413 return this;414 };415 416 /**417 * Hide option in help.418 *419- * @param {boolean} [hide]419+ * @param {boolean} [hide=true]420 * @return {Option}421 */422 423- hideHelp(hide) {424- this.hidden = (hide === undefined) || !!hide;423+ hideHelp(hide = true) {424+ this.hidden = !!hide;425 return this;426 };427 428 /**105 unmodified lines534 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 lines1152 * // 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 };1162 1163 /**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 };1173 1174 /**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+ };1184+1185+ /**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 */1192 1181- 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 lines1202 /**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 */1209 1198- passCommandToAction(passCommand) {1199- this._passCommandToAction = (passCommand === undefined) || !!passCommand;1210+ passCommandToAction(passCommand = true) {1211+ this._passCommandToAction = !!passCommand;1212 return this;1213 };1214 1215 /**287 unmodified lines1503 }1504 1505 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+ }1520 1521 this._actionHandler(args);1522 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1523 } else if (this.parent && this.parent.listenerCount(commandEvent)) {246 unmodified lines1770 this._displayError(1, 'commander.unknownOption', message);1771 };1772 1773 /**1774+ * Excess arguments, more than expected.1775+ *1776+ * @param {string[]} receivedArgs1777+ * @api private1778+ */1779+1780+ _excessArguments(receivedArgs) {1781+ if (this._allowExcessArguments) return;1782+1783+ 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+ };1789+1790+ /**1791 * Unknown command.1792 *1793 * @api private1794 */415 unmodified lines