From 5155946348eed0f79a76f7743407c0c933e3b5f0 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Thu, 7 May 2020 21:18:16 -0400 Subject: [PATCH] Ignore required flags when DisableFlagParsing (#1095) 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 --- command.go | 4 ++++ command_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/command.go b/command.go index 88e6ed7..5b81f61 100644 --- a/command.go +++ b/command.go @@ -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) { diff --git a/command_test.go b/command_test.go index ec8e2ae..16cc41b 100644 --- a/command_test.go +++ b/command_test.go @@ -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"}