简体   繁体   English

PreRun / PreRunE 钩子未在 cobra 中执行

[英]PreRun / PreRunE hooks not being executed in cobra

I have a cobra command我有一条cobra命令

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),
    PreRun: func(cmd *cobra.Command, args []string) {
        fmt.Println("HELLO")
    },
    RunE: func(cmd *cobra.Command, args []string) error {
        viper.BindPFlags(cmd.Flags())

However I don't see the PreRun hook being executed when there is an error in terms of argument passing.但是,当参数传递出现错误时,我看不到PreRun钩子正在执行。

In the case above, mysubcommand requires exactly one argument, so when invoking it without it:在上面的例子中, mysubcommand需要一个参数,所以在没有它的情况下调用它时:

go run main.go mycommand mysubcommand

Error: accepts 1 arg(s), received 0
Usage:
  myprog mycommand mysubcommand [flags]

FWIW what I am trying to do is to print a more elegant and informative message in case the argument count is wrong. FWIW 我想做的是打印一个更优雅和信息丰富的消息,以防参数计数错误。

Same is the situation when using PreRunE in the place of PreRun使用PreRunE代替PreRun时的情况也是如此

From what I understand working with the library so far is that, there is a validation done before execution of PreRun hooks.据我到目前为止使用该库的理解是,在执行PreRun钩子之前进行了验证。 Since you have mentioned Args: cobra.ExactArgs(1) , the validation fails causing the error.由于您提到了Args: cobra.ExactArgs(1) ,因此验证失败导致错误。
Docs .文档

If you want to handle this by yourself, you should do something like this in your mysubcommandCmd如果你想自己处理这个,你应该在你的mysubcommandCmd中做这样的事情

var mysubcommandCmd = &cobra.Command{
    Use:   "mysubcommand",
    PreRunE: func(cmd *cobra.Command, args []string) {
        if len(args) != 1 {
            return errors.New("more elegant and informative message")
        }
        fmt.Println("HELLO")
        return nil
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM