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

Required if another flag is defined #1595

Closed
theprobugmaker opened this issue Feb 6, 2022 · 2 comments · Fixed by #1654
Closed

Required if another flag is defined #1595

theprobugmaker opened this issue Feb 6, 2022 · 2 comments · Fixed by #1654
Labels
area/flags-args Changes to functionality around command line flags and args kind/support Questions, supporting users, etc.

Comments

@theprobugmaker
Copy link

How can I make a flag required if another flag is set?

For example, I have a flag that enables (bool) a feature, I want to make all the flags for that feature required if it's enabled.

Thank you

@tirkarthi
Copy link

Does dynamically marking the flag as required in hooks help? Here email is marked as required when username is "test"

package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

var createCmd = &cobra.Command{
	Use:   "create",
	Short: "Create user",
	Long:  `Create user with given username and email`,
	PreRun: func(cmd *cobra.Command, args []string) {
		username, _ := cmd.Flags().GetString("username")
		if username == "test" {
			cmd.MarkFlagRequired("email")
		}
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		username, _ := cmd.Flags().GetString("username")
		email, _ := cmd.Flags().GetString("email")

		fmt.Println("Username", username)
		fmt.Println("Email", email)

		return nil

	},
}

func init() {
	createCmd.Flags().StringP("username", "u", "", "Username for the user")
	createCmd.Flags().StringP("email", "e", "", "Email of the user")
	createCmd.MarkFlagRequired("username")
}

@johnSchnake johnSchnake added area/flags-args Changes to functionality around command line flags and args kind/support Questions, supporting users, etc. labels Feb 21, 2022
@johnSchnake
Copy link
Collaborator

I think that is the way to go and which is why I think it was intentional that the flag parsing happens before pre run hooks but the validation happens after them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/flags-args Changes to functionality around command line flags and args kind/support Questions, supporting users, etc.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants