diff --git a/command.go b/command.go index d1fc008e78..2021b03456 100644 --- a/command.go +++ b/command.go @@ -161,6 +161,8 @@ type Command struct { globaHelpFlagAdded bool // whether global version flag was added globaVersionFlagAdded bool + // generated root version flag + versionFlag Flag // whether this is a completion command isCompletionCommand bool } diff --git a/command_setup.go b/command_setup.go index fca499cccb..6270468f4a 100644 --- a/command_setup.go +++ b/command_setup.go @@ -104,8 +104,11 @@ func (cmd *Command) setupDefaults(osArgs []string) { localVersionFlag = VersionFlag } - cmd.appendFlag(localVersionFlag) - cmd.globaVersionFlagAdded = true + if !flagNamesInUse(cmd.allFlags(), localVersionFlag.Names()) { + cmd.appendFlag(localVersionFlag) + cmd.versionFlag = localVersionFlag + cmd.globaVersionFlagAdded = true + } } } @@ -193,6 +196,20 @@ func (cmd *Command) setupSubcommand() { cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) } +func flagNamesInUse(flags []Flag, names []string) bool { + for _, name := range names { + for _, fl := range flags { + for _, flagName := range fl.Names() { + if flagName == name { + return true + } + } + } + } + + return false +} + func (cmd *Command) hideHelp() bool { tracef("hide help (cmd=%[1]q)", cmd.Name) for c := cmd; c != nil; c = c.parent { diff --git a/command_test.go b/command_test.go index 24ce5e4739..0ce36baddc 100644 --- a/command_test.go +++ b/command_test.go @@ -2392,6 +2392,31 @@ func TestCommand_Run_Version(t *testing.T) { } } +func TestCommand_Run_CustomFlagCanUseVersionAlias(t *testing.T) { + buf := new(bytes.Buffer) + called := false + + cmd := &Command{ + Name: "boom", + Version: "0.1.0", + Writer: buf, + Flags: []Flag{ + &BoolFlag{Name: "verbose", Aliases: []string{"v"}}, + }, + Action: func(_ context.Context, cmd *Command) error { + called = true + assert.True(t, cmd.Bool("verbose")) + return nil + }, + } + + err := cmd.Run(buildTestContext(t), []string{"boom", "-v"}) + + assert.NoError(t, err) + assert.True(t, called) + assert.Empty(t, buf.String()) +} + func TestCommand_Run_Categories(t *testing.T) { buf := new(bytes.Buffer) diff --git a/help.go b/help.go index 1fba6edf0c..bb1966528a 100644 --- a/help.go +++ b/help.go @@ -459,13 +459,7 @@ func DefaultPrintHelp(out io.Writer, templ string, data any) { } func checkVersion(cmd *Command) bool { - found := false - for _, name := range VersionFlag.Names() { - if cmd.Bool(name) { - found = true - } - } - return found + return cmd.versionFlag != nil && cmd.versionFlag.IsSet() } func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {