cobra包是一个指挥官,提供了一个简单的接口来创建强大的现代CLI接口。除了提供接口之外,Cobra还提供了一个控制器来组织应用程序代码。
文档:https://godoc.org/github.com/spf13/cobra

type Command

  1. type Command struct {
  2. // Use是一行用法消息,rootcmd 可以忽略它
  3. Use string
  4. // 别名是一个别名数组,可以用来代替使用的第一个单词
  5. Aliases []string
  6. // Short是在“help”输出中显示的简短描述
  7. Short string
  8. // Long是'help <this-command>'输出中显示的长消息
  9. Long string
  10. // Example 是显示如何使用命令
  11. Example string
  12. // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
  13. ValidArgs []string
  14. // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
  15. // It is a dynamic version of using ValidArgs.
  16. // Only one of ValidArgs and ValidArgsFunction can be used for a command.
  17. ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
  18. // 所有参数
  19. Args PositionalArgs
  20. // ArgAliases is List of aliases for ValidArgs.
  21. // These are not suggested to the user in the bash completion,
  22. // but accepted if entered manually.
  23. ArgAliases []string
  24. // BashCompletionFunction is custom functions used by the bash autocompletion generator.
  25. BashCompletionFunction string
  26. // Deprecated defines, if this command is deprecated and should print this string when used.
  27. Deprecated string
  28. // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
  29. Hidden bool
  30. // Annotations are key/value pairs that can be used by applications to identify or
  31. // group commands.
  32. Annotations map[string]string
  33. // 定义一个version标识,可通过 version 或 -v 查看
  34. Version string
  35. // Run函数按以下顺序执行:
  36. // * PersistentPreRun()
  37. // * PreRun()
  38. // * Run()
  39. // * PostRun()
  40. // * PersistentPostRun()
  41. // 所有函数都得到相同的参数,即命令名后面的参数.
  42. //
  43. // PersistentPreRun: children of this command will inherit and execute.
  44. PersistentPreRun func(cmd *Command, args []string)
  45. // PersistentPreRunE: PersistentPreRun but returns an error.
  46. PersistentPreRunE func(cmd *Command, args []string) error
  47. // PreRun: children of this command will not inherit.
  48. PreRun func(cmd *Command, args []string)
  49. // PreRunE: PreRun but returns an error.
  50. PreRunE func(cmd *Command, args []string) error
  51. // Run: Typically the actual work function. Most commands will only implement this.
  52. Run func(cmd *Command, args []string)
  53. // RunE: Run but returns an error.
  54. RunE func(cmd *Command, args []string) error
  55. // PostRun: run after the Run command.
  56. PostRun func(cmd *Command, args []string)
  57. // PostRunE: PostRun but returns an error.
  58. PostRunE func(cmd *Command, args []string) error
  59. // PersistentPostRun: children of this command will inherit and execute after PostRun.
  60. PersistentPostRun func(cmd *Command, args []string)
  61. // PersistentPostRunE: PersistentPostRun but returns an error.
  62. PersistentPostRunE func(cmd *Command, args []string) error
  63. // 对下游的错误进行屏蔽
  64. SilenceErrors bool
  65. // 对错误用法进行屏蔽
  66. SilenceUsage bool
  67. // 禁用标志解析.
  68. // 如果为真,所有标志都将作为参数传递给该命令
  69. DisableFlagParsing bool
  70. // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
  71. // will be printed by generating docs for this command.
  72. DisableAutoGenTag bool
  73. // DisableFlagsInUseLine will disable the addition of [flags] to the usage
  74. // line of a command when printing help or generating docs
  75. DisableFlagsInUseLine bool
  76. // DisableSuggestions disables the suggestions based on Levenshtein distance
  77. // that go along with 'unknown command' messages.
  78. DisableSuggestions bool
  79. // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
  80. // Must be > 0.
  81. SuggestionsMinimumDistance int
  82. // TraverseChildren parses flags on all parents before executing child command.
  83. TraverseChildren bool
  84. // FParseErrWhitelist flag parse errors to be ignored
  85. FParseErrWhitelist FParseErrWhitelist
  86. // contains filtered or unexported fields
  87. }

func (c Command) AddCommand(cmds …Command) 向父命令添加一个或多个命令
func (c Command) PersistentFlags() flag.FlagSet PersistentFlags返回在当前命令中特定设置的持久标记集
func (c *Command) Execute() error

  • 使用args (os.Args[1:] by default),遍历命令树,找到命令的适当匹配项,然后找到相应的标志。

type PositionalArgs

  1. type PositionalArgs func(cmd *Command, args []string) error

例子

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/spf13/cobra"
  6. )
  7. // rootCmd.PersistentFlags() 中设置的参数,将被标记为 Global Flags
  8. var rootCmd = &cobra.Command{
  9. Short: "opct server",
  10. Long: "opct server",
  11. Version: "v1.0",
  12. Args: func(cmd *cobra.Command, args []string) error {
  13. if len(args) < 1 {
  14. return errors.New("requires at least one arg")
  15. }
  16. return nil
  17. },
  18. PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
  19. Run: func(cmd *cobra.Command, args []string) {
  20. usageStr := `欢迎使用 四格自动化运维平台,可以使用 -h 查看命令`
  21. fmt.Println(usageStr)
  22. },
  23. }
  24. var (
  25. config string
  26. casbinModel string
  27. StartCmd = &cobra.Command{
  28. Use: "start",
  29. Short: "Start API server",
  30. Example: "OPCT server -c config/settings.yml -m config/casbin_model.conf",
  31. PreRun: func(cmd *cobra.Command, args []string) {
  32. // 初始化项目配置
  33. setup()
  34. },
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. return start()
  37. },
  38. }
  39. StartCmd2 = &cobra.Command{
  40. Use: "start2",
  41. Short: "Start2 API server",
  42. Example: "OPCT server -c config/settings.yml -m config/casbin_model.conf",
  43. PreRun: func(cmd *cobra.Command, args []string) {
  44. // 初始化项目配置
  45. setup()
  46. },
  47. RunE: func(cmd *cobra.Command, args []string) error {
  48. return start2()
  49. },
  50. }
  51. )
  52. func init() {
  53. rootCmd.AddCommand(StartCmd) // rootCmd 增加子命令行
  54. StartCmd.AddCommand(StartCmd2)
  55. // StartCmd 增加命令行参数
  56. StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/app.toml", "Start server with provided configuration file")
  57. StartCmd.PersistentFlags().StringVarP(&casbinModel, "casbinmodel", "m", "config/casbin_model.conf", "Start server with provided casbinmodel file")
  58. }
  59. func main() {
  60. if err := rootCmd.Execute(); err != nil {
  61. os.Exit(-1)
  62. }
  63. }
  64. func setup() {
  65. // 在start()之前运行,用作初始化项目
  66. }
  67. func start() error {
  68. fmt.Println(config)
  69. fmt.Println(casbinModel)
  70. return nil
  71. }
  72. func start2() error {
  73. fmt.Println("-------------------")
  74. return nil
  75. }

二级及更低等级命名的执行,必须带上它父级与更高级的执行命令
image.png