我将眼镜蛇命令flags移动到一个函数中,这样我就可以在其他命令中使用它。我可以看到这些命令,但是当我输入flage时,它总是返回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 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
}因此,当我键入以下命令时
data-check list --ignore-latest--ignore-latest的标志值应该是true,但我得到的是false作为RunE参数中的一个值。我是不是漏掉了什么?
GetCommandFlags是我想在其他命令中使用的东西,我不想重复相同的标志。
发布于 2019-10-24 22:44:41
你应该像cmd = GetCommandFlags(cmd, &opts)一样使用func GetCommandFlags(cmd *cobra.Command, opts *ListOptions)并调用这个函数。
您可以输出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
}发布于 2019-10-24 22:25:47
您正在按值将opts传递给GetCommandFlags。您应该向它传递一个指针,以便为标志注册的地址使用在调用函数中声明的opts。
func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
...
}发布于 2019-10-24 22:26:09
您传递的是值参数,而不是指针参数。
试着这样做:
cmd = GetCommandFlags(cmd, &opts, "")https://stackoverflow.com/questions/58543328
复制相似问题