如何在 cobra 命令中调用默认的 helpCommand?

How can the default helpCommand be called inside a cobra command?

在下面的代码中,我定义了一个命令,其中有两个选项是可能的: 1. myapp 信息 --flag1 文本 2.我的应用程序信息--flag2 如果指定了两个选项中的 none,我想显示 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
        }
     },
 }

在 cobra README 中 helpCommand 的用法解释如下 myapp help infomyapp info --helpmyapp info --nonexistentoption 但与如何实际主动调用该方法无关。有什么指点吗?

我认为它只是通过库查看(未测试):

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()
        }
     },
 }

看这里:

// 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
}

一般来说,自述文件只会提供一些入门和概述信息,您通常需要打开 godocs(内联文档)才能正确理解包:godoc cobra: help command