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

Inconsistent parsing of boolean flags between parent and child commands #2251

Open
parametalol opened this issue Mar 6, 2025 · 0 comments
Open

Comments

@parametalol
Copy link

Expected behavior: command flags should be allowed in front of the commands, even without =true.
Actual behavior: persistent boolean flags put in front of the command are not recognized.

func Test_flagsOrder(t *testing.T) {
	rootCommand := &cobra.Command{SilenceUsage: true, Args: cobra.MaximumNArgs(0)}
	var flagValue bool
	rootCommand.PersistentFlags().BoolVar(&flagValue, "rootflag", false, "root boolean flag")

	cmd := &cobra.Command{Use: "command", SilenceUsage: true, Args: cobra.MaximumNArgs(0)}
	cmd.PersistentFlags().BoolVar(&flagValue, "cmdflag", false, "command boolean flag")
	rootCommand.AddCommand(cmd)

	for name, args := range map[string][]string{
		"root flag before command":                {"--rootflag", "command"},     // ok
		"command flag before command":             {"--cmdflag", "command"},      // unknown flag: --cmdflag
		"command flag with =value before command": {"--cmdflag=true", "command"}, // ok
	} {
		t.Run(name, func(t *testing.T) {
			flagValue = false
			rootCommand.SetArgs(args)
			if err := rootCommand.Execute(); err != nil {
				t.Error(err)
			}
			if !flagValue {
				t.Errorf("flag is false")
			}
		})
	}
}

Output:

-- FAIL: Test_flagsOrder (0.00s)
    --- FAIL: Test_flagsOrder/command_flag_before_command (0.00s)
        flags_test.go:27: unknown flag: --cmdflag
        flags_test.go:30: flag is false

Moved here from spf13/pflag#421

@parametalol parametalol marked this as a duplicate of spf13/pflag#421 Mar 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant