Available Commands: add Add a command to a Cobra Application # 添加子命令 help Help about any command # 帮助信息 init Initialize a Cobra Application # 初始化一个命令
Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") # 指定作者 --config string config file (default is $HOME/.cobra.yaml) # 指定配置文件 -h, --help help for cobra -l, --license string name of license for the project # 指定项目的 license,默认基于 Apache 2.0 --viper use Viper for configuration (default true)
// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "cli", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your application.`, // Uncomment the following line if your bare application // has an action associated with it: // Run: func(cmd *cobra.Command, args []string) { }, }
// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. funcExecute() { cobra.CheckErr(rootCmd.Execute()) }
可通过 cobra add <subcommand> 添加子命令,如 cobra add app.
cobra 会自动生成 app 子命令的相关代码.
1 2 3 4 5 6 7 8 9 10 11 12 13
var appCmd = &cobra.Command{ Use: "app", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("app called") }, } // 在 init() 中 rootCmd 添加了 appCmd 子命令. AddCommand 可以在父命令中添加子命令 funcinit() { rootCmd.AddCommand(appCmd) }
type Command struct { Use string// 单行的用法信息,可以理解为为命令名称 Aliases []string// 命令别名 Short string// 短帮助信息 Long string// 长帮助信息 Example string// 命令的用法示例 ValidArgs []string// 命令行中传入非标志位参数的有效列表 // ValidArgsFunction 用于判断命令行中传入非标志位参数是否有效 ValidArgsFunction func(cmd *Command, args []string, toComplete string)([]string, ShellCompDirective) Args PositionalArgs // 限定命令行参数,见 Args 小节 BashCompletionFunction string// 生成命令行补全命令的函数 Deprecated string// 过期命令执行时打印的内容 Version string// 定义命令版本内容,一般使用 cmd.SetVersionTemplate() 设置版本信息
// *Run func(cmd *cobra.Command, args []string) // The *Run functions are executed in the following order: // * PersistentPreRun() // * PreRun() // * Run() // * PostRun() // * PersistentPostRun() // All functions get the same args, the arguments after the command name.
Inside rootCmd PersistentPreRun with args: [] Inside rootCmd PreRun with args: [] Inside rootCmd Run with args: [] Inside rootCmd PostRun with args: [] Inside rootCmd PersistentPostRun with args: []
Inside rootCmd PersistentPreRun with args: [arg1 arg2] Inside subCmd PreRun with args: [arg1 arg2] Inside subCmd Run with args: [arg1 arg2] Inside subCmd PostRun with args: [arg1 arg2] Inside subCmd PersistentPostRun with args: [arg1 arg2]