Merge pull request #163 from fabianofranz/siblings_improvements
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Improve suggestions
authored by Eric Paris · committed by Eric Paris · parents 53d9650, a83a172 · Browse files · 3 files·+68 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+68 added−31 removed
- other:+68 added−31 removed
Provenance
- Commit
046a673- Tree
0128820- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
53d9650- Parent 2
a83a172
3 files changed+68 added−31 removed
modified:cobra_test.go+28 added-16 removed
80 unmodified lines81 },82 }83 84 var cmdTimes = &Command{85- Use: "times [# times] [string to echo]",86- Short: "Echo anything to the screen more times",87- Long: `a slightly useless command for testing.`,85+ Use: "times [# times] [string to echo]",86+ SuggestFor: []string{"counts"},87+ Short: "Echo anything to the screen more times",88+ Long: `a slightly useless command for testing.`,89 PersistentPreRun: func(cmd *Command, args []string) {90 timesPersPre = args91 },92 Run: func(cmd *Command, args []string) {723 unmodified lines816 cmd := initializeWithRootCmd()817 cmd.AddCommand(cmdTimes)818 819 tests := map[string]string{819- "time": "times",820- "tiems": "times",821- "timeS": "times",822- "rimes": "times",820+ "time": "times",821+ "tiems": "times",822+ "tims": "times",823+ "timeS": "times",824+ "rimes": "times",825+ "ti": "times",826+ "t": "times",827+ "timely": "times",828+ "ri": "",829+ "timezone": "",830+ "foo": "",831+ "counts": "times",832 }833 834 for typo, suggestion := range tests {826- cmd.DisableSuggestions = false827- result := simpleTester(cmd, typo)828- if expected := fmt.Sprintf(outputWithSuggestions, typo, suggestion); result.Output != expected {829- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)835+ for _, suggestionsDisabled := range []bool{false, true} {836+ cmd.DisableSuggestions = suggestionsDisabled837+ result := simpleTester(cmd, typo)838+ expected := ""839+ if len(suggestion) == 0 || suggestionsDisabled {840+ expected = fmt.Sprintf(outputWithoutSuggestions, typo)841+ } else {842+ expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)843+ }844+ if result.Output != expected {845+ t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)846+ }847 }831- cmd.DisableSuggestions = true832- result = simpleTester(cmd, typo)833- if expected := fmt.Sprintf(outputWithoutSuggestions, typo); result.Output != expected {834- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)835- }848 }849 }850 851 func TestFlagsBeforeCommand(t *testing.T) {207 unmodified linesmodified:command.go+28 added-15 removed
37 unmodified lines38 // The one-line usage message.39 Use string40 // An array of aliases that can be used instead of the first word in Use.41 Aliases []string42+ // An array of command names for which this command will be suggested - similar to aliases but only suggests.43+ SuggestFor []string44 // The short description shown in the 'help' output.45 Short string46 // The long message shown in the 'help <this-command>' output.47 Long string382 unmodified lines430 }431 432 // root command with subcommands, do subcommand checking433 if commandFound == c && len(argsWOflags) > 0 {432- suggestions := ""434+ suggestionsString := ""435 if !c.DisableSuggestions {436 if c.SuggestionsMinimumDistance <= 0 {437 c.SuggestionsMinimumDistance = 2438 }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- }439+ if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {440+ suggestionsString += "\n\nDid you mean this?\n"441+ for _, s := range suggestions {442+ suggestionsString += fmt.Sprintf("\t%v\n", s)443 }444 }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- }445 }453- return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestions)446+ return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)447 }448 449 return commandFound, a, nil450 }451 452+func (c *Command) SuggestionsFor(typedName string) []string {453+ suggestions := []string{}454+ for _, cmd := range c.commands {455+ if cmd.IsAvailableCommand() {456+ levenshteinDistance := ld(typedName, cmd.Name(), true)457+ suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance458+ suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))459+ if suggestByLevenshtein || suggestByPrefix {460+ suggestions = append(suggestions, cmd.Name())461+ }462+ for _, explicitSuggestion := range cmd.SuggestFor {463+ if strings.EqualFold(typedName, explicitSuggestion) {464+ suggestions = append(suggestions, cmd.Name())465+ }466+ }467+ }468+ }469+ return suggestions470+}471+472 func (c *Command) Root() *Command {473 var findRoot func(*Command) *Command474 475 findRoot = func(x *Command) *Command {684 unmodified linesmodified:README.md+12 added
440 unmodified lines441 or 442 443 command.SuggestionsMinimumDistance = 1444 445+You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:446+447+```448+$ hugo delete449+unknown command "delete" for "hugo"450+451+Did you mean this?452+ remove453+454+Run 'hugo --help' for usage.455+```456+457 ## Generating markdown formatted documentation for your command458 459 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)460 65 unmodified lines