Skip to content

Commit

Permalink
add typo suggestion test (levenshtein distance)
Browse files Browse the repository at this point in the history
  • Loading branch information
mfridman committed Dec 24, 2024
1 parent 4ccf50b commit c3aed9a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ func (c *Command) getSuggestions(unknownCmd string) []string {
func (c *Command) formatUnknownCommandError(unknownCmd string) error {
suggestions := c.getSuggestions(unknownCmd)
if len(suggestions) > 0 {
return fmt.Errorf("unknown command %q\nDid you mean one of these?\n\t%s",
return fmt.Errorf("unknown command %q. Did you mean one of these?\n\t%s",
unknownCmd,
strings.Join(suggestions, "\n\t"))
}
Expand Down
24 changes: 24 additions & 0 deletions run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func TestRun(t *testing.T) {
t.Parallel()

t.Run("parse and run", func(t *testing.T) {
t.Parallel()
var count int

root := &Command{
Expand Down Expand Up @@ -59,4 +60,27 @@ func TestRun(t *testing.T) {
require.NoError(t, err)
require.Equal(t, 3, count)
})
t.Run("typo suggestion", func(t *testing.T) {
t.Parallel()
root := &Command{
Name: "count",
Usage: "count [flags] [command]",
SubCommands: []*Command{
{
Name: "version",
Usage: "show version",
Exec: func(ctx context.Context, s *State) error {
_, _ = s.Stdout.Write([]byte("1.0.0\n"))
return nil
},
},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}

err := ParseAndRun(context.Background(), root, []string{"verzion"}, nil)
require.Error(t, err)
require.Contains(t, err.Error(), `unknown command "verzion". Did you mean one of these?`)
require.Contains(t, err.Error(), ` version`)
})
}

0 comments on commit c3aed9a

Please sign in to comment.