Skip to content
Myr

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

4 files+116 added−1 removed

modified:cobra_test.go+28 added
797 unmodified lines
798 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)799 }800}801802func 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"805806 cmd := initializeWithRootCmd()807 cmd.AddCommand(cmdTimes)808809 tests := map[string]string{810 "time": "times",811 "tiems": "times",812 "timeS": "times",813 "rimes": "times",814 }815816 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}829830func TestFlagsBeforeCommand(t *testing.T) {831 // short without space832 x := fullSetupTest("-i10 echo")833 if x.Error != nil {
204 unmodified lines
modified:cobra.go+36 added
124 unmodified lines
125 t.Funcs(templateFuncs)126 template.Must(t.Parse(text))127 return t.Execute(w, data)128}129130// ld compares two strings and returns the levenshtein distance between them131func 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 }161162 }163 return d[len(s)][len(t)]164}
modified:command.go+28 added-1 removed
104 unmodified lines
105 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.NormalizedName109110 // 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}115116// os.Args[1:] by default, if desired, can be overridden117// particularly useful when testing.
305 unmodified lines
423 // no subcommand, always take args424 if !commandFound.HasSubCommands() {425 return commandFound, a, nil426 }427428 // 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 }453454 return commandFound, a, nil455}
681 unmodified lines
modified:README.md+24 added
416 unmodified lines
417 _ = rootCmd.Execute()418}419```420421## Suggestions when "unknown command" happens422423Cobra 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:424425```426$ hugo srever427unknown command "srever" for "hugo"428429Did you mean this?430 server431432Run 'hugo --help' for usage.433```434435Suggestions 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.436437If you need to disable suggestions or tweak the string distance in your command, use:438439 command.DisableSuggestions = true440441or 442443 command.SuggestionsMinimumDistance = 1444445## Generating markdown formatted documentation for your command446447Cobra 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