Skip to content

Commit 002bde2

Browse files
committed
Add suggestions support
The new option `app.Suggest` enables command and flag suggestions via the jaro-winkler distance algorithm. Flags are scoped to their appropriate commands whereas command suggestions are scoped to the current command level. Signed-off-by: Sascha Grunert <[email protected]>
1 parent 1b7e4e0 commit 002bde2

9 files changed

Lines changed: 257 additions & 8 deletions

File tree

‎app.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ type App struct {
8888
// single-character bool arguments into one
8989
// i.e. foobar -o -v -> foobar -ov
9090
UseShortOptionHandling bool
91+
// Enable suggestions for commands and flags
92+
Suggest bool
9193

9294
didSetup bool
9395
}
@@ -250,6 +252,11 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
250252
return err
251253
}
252254
_, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
255+
if a.Suggest {
256+
if suggestion, err := a.suggestFlagFromError(err, ""); err == nil {
257+
fmt.Fprintf(a.Writer, suggestion)
258+
}
259+
}
253260
_ = ShowAppHelp(context)
254261
return err
255262
}
@@ -381,6 +388,11 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
381388
return err
382389
}
383390
_, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
391+
if a.Suggest {
392+
if suggestion, err := a.suggestFlagFromError(err, context.Command.Name); err == nil {
393+
fmt.Fprintf(a.Writer, suggestion)
394+
}
395+
}
384396
_ = ShowSubcommandHelp(context)
385397
return err
386398
}

‎command.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@ func (c *Command) Run(ctx *Context) (err error) {
116116
}
117117
_, _ = fmt.Fprintln(context.App.Writer, "Incorrect Usage:", err.Error())
118118
_, _ = fmt.Fprintln(context.App.Writer)
119+
if ctx.App.Suggest {
120+
if suggestion, err := ctx.App.suggestFlagFromError(err, c.Name); err == nil {
121+
fmt.Fprintf(context.App.Writer, suggestion)
122+
}
123+
}
119124
_ = ShowCommandHelp(context, c.Name)
120125
return err
121126
}
@@ -244,6 +249,7 @@ func (c *Command) startApp(ctx *Context) error {
244249
app.ErrWriter = ctx.App.ErrWriter
245250
app.ExitErrHandler = ctx.App.ExitErrHandler
246251
app.UseShortOptionHandling = ctx.App.UseShortOptionHandling
252+
app.Suggest = ctx.App.Suggest
247253

248254
app.categories = newCommandCategories()
249255
for _, command := range c.Subcommands {

‎docs/v2/manual.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ cli v2 manual
3434
* [Version Flag](#version-flag)
3535
+ [Customization](#customization-2)
3636
* [Timestamp Flag](#timestamp-flag)
37+
* [Suggestions](#suggestions)
3738
* [Full API Example](#full-api-example)
3839

3940
<!-- tocstop -->
@@ -1426,6 +1427,13 @@ In this example the flag could be used like this :
14261427

14271428
Side note: quotes may be necessary around the date depending on your layout (if you have spaces for instance)
14281429

1430+
### Suggestions
1431+
1432+
To enable flag and command suggestions, set `app.Suggest = true`. If the suggest
1433+
feature is enabled, then the help output of the corresponding command will
1434+
provide an appropriate suggestion for the provided flag or subcommand if
1435+
available.
1436+
14291437
### Full API Example
14301438

14311439
**Notice**: This is a contrived (functioning) example meant strictly for API

‎go.mod‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.11
44

55
require (
66
github.com/BurntSushi/toml v0.3.1
7+
github.com/antzucaro/matchr v0.0.0-20180616170659-cbc221335f3c
78
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d
89
gopkg.in/yaml.v2 v2.2.2
910
)

‎go.sum‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
22
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3+
github.com/antzucaro/matchr v0.0.0-20180616170659-cbc221335f3c h1:CucViv7orgFBMkehuFFdkCVF5ERovbkRRyhvaYaHu/k=
4+
github.com/antzucaro/matchr v0.0.0-20180616170659-cbc221335f3c/go.mod h1:bV/CkX4+ANGDaBwbHkt9kK287al/i9BsB18PRBvyqYo=
35
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
46
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
57
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=

‎help.go‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,14 @@ import (
1010
"unicode/utf8"
1111
)
1212

13+
const (
14+
helpName = "help"
15+
helpAlias = "h"
16+
)
17+
1318
var helpCommand = &Command{
14-
Name: "help",
15-
Aliases: []string{"h"},
19+
Name: helpName,
20+
Aliases: []string{helpAlias},
1621
Usage: "Shows a list of commands or help for one command",
1722
ArgsUsage: "[command]",
1823
Action: func(c *Context) error {
@@ -27,8 +32,8 @@ var helpCommand = &Command{
2732
}
2833

2934
var helpSubcommand = &Command{
30-
Name: "help",
31-
Aliases: []string{"h"},
35+
Name: helpName,
36+
Aliases: []string{helpAlias},
3237
Usage: "Shows a list of commands or help for one command",
3338
ArgsUsage: "[command]",
3439
Action: func(c *Context) error {
@@ -207,7 +212,13 @@ func ShowCommandHelp(ctx *Context, command string) error {
207212
}
208213

209214
if ctx.App.CommandNotFound == nil {
210-
return Exit(fmt.Sprintf("No help topic for '%v'", command), 3)
215+
errMsg := fmt.Sprintf("No help topic for '%v'", command)
216+
if ctx.App.Suggest {
217+
if suggestion := suggestCommand(ctx.App.Commands, command); suggestion != "" {
218+
errMsg += ". " + suggestion
219+
}
220+
}
221+
return Exit(errMsg, 3)
211222
}
212223

213224
ctx.App.CommandNotFound(ctx, command)

‎parse.go‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,8 @@ func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComple
2626
return err
2727
}
2828

29-
errStr := err.Error()
30-
trimmed := strings.TrimPrefix(errStr, "flag provided but not defined: -")
31-
if errStr == trimmed {
29+
trimmed, trimErr := flagFromError(err)
30+
if trimErr != nil {
3231
return err
3332
}
3433

@@ -67,6 +66,19 @@ func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComple
6766
}
6867
}
6968

69+
const providedButNotDefinedErrMsg = "flag provided but not defined: -"
70+
71+
// flagFromError tries to parse a provided flag from an error message. If the
72+
// parsing fials, it returns the input error and an empty string
73+
func flagFromError(err error) (string, error) {
74+
errStr := err.Error()
75+
trimmed := strings.TrimPrefix(errStr, providedButNotDefinedErrMsg)
76+
if errStr == trimmed {
77+
return "", err
78+
}
79+
return trimmed, nil
80+
}
81+
7082
func splitShortOptions(set *flag.FlagSet, arg string) []string {
7183
shortFlagsExist := func(s string) bool {
7284
for _, c := range s[1:] {

‎suggestions.go‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/antzucaro/matchr"
7+
)
8+
9+
const didYouMeanTemplate = "Did you mean '%s'?"
10+
11+
func (a *App) suggestFlagFromError(err error, command string) (string, error) {
12+
flag, parseErr := flagFromError(err)
13+
if parseErr != nil {
14+
return "", err
15+
}
16+
17+
flags := a.Flags
18+
if command != "" {
19+
cmd := a.Command(command)
20+
if cmd == nil {
21+
return "", err
22+
}
23+
flags = cmd.Flags
24+
}
25+
26+
suggestion := a.suggestFlag(flags, flag)
27+
if len(suggestion) == 0 {
28+
return "", err
29+
}
30+
31+
return fmt.Sprintf(didYouMeanTemplate+"\n\n", suggestion), nil
32+
}
33+
34+
func (a *App) suggestFlag(flags []Flag, provided string) (suggestion string) {
35+
distance := 0.0
36+
37+
for _, flag := range flags {
38+
flagNames := flag.Names()
39+
if !a.HideHelp {
40+
flagNames = append(flagNames, HelpFlag.Names()...)
41+
}
42+
for _, name := range flagNames {
43+
newDistance := matchr.JaroWinkler(name, provided, true)
44+
if newDistance > distance {
45+
distance = newDistance
46+
suggestion = name
47+
}
48+
}
49+
}
50+
51+
if len(suggestion) == 1 {
52+
suggestion = "-" + suggestion
53+
} else if len(suggestion) > 1 {
54+
suggestion = "--" + suggestion
55+
}
56+
57+
return suggestion
58+
}
59+
60+
// suggestCommand takes a list of commands and a provided string to suggest a
61+
// command name
62+
func suggestCommand(commands []*Command, provided string) (suggestion string) {
63+
distance := 0.0
64+
for _, command := range commands {
65+
for _, name := range append(command.Names(), helpName, helpAlias) {
66+
newDistance := matchr.JaroWinkler(name, provided, true)
67+
if newDistance > distance {
68+
distance = newDistance
69+
suggestion = name
70+
}
71+
}
72+
}
73+
74+
return fmt.Sprintf(didYouMeanTemplate, suggestion)
75+
}

‎suggestions_test.go‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
package cli
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"testing"
7+
)
8+
9+
func TestSuggestFlag(t *testing.T) {
10+
// Given
11+
app := testApp()
12+
13+
for _, testCase := range []struct {
14+
provided, expected string
15+
}{
16+
{"", ""},
17+
{"a", "--another-flag"},
18+
{"hlp", "--help"},
19+
{"k", ""},
20+
{"s", "-s"},
21+
} {
22+
// When
23+
res := app.suggestFlag(app.Flags, testCase.provided)
24+
25+
// Then
26+
expect(t, res, testCase.expected)
27+
}
28+
}
29+
30+
func TestSuggestFlagHideHelp(t *testing.T) {
31+
// Given
32+
app := testApp()
33+
app.HideHelp = true
34+
35+
// When
36+
res := app.suggestFlag(app.Flags, "hlp")
37+
38+
// Then
39+
expect(t, res, "--fl")
40+
}
41+
42+
func TestSuggestFlagFromError(t *testing.T) {
43+
// Given
44+
app := testApp()
45+
46+
for _, testCase := range []struct {
47+
command, provided, expected string
48+
}{
49+
{"", "hel", "--help"},
50+
{"", "soccer", "--socket"},
51+
{"config", "anot", "--another-flag"},
52+
} {
53+
// When
54+
res, _ := app.suggestFlagFromError(
55+
errors.New(providedButNotDefinedErrMsg+testCase.provided),
56+
testCase.command,
57+
)
58+
59+
// Then
60+
expect(t, res, fmt.Sprintf(didYouMeanTemplate+"\n\n", testCase.expected))
61+
}
62+
}
63+
64+
func TestSuggestFlagFromErrorWrongError(t *testing.T) {
65+
// Given
66+
app := testApp()
67+
68+
// When
69+
_, err := app.suggestFlagFromError(errors.New("invalid"), "")
70+
71+
// Then
72+
expect(t, true, err != nil)
73+
}
74+
75+
func TestSuggestFlagFromErrorWrongCommand(t *testing.T) {
76+
// Given
77+
app := testApp()
78+
79+
// When
80+
_, err := app.suggestFlagFromError(
81+
errors.New(providedButNotDefinedErrMsg+"flag"),
82+
"invalid",
83+
)
84+
85+
// Then
86+
expect(t, true, err != nil)
87+
}
88+
89+
func TestSuggestFlagFromErrorNoSuggestion(t *testing.T) {
90+
// Given
91+
app := testApp()
92+
93+
// When
94+
_, err := app.suggestFlagFromError(
95+
errors.New(providedButNotDefinedErrMsg+""),
96+
"",
97+
)
98+
99+
// Then
100+
expect(t, true, err != nil)
101+
}
102+
103+
func TestSuggestCommand(t *testing.T) {
104+
// Given
105+
app := testApp()
106+
107+
for _, testCase := range []struct {
108+
provided, expected string
109+
}{
110+
{"", ""},
111+
{"conf", "config"},
112+
{"i", "i"},
113+
{"information", "info"},
114+
{"not-existing", "info"},
115+
} {
116+
// When
117+
res := suggestCommand(app.Commands, testCase.provided)
118+
119+
// Then
120+
expect(t, res, fmt.Sprintf(didYouMeanTemplate, testCase.expected))
121+
}
122+
}

0 commit comments

Comments
 (0)