Skip unknown options check if there is a better error to display (#1464)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Check for uknown options in multiple places, to allow skipping check * Missing command shows help, does not check for options * Check unknown commands before unknown options * Add comments * Restore legacy command:* handling * Add more tests for legacy command('*') * Add comment explaining history for test * Improve comment * Test for command suggestion despite unknown option * Improve comments and suppress test output * Add test for competing unknown command and option * Test that unknown option is an error in simple program * Fix test and comment
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+97 added−5 removed
- tests:+83 added−1 removed
- other:+14 added−4 removed
Provenance
- Commit
4f78587- Tree
b999363- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
b040db4
4 files changed+97 added−5 removed
modified:tests/command.asterisk.test.js+53 added
62 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810936 unmodified lines14614714814915015115215315415515615715815916016116216316462 unmodified lines .action(mockAction); program.parse(['node', 'test', 'unrecognised-command']); expect(mockAction).toHaveBeenCalled(); });
test('when unrecognised argument and known option then asterisk action called', () => { // This tests for a regression between v4 and v5. Known default option should not be rejected by program. const mockAction = jest.fn(); const program = new commander.Command(); program .command('install'); const star = program .command('*') .arguments('[args...]') .option('-d, --debug') .action(mockAction); program.parse(['node', 'test', 'unrecognised-command', '--debug']); expect(mockAction).toHaveBeenCalled(); expect(star.opts().debug).toEqual(true); });
test('when non-command argument and unknown option then error for unknown option', () => { // This is a change in behaviour from v2 which did not error, but is consistent with modern better detection of invalid options const mockAction = jest.fn(); const program = new commander.Command(); program .exitOverride() .configureOutput({ writeErr: () => {} }) .command('install'); program .command('*') .arguments('[args...]') .action(mockAction); let caughtErr; try { program.parse(['node', 'test', 'some-argument', '--unknown']); } catch (err) { caughtErr = err; } expect(caughtErr.code).toEqual('commander.unknownOption'); });});
// Test .on explicitly rather than assuming covered by .commanddescribe(".on('command:*')", () => {36 unmodified lines .on('command:*', mockAction); program.parse(['node', 'test', 'unrecognised-command']); expect(mockAction).toHaveBeenCalled(); });
test('when unrecognised command/argument and unknown option then listener called', () => { // Give listener a chance to make a suggestion for misspelled command. The option // could only be unknown because the command is not correct. // Regression identified in https://github.com/tj/commander.js/issues/1460#issuecomment-772313494 const mockAction = jest.fn(); const program = new commander.Command(); program .command('install'); program .on('command:*', mockAction); program.parse(['node', 'test', 'intsall', '--unknown']); expect(mockAction).toHaveBeenCalled(); });});modified:tests/command.unknownCommand.test.js+17 added-1 removed
1 const commander = require('../');2 3-describe('unknownOption', () => {3+describe('unknownCommand', () => {4 // Optional. Use internal knowledge to suppress output to keep test output clean.5 let writeErrorSpy;6 7 beforeAll(() => {54 unmodified lines62 }63 expect(caughtErr.code).toBe('commander.unknownCommand');64 });65 66+ test('when unknown command and unknown option then error is for unknown command', () => {67+ // The unknown command is more useful since the option is for an unknown command (and might be68+ // ok if the command had been correctly spelled, say).69+ const program = new commander.Command();70+ program71+ .exitOverride()72+ .command('sub');73+ let caughtErr;74+ try {75+ program.parse('node test.js sbu --silly'.split(' '));76+ } catch (err) {77+ caughtErr = err;78+ }79+ expect(caughtErr.code).toBe('commander.unknownCommand');80+ });81+82 test('when unknown subcommand then help suggestion includes command path', () => {83 const program = new commander.Command();84 program85 .exitOverride()12 unmodified linesmodified:tests/command.unknownOption.test.js+13 added
80 unmodified lines81 caughtErr = err;82 }83 expect(caughtErr.code).toBe('commander.unknownOption');84 });85+86+ test('when specify unknown option with simple program then error', () => {87+ const program = new commander.Command();88+ program89+ .exitOverride();90+ let caughtErr;91+ try {92+ program.parse(['node', 'test', '--NONSENSE']);93+ } catch (err) {94+ caughtErr = err;95+ }96+ expect(caughtErr.code).toBe('commander.unknownOption');97+ });98 });modified:index.js+14 added-4 removed
1473 unmodified lines1474 }1475 1476 outputHelpIfRequested(this, parsed.unknown);1477 this._checkForMissingMandatoryOptions();1478- if (parsed.unknown.length > 0) {1479- this.unknownOption(parsed.unknown[0]);1480- }1478 1479+ // We do not always call this check to avoid masking a "better" error, like unknown command.1480+ const checkForUnknownOptions = () => {1481+ if (parsed.unknown.length > 0) {1482+ this.unknownOption(parsed.unknown[0]);1483+ }1484+ };1485+1486 const commandEvent = `command:${this.name()}`;1487 if (this._actionHandler) {1488+ checkForUnknownOptions();1489 // Check expected arguments and collect variadic together.1490 const args = this.args.slice();1491 this._args.forEach((arg, i) => {1492 if (arg.required && args[i] == null) {9 unmodified lines1502 1503 this._actionHandler(args);1504 if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy1505 } else if (this.parent && this.parent.listenerCount(commandEvent)) {1506+ checkForUnknownOptions();1507 this.parent.emit(commandEvent, operands, unknown); // legacy1508 } else if (operands.length) {1503- if (this._findCommand('*')) { // legacy1509+ if (this._findCommand('*')) { // legacy default command1510 this._dispatchSubcommand('*', operands, unknown);1511 } else if (this.listenerCount('command:*')) {1512+ // skip option check, emit event for possible misspelling suggestion1513 this.emit('command:*', operands, unknown);1514 } else if (this.commands.length) {1515 this.unknownCommand();1516+ } else {1517+ checkForUnknownOptions();1518 }1519 } else if (this.commands.length) {1520 // This command has subcommands and nothing hooked up at this level, so display help.1521 this.help({ error: true });1522 } else {1523+ checkForUnknownOptions();1524 // fall through for caller to handle after calling .parse()1525 }1526 }1527 };690 unmodified lines