21

I want sub command to print out the Help menu if no argument or flags is passed (The main command does this by default).

For example, the main command without any arguments or flags:

chris@pop-os:~$ ./tk
Command line application to deploy

Usage:
  tk [command]

Available Commands:
  addon       Install packages
  cluster     Used to create cloud infrastructures
  help        Help about any command

Flags:
      --config string   config file (default is $HOME/.tk8.yaml)
  -h, --help            help for tk
  -t, --toggle          Help message for toggle

Use "tk [command] --help" for more information about a command.

I want subcommand like "tk addon" to also return it's own help menu if no arguments or flags is entered, currently it only gives a blank line.

addon code :

var addonCmd = &cobra.Command{
    Use:   "addon",
Short: "Install addon packages",
Long: `Install additional packages`,
Run: func(cmd *cobra.Command, args []string) {

        }
    },
}
4

3 回答 3

31

可以检查传递给程序的参数的数量。如果有更多然后0args 你将做实际的工作,但如果它更少那么你将只显示命令的“帮助”。

var addonCmd = &cobra.Command{
    Use:   "addon",
    Short: "Install addon packages",
    Long: `Install additional packages`,
    Run: func(cmd *cobra.Command, args []string) {
        if len(args) == 0 {
            cmd.Help()
            os.Exit(0)
        }
        // do actual work
    },
}
于 2018-03-07T14:00:28.277 回答
3

我认为最好在 PreRunE 上处理它。

var addonCmd = &cobra.Command{
    Use:   "addon",
    Short: "Install addon packages",
    Long: `Install additional packages`,
    PreRunE: func(cmd *cobra.Command, args []string) error {
        if len(args) == 0 {
            cmd.Help()
            os.Exit(0)
        }
        return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        // do actual work
    },
}
于 2020-09-12T03:46:45.687 回答
0

我对 Go 完全陌生,因为如果没有提供任何参数,我也需要显示帮助。公认的答案很好,这仅作为替代方案。

我的子命令正好需要 2 个参数,所以我发现 Cobra 为此提供了一个很好的机制

var subCmd = &cobra.Command {
    Use : "subc",
    Args : cobra.ExactArgs(2),
    ...
}

问题是,即使在接受的答案中讨论了条件,Run这也不允许我打印帮助。因此,在进一步挖掘之后,我发现结构中的定义Args与字段Command相同(请参阅 PositionalArgs 的文档)。它只不过是一个与 or 具有完全相同签名的函数。*RunERunEPreRunE

因此,在需要任何情况下检查参数和打印帮助的替代解决方案,请考虑

var subCmd = &cobra.Command {
    ...
    Args : func (cmd *cobra.Command, args []string) error {
        if len(args) == 0 {
            cmd.Help()
            os.Exit(0)
        } else if len(args) < 2 {
            fmt.Println("Incorrect number of args.  <arg1> <arg2> are required")
            os.Exit(1)
        }
        // as written, the command ignores anything more than 2
        return nil
    },
}

这样做的好处是清晰简洁,这与参数有关,而不是命令实现的“功能”。

于 2021-11-09T20:20:29.390 回答