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.
This commit is contained in:
dualfroz committed 2026-09-02 10:12:40 +02:00
1 parent 53d1818651
commit 3caf507246
2 files changed
+26 -1

No files matched your search

+1 -1
View File
@@ -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))
}
}
}
+25
View File
@@ -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) {