Allows command suggestions along with "unknown command" errors
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Fabiano Franz · committed by Fabiano Franz · parent 4b86c66 · Browse files · 4 files·+116 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+116 added−1 removed
- other:+116 added−1 removed
Provenance
- Commit
b4087da- Tree
7ad3435- Author
Fabiano Franz <ffranz@redhat.com>- Committer
Fabiano Franz <ffranz@redhat.com>- Parent
4b86c66
4 files changed+116 added−1 removed
modified:cobra_test.go+28 added
797 unmodified lines798 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)799 }800 }801 802+func TestRootSuggestions(t *testing.T) {803+ outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"804+ outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"805+806+ cmd := initializeWithRootCmd()807+ cmd.AddCommand(cmdTimes)808+809+ tests := map[string]string{810+ "time": "times",811+ "tiems": "times",812+ "timeS": "times",813+ "rimes": "times",814+ }815+816+ for typo, suggestion := range tests {817+ cmd.DisableSuggestions = false818+ result := simpleTester(cmd, typo)819+ if expected := fmt.Sprintf(outputWithSuggestions, typo, suggestion); result.Output != expected {820+ t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)821+ }822+ cmd.DisableSuggestions = true823+ result = simpleTester(cmd, typo)824+ if expected := fmt.Sprintf(outputWithoutSuggestions, typo); result.Output != expected {825+ t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)826+ }827+ }828+}829+830 func TestFlagsBeforeCommand(t *testing.T) {831 // short without space832 x := fullSetupTest("-i10 echo")833 if x.Error != nil {204 unmodified linesmodified:cobra.go+36 added
124 unmodified lines125 t.Funcs(templateFuncs)126 template.Must(t.Parse(text))127 return t.Execute(w, data)128 }129+130+// ld compares two strings and returns the levenshtein distance between them131+func ld(s, t string, ignoreCase bool) int {132+ if ignoreCase {133+ s = strings.ToLower(s)134+ t = strings.ToLower(t)135+ }136+ d := make([][]int, len(s)+1)137+ for i := range d {138+ d[i] = make([]int, len(t)+1)139+ }140+ for i := range d {141+ d[i][0] = i142+ }143+ for j := range d[0] {144+ d[0][j] = j145+ }146+ for j := 1; j <= len(t); j++ {147+ for i := 1; i <= len(s); i++ {148+ if s[i-1] == t[j-1] {149+ d[i][j] = d[i-1][j-1]150+ } else {151+ min := d[i-1][j]152+ if d[i][j-1] < min {153+ min = d[i][j-1]154+ }155+ if d[i-1][j-1] < min {156+ min = d[i-1][j-1]157+ }158+ d[i][j] = min + 1159+ }160+ }161+162+ }163+ return d[len(s)][len(t)]164+}modified:command.go+28 added-1 removed
104 unmodified lines105 helpFunc func(*Command, []string) // Help can be defined by application106 helpCommand *Command // The help command107 // The global normalization function that we can use on every pFlag set and children commands108 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName109+110+ // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages111+ DisableSuggestions bool112+ // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0113+ SuggestionsMinimumDistance int114 }115 116 // os.Args[1:] by default, if desired, can be overridden117 // particularly useful when testing.305 unmodified lines423 // no subcommand, always take args424 if !commandFound.HasSubCommands() {425 return commandFound, a, nil426 }427+428 // root command with subcommands, do subcommand checking429 if commandFound == c && len(argsWOflags) > 0 {424- return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())430+ suggestions := ""431+ if !c.DisableSuggestions {432+ if c.SuggestionsMinimumDistance <= 0 {433+ c.SuggestionsMinimumDistance = 2434+ }435+ similar := []string{}436+ for _, cmd := range c.commands {437+ if cmd.IsAvailableCommand() {438+ levenshtein := ld(argsWOflags[0], cmd.Name(), true)439+ if levenshtein <= c.SuggestionsMinimumDistance {440+ similar = append(similar, cmd.Name())441+ }442+ }443+ }444+ if len(similar) > 0 {445+ suggestions += "\n\nDid you mean this?\n"446+ for _, s := range similar {447+ suggestions += fmt.Sprintf("\t%v\n", s)448+ }449+ }450+ }451+ return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestions)452 }453 454 return commandFound, a, nil455 }681 unmodified linesmodified:README.md+24 added
416 unmodified lines417 _ = rootCmd.Execute()418 }419 ```420 421+## Suggestions when "unknown command" happens422+423+Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behavior similarly to the `git` command when a typo happens. For example:424+425+```426+$ hugo srever427+unknown command "srever" for "hugo"428+429+Did you mean this?430+ server431+432+Run 'hugo --help' for usage.433+```434+435+Suggestions are automatic based on every subcommand registered and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.436+437+If you need to disable suggestions or tweak the string distance in your command, use:438+439+ command.DisableSuggestions = true440+441+or 442+443+ command.SuggestionsMinimumDistance = 1444+445 ## Generating markdown formatted documentation for your command446 447 Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md)448 65 unmodified lines