From c3aed9a833f154300a0246afb843bdb7f997a9ea Mon Sep 17 00:00:00 2001 From: Mike Fridman Date: Tue, 24 Dec 2024 14:07:19 -0500 Subject: [PATCH] add typo suggestion test (levenshtein distance) --- command.go | 2 +- run_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index fc8c77a..8e3b2ec 100644 --- a/command.go +++ b/command.go @@ -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")) } diff --git a/run_test.go b/run_test.go index 99f5044..f829518 100644 --- a/run_test.go +++ b/run_test.go @@ -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{ @@ -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`) + }) }