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

'MarkFlagsRequiredTogether' does not work as intended. Am I wrong? #2103

Open
haung921209 opened this issue Jan 29, 2024 · 1 comment
Open

Comments

@haung921209
Copy link

cmd
ㄴroot.go
ㄴtest
    ㄴcmd.go
    ㄴtest_cmd.go
    ㄴtest_sub.go
// root.go
...
func init() {
	RootCmd.PersistentFlags().StringVar(&profile, "profile", "default", "input dev profile, if needed")
...
	RootCmd.AddCommand(test.GetCommands()...)
}
// cmd.go
var commands []*cobra.Command

func addCommand(command *cobra.Command) {
	commands = append(commands, command)
}

func GetCommands() []*cobra.Command {
	return commands
}
// test.go

var (
	path           string
	testCmd      = &cobra.Command{
		Use:   "test",
		Short: "testCmd",
		Long:  "Test Command",
	}
)

func init() {
	testCmd.PersistentFlags().StringVar(&path, "path", "", "Path to mount")
	addCommand(testCmd)
}
//test_sub.go
var testSubCmd = &cobra.Command{
	Use:   "sub",
	Short: "test.testSubCmd",
	Long:  "Test Job",
	Run: func(cmd *cobra.Command, args []string) {
	},
}

func init() {
	testSubCmd.MarkFlagsRequiredTogether("path")
	testCmd.AddCommand(testSubCmd)
}

After writing this, I thought "path" would only work to require when running testSubCmd. However, I was able to see the error that "path" was required when requesting another command (for example, a command of another package implemented in the same way). (This was not only true for 'MarkFlagsRequiredTogether' but also for 'MarkFlagRequired' and so on.)
In this case, is there a way to resolve it in cobra?

@marckhouzam
Copy link
Collaborator

This is probably because you have declared --path as a persistent flag: testCmd.PersistentFlags().StringVar(&path, "path", "", "Path to mount"). A persistent flag applies to the command and all its sub-commands.
You can instead try: testCmd.Flags().StringVar(&path, "path", "", "Path to mount")

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

2 participants