command
推荐学习:
快速使用
安装cobra生成器
命令:
go get -u github.com/spf13/cobra/cobra
同时需要确保cobra被添加到PATH环境中
cobra -h
这个命令相当于在你电脑全局安装一个cobra生成器,(类似于脚手架),可以帮助你快速搭建一个cli应用。
看看他有哪些命令可以帮助到你
Available Commands:
add Add a command to a Cobra Application //添加命令到cobra的应用中
completion generate the autocompletion script for the specified shell //为指定的 shell 生成自动完成脚本
help Help about any command //帮助信息关于其他命令
init Initialize a Cobra Application //初始化一个cobra的应用
初始化cobra应用
cobra init --pkg-name {填你的mod名称,否则会报错}
报错原因很简单,就是找不到本地库。如果你手动导入过本地库就知道了。
他就会生成以下文件:
C:.
│ go.mod //modules
│ LICENSE //版权信息
│ main.go //入口文件
└─cmd
root.go //根命令
介绍主要函数用处
// EExecute 将所有子命令添加到根命令并适当设置标志。
// 这是由 main.main() 调用的。 它只需要对 rootCmd 发生一次。
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
rootcmd作为一个根命令去启动。(你可以把它当作一个启动命令)
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
//标志可以是 "persistent" 的,这意味着该标志将可用于分配给它的命令以及该命令下的每个命令。对于全局标志,将标志分配为根上的持久标志。
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
//也可以在本地分配一个标志,该标志仅适用于该特定命令。
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
这个就是一个初始化函数,当main去引用这包时候进行初始化操作,可以设置一些标志,通过控制标志达到完成相关命令的能力。
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "demo",
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. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
下面是command的类的每一个字段,可以选择需要的作为这个命令使用。
// Command代表执行命令的结构
type Command struct {
// 代表当前命令的,如何执行,root 最好和生成的命令工具名称一致
Use string
// 代表这个工具的别名,在 subCommand 中有用,比如 root cmd1 和 root cmd_1 想要都执行一个 subCommand 就需要这样
Aliases []string
// 由于不强制设置,用于输入错误的时候建议字段
SuggestFor []string
// 这个就是在 help 的时候一句话描述这个命令的功能
Short string
// 详细描述这个命令的功能
Long string
// 例子
Example string
// 需要验证的参数
ValidArgs []string
// 有多少个参数,这里放了一个验证函数,可以是 ExactArgs,MaximumNArgs 等,验证有多少个参数
Args PositionalArgs
// 参数别名
ArgAliases []string
// 自动生成的命令设置
BashCompletionFunction string
// 如果这个命令已经废弃了,那么就这里写上废弃信息
Deprecated string
// 如果这个命令要被隐藏,设置这个字段
Hidden bool
// Annotations are key/value pairs that can be used by applications to identify or
// group commands.
Annotations map[string]string
// 这个命令的版本
Version string
// 是否要打印错误信息
SilenceErrors bool
// 是否要打印如何使用
SilenceUsage bool
// 是否有 flag,如果这个命令没有 flag,设置为 true,那么所有的命令后面的参数都会是 arguments
DisableFlagParsing bool
// 是否打印自动生成字样: ("Auto generated by spf13/cobra...")
DisableAutoGenTag bool
// 是否显示[flags]字样
DisableFlagsInUseLine bool
// 是否打印建议
DisableSuggestions bool
// 两个字符串的差距多少会进入 suggest
SuggestionsMinimumDistance int
// 是否使用 Traverse 的方式来解析参数
TraverseChildren bool
// 解析错误白名单, 比如像未知参数
FParseErrWhitelist FParseErrWhitelist
// The *Run 函数运行顺序:
// * PersistentPreRun()
// * PreRun()
// * Run()
// * PostRun()
// * PersistentPostRun()
// 会被继承的前置 Run
PersistentPreRun func(cmd *Command, args []string)
// 会被继承的前置 Run, 带 error
PersistentPreRunE func(cmd *Command, args []string) error
// 当前这个命令的前置 Run
PreRun func(cmd *Command, args []string)
// 当前这个命令的前置 Run,带 Error
PreRunE func(cmd *Command, args []string) error
// zh: 实际跑的时候运行的函数
Run func(cmd *Command, args []string)
// zh: Run 执行错误了之后
RunE func(cmd *Command, args []string) error
// 后置运行
PostRun func(cmd *Command, args []string)
// 后置运行,带 error
PostRunE func(cmd *Command, args []string) error
// 会被继承的后置运行
PersistentPostRun func(cmd *Command, args []string)
// 会被继承的后置运行,带 error
PersistentPostRunE func(cmd *Command, args []string) error
}
添加命令
命令行输入:
cobra add version
你就会发现你的cmd文件里面就会多一个文件version.go
go build之后,你在去跑命令,你就会发现就会有一个子命令。
Usage:
demo [command]
Available Commands:
completion generate the autocompletion script for the specified shell
help Help about any command
version A brief description of your command
Flags:
--config string config file (default is $HOME/.demo.yaml)
-h, --help help for demo
-t, --toggle Help message for toggle
你就可以按照常用的方式去使用命令行。
PS C:\Users\Y\Desktop\yay-guide\go-test\cobra> .\demo.exe version
version called
后续会根据我搭建的一个web应用骨架去讲述一个实例。