Reputation:
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 ?
Upvotes: 3
Views: 2010
Reputation: 141
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).
Upvotes: 6