Skip to content

Commit

Permalink
fix: show flags that shadow parent persistent flag in child help
Browse files Browse the repository at this point in the history
This fixes a bug where a child flag that shadows (has the same
name as) a parent persistent flag would not be shown in the
child command's help output and the parent flag would be shown
instead under the global flags section.

This change makes the help output consistent with the
observed behavior during execution, where the child flag is
the one that is actually used.
  • Loading branch information
brianpursley committed Aug 17, 2022
1 parent dbf85f6 commit 1e1525e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
9 changes: 8 additions & 1 deletion command.go
Expand Up @@ -1505,7 +1505,14 @@ func (c *Command) LocalFlags() *flag.FlagSet {
}

addToLocal := func(f *flag.Flag) {
if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
if c.lflags.Lookup(f.Name) != nil {
return // A flag with this name has already been added
}

// Add the flag if the flag is not a parent PFlag -OR- if it shadows a parent PFlag
parentPFlag := c.parentsPflags.Lookup(f.Name)
shadowsParentPFlag := parentPFlag != nil && parentPFlag != f
if parentPFlag == nil || shadowsParentPFlag {
c.lflags.AddFlag(f)
}
}
Expand Down
35 changes: 32 additions & 3 deletions command_test.go
Expand Up @@ -708,9 +708,6 @@ func TestEmptyInputs(t *testing.T) {
}

func TestOverwrittenFlag(t *testing.T) {
// TODO: This test fails, but should work.
t.Skip()

parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun}

Expand Down Expand Up @@ -887,6 +884,38 @@ func TestHelpCommandExecutedOnChild(t *testing.T) {
checkStringContains(t, output, childCmd.Long)
}

func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {
parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun}
parent.AddCommand(child)

parent.PersistentFlags().Bool("foo", false, "parent foo usage")
parent.PersistentFlags().Bool("bar", false, "parent bar usage")
child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag
child.Flags().Bool("baz", false, "child baz usage")

got, err := executeCommand(parent, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

expected := `Usage:
parent child [flags]
Flags:
--baz child baz usage
--foo child foo usage
-h, --help help for child
Global Flags:
--bar parent bar usage
`

if got != expected {
t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got)
}
}

func TestSetHelpCommand(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
c.AddCommand(&Command{Use: "empty", Run: emptyRun})
Expand Down

0 comments on commit 1e1525e

Please sign in to comment.