Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
21 changes: 19 additions & 2 deletions command_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}

Expand Down Expand Up @@ -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 {
Expand Down
25 changes: 25 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
8 changes: 1 addition & 7 deletions help.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading