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
Provenance
- Commit
6d70311- Tree
8e07246- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
b28774d- Parent 2
b4087da
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
130 unmodified lines131 t.Funcs(templateFuncs)132 template.Must(t.Parse(text))133 return t.Execute(w, data)134 }135+136+// ld compares two strings and returns the levenshtein distance between them137+func 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+ }167+168+ }169+ return d[len(s)][len(t)]170+}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.307 unmodified lines425 // no subcommand, always take args426 if !commandFound.HasSubCommands() {427 return commandFound, a, nil428 }429+430 // 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 }455 456 return commandFound, a, nil457 }685 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