Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: show flags that shadow parent persistent flag in child help #1776

Merged
merged 1 commit into from Aug 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion command.go
Expand Up @@ -1505,7 +1505,8 @@ func (c *Command) LocalFlags() *flag.FlagSet {
}

addToLocal := func(f *flag.Flag) {
if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
c.lflags.AddFlag(f)
}
}
Expand Down
39 changes: 34 additions & 5 deletions command_test.go
Expand Up @@ -707,10 +707,7 @@ func TestEmptyInputs(t *testing.T) {
}
}

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

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

Expand All @@ -732,7 +729,7 @@ func TestOverwrittenFlag(t *testing.T) {
}

if childInherited.Lookup("intf") != nil {
t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`)
t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`)
}
if childLocal.Lookup("intf") == nil {
t.Error(`LocalFlags expected to contain "intf", got "nil"`)
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