Retain entered flag spellings in parser failures

This commit is contained in:
2026-10-20 00:29:49 +00:00
parent eb92f7be7f
commit 520d7e125b
5 changed files with 108 additions and 8 deletions

View File

@@ -2,6 +2,7 @@ package cobra
import (
"reflect"
"strings"
"testing"
commandmeta "gitea.maximumdirect.net/eric/CommandKit/internal/commandmeta"
@@ -158,3 +159,40 @@ func TestParseFlagAliasOccurrenceOrderAndSpellings(t *testing.T) {
t.Fatalf("tag spellings = %#v, want %#v", got, want)
}
}
func TestParseFailuresRetainEnteredFlagSpellings(t *testing.T) {
for _, spelling := range []string{"--color", "--colour", "-c", "-C"} {
t.Run("missing/"+spelling, func(t *testing.T) {
result := Parse(flagGrammarTree(), []string{"run", spelling}, flagGrammarOptions())
if result.Failure == nil || !strings.Contains(result.Failure.Message, ": "+spelling) {
t.Fatalf("missing value failure = %#v, want entered spelling %q", result.Failure, spelling)
}
})
}
result := Parse(flagGrammarTree(), []string{"run", "-wC"}, flagGrammarOptions())
if result.Failure == nil || !strings.Contains(result.Failure.Message, ": -C") {
t.Fatalf("cluster missing value failure = %#v", result.Failure)
}
for _, test := range []struct {
args []string
spelling string
}{
{[]string{"--hlep=bad"}, "--hlep"},
{[]string{"-h=bad"}, "-h"},
{[]string{"--help=bad"}, "--help"},
{[]string{"--hlep=bad", "--help=true"}, "--hlep"},
{[]string{"-h=bad", "--hlep=true"}, "-h"},
{[]string{"--help=true", "--hlep=bad"}, "--hlep"},
} {
t.Run(strings.Join(test.args, " "), func(t *testing.T) {
result := Parse(flagGrammarTree(), append([]string{"run"}, test.args...), flagGrammarOptions())
if result.Failure == nil || !strings.Contains(result.Failure.Message, "for "+test.spelling) {
t.Fatalf("help failure = %#v, want entered spelling %q", result.Failure, test.spelling)
}
})
}
result = Parse(flagGrammarTree(), []string{"run", "--unknown", "--colour"}, flagGrammarOptions())
if result.Failure == nil || !strings.Contains(result.Failure.Message, "unknown") || strings.Contains(result.Failure.Message, "needs an argument") {
t.Fatalf("earlier parser failure = %#v", result.Failure)
}
}