Skip to content
Myr

Merge pull request #149 from fabianofranz/siblings

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

Allows command suggestions along with "unknown command" errors

authored by Eric Paris · committed by Eric Paris · parents b28774d, b4087da · 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
130 unmodified lines
131 t.Funcs(templateFuncs)132 template.Must(t.Parse(text))133 return t.Execute(w, data)134}135136// ld compares two strings and returns the levenshtein distance between them137func ld(s, t string, ignoreCase bool) int {138 if ignoreCase {139 s = strings.ToLower(s)140 t = strings.ToLower(t)141 }142 d := make([][]int, len(s)+1)143 for i := range d {144 d[i] = make([]int, len(t)+1)145 }146 for i := range d {147 d[i][0] = i148 }149 for j := range d[0] {150 d[0][j] = j151 }152 for j := 1; j <= len(t); j++ {153 for i := 1; i <= len(s); i++ {154 if s[i-1] == t[j-1] {155 d[i][j] = d[i-1][j-1]156 } else {157 min := d[i-1][j]158 if d[i][j-1] < min {159 min = d[i][j-1]160 }161 if d[i-1][j-1] < min {162 min = d[i-1][j-1]163 }164 d[i][j] = min + 1165 }166 }167168 }169 return d[len(s)][len(t)]170}
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.
307 unmodified lines
425 // no subcommand, always take args426 if !commandFound.HasSubCommands() {427 return commandFound, a, nil428 }429430 // root command with subcommands, do subcommand checking431 if commandFound == c && len(argsWOflags) > 0 {426 return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())432 suggestions := ""433 if !c.DisableSuggestions {434 if c.SuggestionsMinimumDistance <= 0 {435 c.SuggestionsMinimumDistance = 2436 }437 similar := []string{}438 for _, cmd := range c.commands {439 if cmd.IsAvailableCommand() {440 levenshtein := ld(argsWOflags[0], cmd.Name(), true)441 if levenshtein <= c.SuggestionsMinimumDistance {442 similar = append(similar, cmd.Name())443 }444 }445 }446 if len(similar) > 0 {447 suggestions += "\n\nDid you mean this?\n"448 for _, s := range similar {449 suggestions += fmt.Sprintf("\t%v\n", s)450 }451 }452 }453 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestions)454 }455456 return commandFound, a, nil457}
685 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