确定在golang的cobra/viper中的(子)命令调用中是否实际传递了标志位。

huangapple go评论93阅读模式
英文:

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

问题

我有一个cobra命令:

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

还有一个子命令:

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

当然,我将它们绑定在一起:

mycommandCmd.AddCommand(mysubcommandCmd)

我还为它们设置了一些标志:

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

我的问题是:

假设最终的go二进制文件名为prog,是否有一种(cobra / viper)内置的方法来检查在调用子命令时是否传递了任何标志?

也就是说,我如何以编程方式区分这两种情况:

prog mycommand mysubcommand --foobar

prog mycommand mysubcommand

当然,检查默认标志值是行不通的(而且在标志数量上不可扩展)。

英文:

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)

答案1

得分: 2

你可以这样做:

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

这将返回标志是否被设置,或者是否使用了默认值。

英文:

You can do:

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

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

huangapple
  • 本文由 发表于 2021年11月17日 01:36:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/69993691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定