为了账号安全,请及时绑定邮箱和手机立即绑定

公共函数中的 Golang Cobra 命令标志未从 cli 获取值

公共函数中的 Golang Cobra 命令标志未从 cli 获取值

Go
红糖糍粑 2023-07-31 15:49:26
我正在将 cobra 命令移至flags函数内,以便可以在其他命令中使用它。我可以看到命令,但是当我输入标志时它总是返回false。以下是我的代码:func NewCommand(ctx context.Context) *cobra.Command {    var opts ListOptions    cmd := &cobra.Command{        Use:   "list",        Short: "List",        RunE: func(cmd *cobra.Command, args []string) error {            fmt.Println(args) // []            opts.refs = args            return List(ctx, gh, opts, os.Stdout)        },    }    cmd = GetCommandFlags(cmd, opts)    return cmd}// GetListCommandFlags for listfunc GetCommandFlags(cmd *cobra.Command, opts ListOptions) *cobra.Command {    flags := cmd.Flags()    flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")    flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")    return cmd}所以当我输入以下命令时data-check list --ignore-latest的标志值--ignore-latest应该是true,但我得到的false是 args 中的值RunE。我在这里错过了什么吗?GetCommandFlags是我想在其他命令中使用它的东西,我不想重复相同的标志。
查看完整描述

3 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

您应该像使用func GetCommandFlags(cmd *cobra.Command, opts *ListOptions)和调用 func 一样cmd = GetCommandFlags(cmd, &opts)。


您可以打印opts.IgnoreLatest并opts.IgnoreOld查看更改后的值。


对我来说效果很好。希望它也对你有用。


func NewCommand(ctx context.Context) *cobra.Command {

    var opts ListOptions


    cmd := &cobra.Command{

        Use:   "list",

        Short: "List",

        RunE: func(cmd *cobra.Command, args []string) error {

            // fmt.Println(args) // []

            fmt.Println(opts.IgnoreLatest, ", ", opts.IgnoreOld)

            opts.refs = args

            return List(ctx, gh, opts, os.Stdout)

        },

    }


    cmd = GetCommandFlags(cmd, &opts)

    return cmd

}


// GetListCommandFlags for list

func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {

    flags := cmd.Flags()

    flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")

    flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")

    return cmd

}


查看完整回答
反对 回复 2023-07-31
?
心有法竹

TA贡献1866条经验 获得超5个赞

您正在optsGetCommandFlags值传递。您应该向它传递一个指针,以便为标志注册的地址使用opts调用函数中声明的地址。

func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
  ...
}


查看完整回答
反对 回复 2023-07-31
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您传递的是值参数而不是指针参数。

尝试一些像:

cmd = GetCommandFlags(cmd, &opts, "")


查看完整回答
反对 回复 2023-07-31
  • 3 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信