Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine if flags were actually passed in (sub)command invocation in golang's cobra/viper

I have a cobra command

var mycommandCmd = &cobra.Command{
    Use:   "mycommand",
    PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
        viper.BindPFlags(cmd.Flags())

and a subcommand

var mysubcommandCmd = &cobra.Command{
    Use:   "mysubcommand",
    Args:  cobra.ExactArgs(1),
    RunE: func(cmd *cobra.Command, args []string) error {
        viper.BindPFlags(cmd.Flags())

which I of course bind together

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mycommandCmd.AddCommand(mysubcommandCmd)

I also have some flags for both of them

mycommandCmd.PersistentFlags().BoolP("foo", "", true, "Whether to foo")
mysubcommandCmd.Flags().BoolP("foobar", "", true,  "Whether to foobar")

My question is the following:

Assuming the end go binary is named prog, is there a (cobra / viper) built in way of checking of whether any flags were actually passed during subcommand invocation?

i.e. how can I programmatically distinguish between this

prog mycommand mysubcommand --foobar

and this

prog mycommand mysubcommand

Checking against the default flag values will not work of course (and does not scale against the flag number)

>Solution :

You can do:

isSet:=cmd.Flags().Lookup("foobar").Changed

That should return if the flag was set, or if the default value was used.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading