3

在下面的代码中,我定义了一个命令,其中可能有两个选项: 1. myapp info --flag1 text 2. myapp info --flag2 如果没有指定两个选项,我想显示 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 infoormyapp info --help或,myapp info --nonexistentoption但没有说明如何实际调用该方法。任何指针?

4

1 回答 1

3

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

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

于 2017-10-01T15:19:28.580 回答