From 3caf507246744f68f1be42317f70a850a1346c0a Mon Sep 17 00:00:00 2001 From: DualFroz Date: Wed, 2 Sep 2026 10:12:40 +0200 Subject: [PATCH] fix(args): suggest alternatives for the invalid arg, not the first one OnlyValidArgs reports the offending argument correctly ("invalid argument %q") but computed the "Did you mean this?" suggestion from args[0]. When the invalid argument is not the first one, the suggestion was therefore based on an unrelated (valid) argument, so it was missing or pointed at the wrong token. Compute the suggestion from the argument actually being reported, so it always matches the invalid argument regardless of its position. --- args.go | 2 +- args_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/args.go b/args.go index 7bf8c38..bdac116 100644 --- a/args.go +++ b/args.go @@ -58,7 +58,7 @@ func OnlyValidArgs(cmd *Command, args []string) error { } for _, v := range args { if !stringInSlice(v, validArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) + return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(v)) } } } diff --git a/args_test.go b/args_test.go index 7d75e16..98a2c8b 100644 --- a/args_test.go +++ b/args_test.go @@ -164,6 +164,31 @@ func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) { validOnlyWithInvalidArgs(err, t) } +// TestOnlyValidArgs_SuggestsForInvalidArg ensures the "Did you mean this?" +// suggestion is computed for the argument actually reported as invalid, not +// always for the first argument. When a later argument is the invalid one, the +// suggestion must still match that argument. +func TestOnlyValidArgs_SuggestsForInvalidArg(t *testing.T) { + c := &Command{ + Use: "c", + ValidArgs: []string{"one", "two"}, + Run: emptyRun, + } + c.AddCommand(&Command{Use: "three", Run: emptyRun}) + + err := OnlyValidArgs(c, []string{"one", "thre"}) + if err == nil { + t.Fatal("Expected an error") + } + got := err.Error() + if !strings.Contains(got, `invalid argument "thre"`) { + t.Errorf("Expected error to reference the invalid argument, got: %q", got) + } + if !strings.Contains(got, "three") { + t.Errorf("Expected suggestion for the invalid argument, got: %q", got) + } +} + // NoDuplicateArgs func TestNoDuplicateArgs(t *testing.T) {