Skip to content

Commit 75691d8

Browse files
committed
fix: skip AllowExtFlags flags in the duplicate name check
With AllowExtFlags, the Go flags that other packages register on flag.CommandLine are appended to cmd.Flags. glog, for example, registers -v in init(), so a command with its own -v flag now failed: foo -v # flag "v" defined multiple times The user can't rename a flag that belongs to a dependency. Skip ext flags in the check so the user flag wins again, as before this change. Assisted-by: claude:claude-opus-5-5 Signed-off-by: Eng Zer Jun <[email protected]>
1 parent 0f36b6e commit 75691d8

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎command.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,11 @@ func (cmd *Command) checkHelp() bool {
188188
func (cmd *Command) checkDuplicateFlagNames() error {
189189
seen := map[string]struct{}{}
190190
for _, fl := range cmd.allFlags() {
191+
// Go flags from other packages (AllowExtFlags) can't be renamed
192+
// by the user, so a user flag with the same name wins instead.
193+
if _, ok := fl.(*extFlag); ok {
194+
continue
195+
}
191196
for _, name := range fl.Names() {
192197
if _, ok := seen[name]; ok {
193198
return fmt.Errorf("flag %q defined multiple times", name)

‎command_test.go‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4048,6 +4048,31 @@ func TestDuplicateFlagNamesAreRejected(t *testing.T) {
40484048
}
40494049
}
40504050

4051+
// A Go flag that another package registers on flag.CommandLine, such as
4052+
// glog's -v, can't be renamed by the user, so it is not reported as a
4053+
// duplicate. The user flag wins, as before.
4054+
func TestDuplicateFlagNamesSkipExtFlags(t *testing.T) {
4055+
origCommandLine := flag.CommandLine
4056+
t.Cleanup(func() { flag.CommandLine = origCommandLine })
4057+
flag.CommandLine = flag.NewFlagSet("foo", flag.ContinueOnError)
4058+
ext := flag.Bool("v", false, "ext package flag usage")
4059+
4060+
cmd := &Command{
4061+
AllowExtFlags: true,
4062+
Flags: []Flag{
4063+
&BoolFlag{Name: "verbose", Aliases: []string{"v"}},
4064+
},
4065+
Action: func(context.Context, *Command) error {
4066+
return nil
4067+
},
4068+
}
4069+
4070+
err := cmd.Run(buildTestContext(t), []string{"foo", "-v"})
4071+
require.NoError(t, err)
4072+
require.True(t, cmd.Bool("verbose"))
4073+
require.False(t, *ext)
4074+
}
4075+
40514076
func TestUserDefinedHelpFlagOverridesBuiltin(t *testing.T) {
40524077
writer := &bytes.Buffer{}
40534078
cmd := &Command{

0 commit comments

Comments
 (0)