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

Time:11-17

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

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)

CodePudding user response:

You can do:

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

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

  • Related