duanjuan1103 2017-10-01 15:09
浏览 40
已采纳

如何在眼镜蛇命令中调用默认的helpCommand?

In the following code I'm defining a command, where two options are possible: 1. myapp info --flag1 text 2. myapp info --flag2 if none of the two options are specified, I want to show the helpCommand

var infoCmd = &cobra.Command{
    Use:   "info",
    Short: "A brief description of your command",
    Run: func(cmd *cobra.Command, args []string) {
        var infoURL string
        if flag1 != "" {
            doSomething()
        } else if flag2 { //this is a boolean flag
            doSomethingElse()
        } else {
            // Show the default help here
        }
     },
 }

In the cobra README the helpCommand is explained for usage like myapp help info or myapp info --help or myapp info --nonexistentoption but nothing regarding how to actually call the method voluntarily. Any pointers?

  • 写回答

1条回答 默认 最新

  • doupang9614 2017-10-01 15:19
    关注

    I think its just this looking through the lib (not tested):

    var infoCmd = &cobra.Command{
        Use:   "info",
        Short: "A brief description of your command",
        Run: func(cmd *cobra.Command, args []string) {
            var infoURL string
            if flag1 != "" {
                doSomething()
            } else if flag2 { //this is a boolean flag
                doSomethingElse()
            } else {
                // Show the default help here
                cmd.Help()
            }
         },
     }
    

    See here:

    // Help puts out the help for the command.
    // Used when a user calls help [command].
    // Can be defined by user by overriding HelpFunc.
    func (c *Command) Help() error {
        c.HelpFunc()(c, []string{})
        return nil
    }
    

    Generally speaking a readme is only going to give some get started and overview info, you will often have to open up the godocs (inline documentation) to properly understand a package: godoc cobra: help command

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥20 unity内置语言切换的按钮设置
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器