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 #421

Closed
parametalol opened this issue Mar 3, 2025 · 2 comments
Closed

Comments

@parametalol
Copy link

Expected behavior: command flags should be allowed in front of the commands, even without =true.

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
@parametalol
Copy link
Author

Is it a pflag or cobra issue btw?

@parametalol
Copy link
Author

Moved to cobra.

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