Skip to content
Myr

Suggestion for unknown command and unknown option (#1590)

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

* Proof of concept suggestion for unknown command * Leave length check to similarity test * Fix JSDoc * Add tests * Fix import * Offer multiple suggestions * Add search for similar option * Add global options to suggestions * Show unknown (global) option rather than help * Add tests for help command and option suggestions * Fix option suggestions for subcommands, and first raft of tests for option suggestions * Do not suggest hidden candidates. Remove duplicates. * Tiny comment change * Add test for fixed behaviour, unknown option before subcommand * Remove low value local variable * Suppress output from test * Add showSuggestionAfterError * Fix arg for parse * Suggestions off by default for now * Add to README * Remove development trace statement * Describe scenario using same terms as error * Add test that command:* listener blocks command suggestion

authored by John Gee · committed by GitHub · parent 2911e0e · Browse files · 9 files+449 added−3 removed
This commit

State

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

Diff stats

9 files+449 added−3 removed

  • tests:+281 added−0 removed
  • other:+168 added−3 removed

9 files+449 added−3 removed

modified:lib/command.js+46 added-2 removed
5 unmodified lines
6const { Argument, humanReadableArgName } = require('./argument.js');7const { CommanderError } = require('./error.js');8const { Help } = require('./help.js');9const { Option, splitOptionFlags } = require('./option.js');10const { suggestSimilar } = require('./suggestSimilar');1112// @ts-check1314class Command extends EventEmitter {
36 unmodified lines
51 this._passThroughOptions = false;52 this._lifeCycleHooks = {}; // a hash of arrays53 /** @type {boolean | string} */54 this._showHelpAfterError = false;55 this._showSuggestionAfterError = false;5657 // see .configureOutput() for docs58 this._outputConfiguration = {59 writeOut: (str) => process.stdout.write(str),
40 unmodified lines
100 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;101 this._allowExcessArguments = sourceCommand._allowExcessArguments;102 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103 this._showHelpAfterError = sourceCommand._showHelpAfterError;104 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;105106 return this;107 }108
127 unmodified lines
236 return this;237 }238239 /**240 * Display suggestion of similar commands for unknown commands, or options for unknown options.241 *242 * @param {boolean} [displaySuggestion]243 * @return {Command} `this` command for chaining244 */245 showSuggestionAfterError(displaySuggestion = true) {246 this._showSuggestionAfterError = !!displaySuggestion;247 return this;248 }249250 /**251 * Add a prepared subcommand.252 *253 * See .command() for creating an attached subcommand which inherits settings from its parent.254 *
971 unmodified lines
1226 checkForUnknownOptions();1227 this._processArguments();1228 }1229 } else if (this.commands.length) {1230 checkForUnknownOptions();1231 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1232 this.help({ error: true });1233 } else {1234 checkForUnknownOptions();
279 unmodified lines
1514 */15151516 unknownOption(flag) {1517 if (this._allowUnknownOption) return;1518 let suggestion = '';15191520 if (flag.startsWith('--') && this._showSuggestionAfterError) {1521 // Looping to pick up the global options too1522 let candidateFlags = [];1523 let command = this;1524 do {1525 const moreFlags = command.createHelp().visibleOptions(command)1526 .filter(option => option.long)1527 .map(option => option.long);1528 candidateFlags = candidateFlags.concat(moreFlags);1529 command = command.parent;1530 } while (command && !command._enablePositionalOptions);1531 suggestion = suggestSimilar(flag, candidateFlags);1532 }15331503 const message = `error: unknown option '${flag}'`;1534 const message = `error: unknown option '${flag}'${suggestion}`;1535 this._displayError(1, 'commander.unknownOption', message);1536 };15371538 /**
19 unmodified lines
1558 * @api private1559 */15601561 unknownCommand() {1531 const message = `error: unknown command '${this.args[0]}'`;1562 const unknownName = this.args[0];1563 let suggestion = '';15641565 if (this._showSuggestionAfterError) {1566 const candidateNames = [];1567 this.createHelp().visibleCommands(this).forEach((command) => {1568 candidateNames.push(command.name());1569 // just visible alias1570 if (command.alias()) candidateNames.push(command.alias());1571 });1572 suggestion = suggestSimilar(unknownName, candidateNames);1573 }15741575 const message = `error: unknown command '${unknownName}'${suggestion}`;1576 this._displayError(1, 'commander.unknownCommand', message);1577 };15781579 /**
345 unmodified lines
added:lib/suggestSimilar.js+100 added
1const maxDistance = 3;23function editDistance(a, b) {4 // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance5 // Calculating optimal string alignment distance, no substring is edited more than once.6 // (Simple implementation.)78 // Quick early exit, return worst case.9 if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);1011 // distance between prefix substrings of a and b12 const d = [];1314 // pure deletions turn a into empty string15 for (let i = 0; i <= a.length; i++) {16 d[i] = [i];17 }18 // pure insertions turn empty string into b19 for (let j = 0; j <= b.length; j++) {20 d[0][j] = j;21 }2223 // fill matrix24 for (let j = 1; j <= b.length; j++) {25 for (let i = 1; i <= a.length; i++) {26 let cost = 1;27 if (a[i - 1] === b[j - 1]) {28 cost = 0;29 } else {30 cost = 1;31 }32 d[i][j] = Math.min(33 d[i - 1][j] + 1, // deletion34 d[i][j - 1] + 1, // insertion35 d[i - 1][j - 1] + cost // substitution36 );37 // transposition38 if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {39 d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);40 }41 }42 }4344 return d[a.length][b.length];45}4647/**48 * Find close matches, restricted to same number of edits.49 *50 * @param {string} word51 * @param {string[]} candidates52 * @returns {string}53 */5455function suggestSimilar(word, candidates) {56 if (!candidates || candidates.length === 0) return '';57 // remove possible duplicates58 candidates = Array.from(new Set(candidates));5960 const searchingOptions = word.startsWith('--');61 if (searchingOptions) {62 word = word.slice(2);63 candidates = candidates.map(candidate => candidate.slice(2));64 }6566 let similar = [];67 let bestDistance = maxDistance;68 const minSimilarity = 0.4;69 candidates.forEach((candidate) => {70 if (candidate.length <= 1) return; // no one character guesses7172 const distance = editDistance(word, candidate);73 const length = Math.max(word.length, candidate.length);74 const similarity = (length - distance) / length;75 if (similarity > minSimilarity) {76 if (distance < bestDistance) {77 // better edit distance, throw away previous worse matches78 bestDistance = distance;79 similar = [candidate];80 } else if (distance === bestDistance) {81 similar.push(candidate);82 }83 }84 });8586 similar.sort((a, b) => a.localeCompare(b));87 if (searchingOptions) {88 similar = similar.map(candidate => `--${candidate}`);89 }9091 if (similar.length > 1) {92 return `\n(Did you mean one of ${similar.join(', ')}?)`;93 }94 if (similar.length === 1) {95 return `\n(Did you mean ${similar[0]}?)`;96 }97 return '';98}99100exports.suggestSimilar = suggestSimilar;
modified:tests/command.chain.test.js+6 added
added:tests/command.showSuggestionAfterError.test.js+50 added
1const { Command } = require('../');23function getSuggestion(program, arg) {4 let message = '';5 program6 .exitOverride()7 .configureOutput({8 writeErr: (str) => { message = str; }9 });1011 try {12 program.parse([arg], { from: 'user' });13 } catch (err) {14 }1516 const match = message.match(/Did you mean (one of )?(.*)\?/);17 return match ? match[2] : null;18};1920test('when unknown command and showSuggestionAfterError() then show suggestion', () => {21 const program = new Command();22 program.showSuggestionAfterError();23 program.command('example');24 const suggestion = getSuggestion(program, 'exampel');25 expect(suggestion).toBe('example');26});2728test('when unknown command and showSuggestionAfterError(false) then do not show suggestion', () => {29 const program = new Command();30 program.showSuggestionAfterError(false);31 program.command('example');32 const suggestion = getSuggestion(program, 'exampel');33 expect(suggestion).toBe(null);34});3536test('when unknown option and showSuggestionAfterError() then show suggestion', () => {37 const program = new Command();38 program.showSuggestionAfterError();39 program.option('--example');40 const suggestion = getSuggestion(program, '--exampel');41 expect(suggestion).toBe('--example');42});4344test('when unknown option and showSuggestionAfterError(false) then do not show suggestion', () => {45 const program = new Command();46 program.showSuggestionAfterError(false);47 program.option('--example');48 const suggestion = getSuggestion(program, '--exampel');49 expect(suggestion).toBe(null);50});
modified:tests/command.unknownOption.test.js+15 added
93 unmodified lines
94 caughtErr = err;95 }96 expect(caughtErr.code).toBe('commander.unknownOption');97 });9899 test('when specify unknown global option before subcommand then error', () => {100 const program = new commander.Command();101 program102 .exitOverride();103 program.command('sub');104105 let caughtErr;106 try {107 program.parse(['--NONSENSE', 'sub'], { from: 'user' });108 } catch (err) {109 caughtErr = err;110 }111 expect(caughtErr.code).toBe('commander.unknownOption');112 });113});
added:tests/help.suggestion.test.js+210 added
1const { Command, Option } = require('../');23// Note: setting up shared command configuration in getSuggestion,4// and looking for possible subcommand 'sub'.56function getSuggestion(program, arg) {7 let message = '';8 program9 .showSuggestionAfterError() // make sure on10 .exitOverride()11 .configureOutput({12 writeErr: (str) => { message = str; }13 });14 // Do the same setup for subcommand.15 const sub = program._findCommand('sub');16 if (sub) sub.copyInheritedSettings(program);1718 try {19 // Passing in an array for a few of the tests.20 const args = Array.isArray(arg) ? arg : [arg];21 program.parse(args, { from: 'user' });22 } catch (err) {23 }2425 const match = message.match(/Did you mean (one of )?(.*)\?/);26 return match ? match[2] : null;27};2829test.each([30 ['yyy', ['zzz'], null, 'none similar'],31 ['a', ['b'], null, 'one edit away but not similar'],32 ['a', ['ab'], 'ab', 'one edit away'],33 ['ab', ['a'], null, 'one edit away'],34 ['at', ['cat'], 'cat', '1 insertion'],35 ['cat', ['at'], 'at', '1 deletion'],36 ['bat', ['cat'], 'cat', '1 substitution'],37 ['act', ['cat'], 'cat', '1 transposition'],38 ['cxx', ['cat'], null, '2 edits away and short string'],39 ['caxx', ['cart'], 'cart', '2 edits away and longer string'],40 ['1234567', ['1234567890'], '1234567890', '3 edits away is similar for long string'],41 ['123456', ['1234567890'], null, '4 edits is too far'],42 ['xat', ['rat', 'cat', 'bat'], 'bat, cat, rat', 'sorted possibles'],43 ['cart', ['camb', 'cant', 'bard'], 'cant', 'only closest of different edit distances']44])('when cli of %s and commands %j then suggest %s because %s', (arg, commandNames, expected) => {45 const program = new Command();46 commandNames.forEach(name => { program.command(name); });47 const suggestion = getSuggestion(program, arg);48 expect(suggestion).toBe(expected);49});5051test('when similar alias then suggest alias', () => {52 const program = new Command();53 program.command('xyz')54 .alias('car');55 const suggestion = getSuggestion(program, 'bar');56 expect(suggestion).toBe('car');57});5859test('when similar hidden alias then not suggested', () => {60 const program = new Command();61 program.command('xyz')62 .alias('visible')63 .alias('silent');64 const suggestion = getSuggestion(program, 'slent');65 expect(suggestion).toBe(null);66});6768test('when similar command and alias then suggest both', () => {69 const program = new Command();70 program.command('aaaaa')71 .alias('cat');72 program.command('bat');73 program.command('ccccc');74 const suggestion = getSuggestion(program, 'mat');75 expect(suggestion).toBe('bat, cat');76});7778test('when implicit help command then help is candidate for suggestion', () => {79 const program = new Command();80 program.command('sub');81 const suggestion = getSuggestion(program, 'hepl');82 expect(suggestion).toBe('help');83});8485test('when help command disabled then not candidate for suggestion', () => {86 const program = new Command();87 program.addHelpCommand(false);88 program.command('sub');89 const suggestion = getSuggestion(program, 'hepl');90 expect(suggestion).toBe(null);91});9293test('when default help option then --help is candidate for suggestion', () => {94 const program = new Command();95 const suggestion = getSuggestion(program, '--hepl');96 expect(suggestion).toBe('--help');97});9899test('when custom help option then --custom-help is candidate for suggestion', () => {100 const program = new Command();101 program.helpOption('-H, --custom-help');102 const suggestion = getSuggestion(program, '--custom-hepl');103 expect(suggestion).toBe('--custom-help');104});105106test('when help option disabled then not candidate for suggestion', () => {107 const program = new Command();108 program.helpOption(false);109 const suggestion = getSuggestion(program, '--hepl');110 expect(suggestion).toBe(null);111});112113test('when command:* listener and unknown command then no suggestion', () => {114 // Because one use for command:* was to handle unknown commands.115 // Listener actually stops error being thrown, but we just care about affect on suggestion in this test.116 const program = new Command();117 program.on('command:*', () => {});118 program.command('rat');119 const suggestion = getSuggestion(program, 'cat');120 expect(suggestion).toBe(null);121});122123// Easy to just run same tests as for commands with cut and paste!124// Note: length calculations disregard the leading --125test.each([126 ['--yyy', ['--zzz'], null, 'none similar'],127 ['--a', ['--b'], null, 'one edit away but not similar'],128 ['--a', ['--ab'], '--ab', 'one edit away'],129 ['--ab', ['--a'], null, 'one edit away'],130 ['--at', ['--cat'], '--cat', '1 insertion'],131 ['--cat', ['--at'], '--at', '1 deletion'],132 ['--bat', ['--cat'], '--cat', '1 substitution'],133 ['--act', ['--cat'], '--cat', '1 transposition'],134 ['--cxx', ['--cat'], null, '2 edits away and short string'],135 ['--caxx', ['--cart'], '--cart', '2 edits away and longer string'],136 ['--1234567', ['--1234567890'], '--1234567890', '3 edits away is similar for long string'],137 ['--123456', ['--1234567890'], null, '4 edits is too far'],138 ['--xat', ['--rat', '--cat', '--bat'], '--bat, --cat, --rat', 'sorted possibles'],139 ['--cart', ['--camb', '--cant', '--bard'], '--cant', 'only closest of different edit distances']140])('when cli of %s and options %j then suggest %s because %s', (arg, commandNames, expected) => {141 const program = new Command();142 commandNames.forEach(name => { program.option(name); });143 const suggestion = getSuggestion(program, arg);144 expect(suggestion).toBe(expected);145});146147test('when no options then no suggestion', () => {148 // Checking nothing blows up as much as no suggestion!149 const program = new Command();150 program151 .helpOption(false);152 const suggestion = getSuggestion(program, '--option');153 expect(suggestion).toBe(null);154});155156test('when subcommand option then candidate for subcommand option suggestion', () => {157 const program = new Command();158 program.command('sub')159 .option('-l,--local');160 const suggestion = getSuggestion(program, ['sub', '--loca']);161 expect(suggestion).toBe('--local');162});163164test('when global option then candidate for subcommand option suggestion', () => {165 const program = new Command();166 program.option('-g, --global');167 program.command('sub');168 const suggestion = getSuggestion(program, ['sub', '--globla']);169 expect(suggestion).toBe('--global');170});171172test('when global option but positionalOptions then not candidate for subcommand suggestion', () => {173 const program = new Command();174 program175 .enablePositionalOptions();176 program.option('-g, --global');177 program.command('sub');178 const suggestion = getSuggestion(program, ['sub', '--globla']);179 expect(suggestion).toBe(null);180});181182test('when global and local options then both candidates', () => {183 const program = new Command();184 program.option('--cat');185 program.command('sub')186 .option('--rat');187 const suggestion = getSuggestion(program, ['sub', '--bat']);188 expect(suggestion).toBe('--cat, --rat');189});190191test('when command hidden then not suggested as candidate', () => {192 const program = new Command();193 program.command('secret', { hidden: true });194 const suggestion = getSuggestion(program, 'secrt');195 expect(suggestion).toBe(null);196});197198test('when option hidden then not suggested as candidate', () => {199 const program = new Command();200 program.addOption(new Option('--secret').hideHelp());201 const suggestion = getSuggestion(program, '--secrt');202 expect(suggestion).toBe(null);203});204205test('when may be duplicate identical candidates then only return one', () => {206 const program = new Command();207 program.command('sub');208 const suggestion = getSuggestion(program, ['sub', '--hepl']);209 expect(suggestion).toBe('--help');210});
modified:typings/index.d.ts+6 added-1 removed
410 unmodified lines
411 * Copy settings that are useful to have in common across root command and subcommands.412 *413 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)414 */415 copyInheritedSettings(sourceCommand: Command): this;415 copyInheritedSettings(sourceCommand: Command): this;416417 /**418 * Display the help or a custom message after an error occurs.419 */420 showHelpAfterError(displayHelp?: boolean | string): this;421422 /**423 * Display suggestion of similar commands for unknown commands, or options for unknown options.424 */425 showSuggestionAfterError(displaySuggestion?: boolean): this;426427 /**428 * Register callback `fn` for the command.429 *430 * @example431 * ```
338 unmodified lines
modified:typings/index.test-d.ts+4 added
291 unmodified lines
292expectType<commander.Command>(program.showHelpAfterError());293expectType<commander.Command>(program.showHelpAfterError(true));294expectType<commander.Command>(program.showHelpAfterError('See --help'));295296// showSuggestionAfterError297expectType<commander.Command>(program.showSuggestionAfterError());298expectType<commander.Command>(program.showSuggestionAfterError(false));299300// configureOutput301expectType<commander.Command>(program.configureOutput({ }));302expectType<commander.OutputConfiguration>(program.configureOutput());303
110 unmodified lines
modified:Readme.md+12 added
690 unmodified lines
691error: unknown option '--unknown'692(add --help for additional information)693```694695You can also show suggestions after an error for an unknown command or option.696697```js698program.showSuggestionAfterError();699```700701```sh702$ pizza --hepl703error: unknown option '--hepl'704(Did you mean --help?)705```706707### Display help from code708709`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.710
311 unmodified lines