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
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
Provenance
- Commit
91ccfd5- Tree
e1fd0a7- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
2911e0e
9 files changed+449 added−3 removed
modified:lib/command.js+46 added-2 removed
5 unmodified lines6 const { Argument, humanReadableArgName } = require('./argument.js');7 const { CommanderError } = require('./error.js');8 const { Help } = require('./help.js');9 const { Option, splitOptionFlags } = require('./option.js');10+const { suggestSimilar } = require('./suggestSimilar');11 12 // @ts-check13 14 class Command extends EventEmitter {36 unmodified lines51 this._passThroughOptions = false;52 this._lifeCycleHooks = {}; // a hash of arrays53 /** @type {boolean | string} */54 this._showHelpAfterError = false;55+ this._showSuggestionAfterError = false;56 57 // see .configureOutput() for docs58 this._outputConfiguration = {59 writeOut: (str) => process.stdout.write(str),40 unmodified lines100 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;101 this._allowExcessArguments = sourceCommand._allowExcessArguments;102 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103 this._showHelpAfterError = sourceCommand._showHelpAfterError;104+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;105 106 return this;107 }108 127 unmodified lines236 return this;237 }238 239 /**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+ }249+250+ /**251 * Add a prepared subcommand.252 *253 * See .command() for creating an attached subcommand which inherits settings from its parent.254 *971 unmodified lines1226 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 lines1514 */1515 1516 unknownOption(flag) {1517 if (this._allowUnknownOption) return;1518+ let suggestion = '';1519+1520+ 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+ }1533+1503- const message = `error: unknown option '${flag}'`;1534+ const message = `error: unknown option '${flag}'${suggestion}`;1535 this._displayError(1, 'commander.unknownOption', message);1536 };1537 1538 /**19 unmodified lines1558 * @api private1559 */1560 1561 unknownCommand() {1531- const message = `error: unknown command '${this.args[0]}'`;1562+ const unknownName = this.args[0];1563+ let suggestion = '';1564+1565+ 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+ }1574+1575+ const message = `error: unknown command '${unknownName}'${suggestion}`;1576 this._displayError(1, 'commander.unknownCommand', message);1577 };1578 1579 /**345 unmodified linesadded:lib/suggestSimilar.js+100 added
1+const maxDistance = 3;2+3+function 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.)7+8+ // Quick early exit, return worst case.9+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);10+11+ // distance between prefix substrings of a and b12+ const d = [];13+14+ // 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+ }22+23+ // 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+ }43+44+ return d[a.length][b.length];45+}46+47+/**48+ * Find close matches, restricted to same number of edits.49+ *50+ * @param {string} word51+ * @param {string[]} candidates52+ * @returns {string}53+ */54+55+function suggestSimilar(word, candidates) {56+ if (!candidates || candidates.length === 0) return '';57+ // remove possible duplicates58+ candidates = Array.from(new Set(candidates));59+60+ const searchingOptions = word.startsWith('--');61+ if (searchingOptions) {62+ word = word.slice(2);63+ candidates = candidates.map(candidate => candidate.slice(2));64+ }65+66+ let similar = [];67+ let bestDistance = maxDistance;68+ const minSimilarity = 0.4;69+ candidates.forEach((candidate) => {70+ if (candidate.length <= 1) return; // no one character guesses71+72+ 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+ });85+86+ similar.sort((a, b) => a.localeCompare(b));87+ if (searchingOptions) {88+ similar = similar.map(candidate => `--${candidate}`);89+ }90+91+ 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+}99+100+exports.suggestSimilar = suggestSimilar;modified:tests/command.chain.test.js+6 added
182 unmodified linesExpand all1831841851861871881891901911921931941951963 unmodified lines182 unmodified linesExpand all const result = program.showHelpAfterError(); expect(result).toBe(program); });
test('when call .showSuggestionAfterError() then returns this', () => { const program = new Command(); const result = program.showSuggestionAfterError(); expect(result).toBe(program); });
test('when call .copyInheritedSettings() then returns this', () => { const program = new Command(); const cmd = new Command(); const result = cmd.copyInheritedSettings(program);3 unmodified linesadded:tests/command.showSuggestionAfterError.test.js+50 added
1+const { Command } = require('../');2+3+function getSuggestion(program, arg) {4+ let message = '';5+ program6+ .exitOverride()7+ .configureOutput({8+ writeErr: (str) => { message = str; }9+ });10+11+ try {12+ program.parse([arg], { from: 'user' });13+ } catch (err) {14+ }15+16+ const match = message.match(/Did you mean (one of )?(.*)\?/);17+ return match ? match[2] : null;18+};19+20+test('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+});27+28+test('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+});35+36+test('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+});43+44+test('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 lines94 caughtErr = err;95 }96 expect(caughtErr.code).toBe('commander.unknownOption');97 });98+99+ test('when specify unknown global option before subcommand then error', () => {100+ const program = new commander.Command();101+ program102+ .exitOverride();103+ program.command('sub');104+105+ 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
1+const { Command, Option } = require('../');2+3+// Note: setting up shared command configuration in getSuggestion,4+// and looking for possible subcommand 'sub'.5+6+function 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);17+18+ 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+ }24+25+ const match = message.match(/Did you mean (one of )?(.*)\?/);26+ return match ? match[2] : null;27+};28+29+test.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+});50+51+test('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+});58+59+test('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+});67+68+test('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+});77+78+test('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+});84+85+test('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+});92+93+test('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+});98+99+test('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+});105+106+test('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+});112+113+test('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+});122+123+// Easy to just run same tests as for commands with cut and paste!124+// Note: length calculations disregard the leading --125+test.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+});146+147+test('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+});155+156+test('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+});163+164+test('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+});171+172+test('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+});181+182+test('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+});190+191+test('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+});197+198+test('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+});204+205+test('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 lines411 * 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;416 417 /**418 * Display the help or a custom message after an error occurs.419 */420 showHelpAfterError(displayHelp?: boolean | string): this;421 422 /**423+ * Display suggestion of similar commands for unknown commands, or options for unknown options.424+ */425+ showSuggestionAfterError(displaySuggestion?: boolean): this;426+427+ /**428 * Register callback `fn` for the command.429 *430 * @example431 * ```338 unmodified linesmodified:typings/index.test-d.ts+4 added
291 unmodified lines292 expectType<commander.Command>(program.showHelpAfterError());293 expectType<commander.Command>(program.showHelpAfterError(true));294 expectType<commander.Command>(program.showHelpAfterError('See --help'));295 296+// showSuggestionAfterError297+expectType<commander.Command>(program.showSuggestionAfterError());298+expectType<commander.Command>(program.showSuggestionAfterError(false));299+300 // configureOutput301 expectType<commander.Command>(program.configureOutput({ }));302 expectType<commander.OutputConfiguration>(program.configureOutput());303 110 unmodified linesmodified:Readme.md+12 added
690 unmodified lines691 error: unknown option '--unknown'692 (add --help for additional information)693 ```694 695+You can also show suggestions after an error for an unknown command or option.696+697+```js698+program.showSuggestionAfterError();699+```700+701+```sh702+$ pizza --hepl703+error: unknown option '--hepl'704+(Did you mean --help?)705+```706+707 ### Display help from code708 709 `.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