Skip to content

Commit

Permalink
Ignore required flags when DisableFlagParsing (#1095)
Browse files Browse the repository at this point in the history
When a command request to DisableFlagParsing, it should not fail due
to a missing required flag.  In fact, such a check will always fail
since flags weren't parsed!

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
  • Loading branch information
marckhouzam committed May 8, 2020
1 parent aa5badd commit 5155946
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -979,6 +979,10 @@ func (c *Command) ValidateArgs(args []string) error {
}

func (c *Command) validateRequiredFlags() error {
if c.DisableFlagParsing {
return nil
}

flags := c.Flags()
missingFlagNames := []string{}
flags.VisitAll(func(pflag *flag.Flag) {
Expand Down
31 changes: 31 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,37 @@ func TestPersistentRequiredFlags(t *testing.T) {
}
}

func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {
// Make sure a required persistent flag does not break
// commands that disable flag parsing

parent := &Command{Use: "parent", Run: emptyRun}
parent.PersistentFlags().Bool("foo", false, "")
flag := parent.PersistentFlags().Lookup("foo")
parent.MarkPersistentFlagRequired("foo")

child := &Command{Use: "child", Run: emptyRun}
child.DisableFlagParsing = true

parent.AddCommand(child)

if _, err := executeCommand(parent, "--foo", "child"); err != nil {
t.Errorf("Unexpected error: %v", err)
}

// Reset the flag or else it will remember the state from the previous command
flag.Changed = false
if _, err := executeCommand(parent, "child", "--foo"); err != nil {
t.Errorf("Unexpected error: %v", err)
}

// Reset the flag or else it will remember the state from the previous command
flag.Changed = false
if _, err := executeCommand(parent, "child"); err != nil {
t.Errorf("Unexpected error: %v", err)
}
}

func TestInitHelpFlagMergesFlags(t *testing.T) {
usage := "custom flag"
rootCmd := &Command{Use: "root"}
Expand Down

0 comments on commit 5155946

Please sign in to comment.