3

I would like to define a CLI flag that counts the number of times that it appears.

For example, let's define the flag --verbose with its shorthand -v:

# verbose value should be 0
> myCmd

# verbose value should be 1
> myCmd -v

# verbose value should be 2
> myCmd -vv

# ...

It's there any built-in way to achieve it ?

1 Answers1

6

From https://github.com/spf13/cobra: "Flag functionality is provided by the pflag library"

There are several options for counted flags in the pflag library as documented at: https://godoc.org/github.com/spf13/pflag#Count

A long example spanning many files could be presented, but the crux of it is to use something like this (where "run" is the cobra command in this case):

runCmd.Flags().CountP("verbose", "v", "counted verbosity")

To later retrieve that value within runCmd's Run function, use this:

verbosity, _ := cmd.Flags().GetCount("verbose")

Variable verbosity will then be an int holding the number of repetitions.

In that example, I have used the CountP version from pflag, which permits both a long and short flag name to be provided (which I think is what you were hoping to find).

Bill
  • 131
  • 1
  • 5
  • 1
    follow on question because i'm looking to do this as well: what's the idiomatic way to expose the `verbosity` value to functions called by the command execution? sometimes those called functions are in different packages. the value should only exist for the life of the command, not persisted in a config file, etc. – Rob Wilkerson Feb 11 '22 at 19:51
  • There are multiple things you could do. 1. Define `verbosity` as a PersistentFlag in the root command and the sub-commands will automatically have them. 2. set a value in the context of the rootCmd. cobra.Command has a method called SetContext. You can create a new context with the value of verbosity and pass it on in the context set with the root cmd. – Rishabh Bhatnagar Jul 21 '23 at 23:10