普通网友 2018-03-07 09:59
浏览 68
已采纳

Cobra子命令默认调用帮助

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) {

        }
    },
}
  • 写回答

1条回答 默认 最新

  • douruduan8812 2018-03-07 14:00
    关注

    It is possible to do with checking of amount of passed arguments to your program. If there is more then 0 args you will do actual work, but if it less then you will just show the "help" for the command.

    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
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要