- Command">type Command
- PositionalArgs">type PositionalArgs
- 例子
cobra包是一个指挥官,提供了一个简单的接口来创建强大的现代CLI接口。除了提供接口之外,Cobra还提供了一个控制器来组织应用程序代码。
文档:https://godoc.org/github.com/spf13/cobra
type Command
type Command struct {
// Use是一行用法消息,rootcmd 可以忽略它
Use string
// 别名是一个别名数组,可以用来代替使用的第一个单词
Aliases []string
// Short是在“help”输出中显示的简短描述
Short string
// Long是'help <this-command>'输出中显示的长消息
Long string
// Example 是显示如何使用命令
Example string
// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
ValidArgs []string
// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
// It is a dynamic version of using ValidArgs.
// Only one of ValidArgs and ValidArgsFunction can be used for a command.
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
// 所有参数
Args PositionalArgs
// ArgAliases is List of aliases for ValidArgs.
// These are not suggested to the user in the bash completion,
// but accepted if entered manually.
ArgAliases []string
// BashCompletionFunction is custom functions used by the bash autocompletion generator.
BashCompletionFunction string
// Deprecated defines, if this command is deprecated and should print this string when used.
Deprecated string
// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
Hidden bool
// Annotations are key/value pairs that can be used by applications to identify or
// group commands.
Annotations map[string]string
// 定义一个version标识,可通过 version 或 -v 查看
Version string
// Run函数按以下顺序执行:
// * PersistentPreRun()
// * PreRun()
// * Run()
// * PostRun()
// * PersistentPostRun()
// 所有函数都得到相同的参数,即命令名后面的参数.
//
// PersistentPreRun: children of this command will inherit and execute.
PersistentPreRun func(cmd *Command, args []string)
// PersistentPreRunE: PersistentPreRun but returns an error.
PersistentPreRunE func(cmd *Command, args []string) error
// PreRun: children of this command will not inherit.
PreRun func(cmd *Command, args []string)
// PreRunE: PreRun but returns an error.
PreRunE func(cmd *Command, args []string) error
// Run: Typically the actual work function. Most commands will only implement this.
Run func(cmd *Command, args []string)
// RunE: Run but returns an error.
RunE func(cmd *Command, args []string) error
// PostRun: run after the Run command.
PostRun func(cmd *Command, args []string)
// PostRunE: PostRun but returns an error.
PostRunE func(cmd *Command, args []string) error
// PersistentPostRun: children of this command will inherit and execute after PostRun.
PersistentPostRun func(cmd *Command, args []string)
// PersistentPostRunE: PersistentPostRun but returns an error.
PersistentPostRunE func(cmd *Command, args []string) error
// 对下游的错误进行屏蔽
SilenceErrors bool
// 对错误用法进行屏蔽
SilenceUsage bool
// 禁用标志解析.
// 如果为真,所有标志都将作为参数传递给该命令
DisableFlagParsing bool
// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
// will be printed by generating docs for this command.
DisableAutoGenTag bool
// DisableFlagsInUseLine will disable the addition of [flags] to the usage
// line of a command when printing help or generating docs
DisableFlagsInUseLine bool
// DisableSuggestions disables the suggestions based on Levenshtein distance
// that go along with 'unknown command' messages.
DisableSuggestions bool
// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
// Must be > 0.
SuggestionsMinimumDistance int
// TraverseChildren parses flags on all parents before executing child command.
TraverseChildren bool
// FParseErrWhitelist flag parse errors to be ignored
FParseErrWhitelist FParseErrWhitelist
// contains filtered or unexported fields
}
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
type PositionalArgs func(cmd *Command, args []string) error
例子
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
// rootCmd.PersistentFlags() 中设置的参数,将被标记为 Global Flags
var rootCmd = &cobra.Command{
Short: "opct server",
Long: "opct server",
Version: "v1.0",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires at least one arg")
}
return nil
},
PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
Run: func(cmd *cobra.Command, args []string) {
usageStr := `欢迎使用 四格自动化运维平台,可以使用 -h 查看命令`
fmt.Println(usageStr)
},
}
var (
config string
casbinModel string
StartCmd = &cobra.Command{
Use: "start",
Short: "Start API server",
Example: "OPCT server -c config/settings.yml -m config/casbin_model.conf",
PreRun: func(cmd *cobra.Command, args []string) {
// 初始化项目配置
setup()
},
RunE: func(cmd *cobra.Command, args []string) error {
return start()
},
}
StartCmd2 = &cobra.Command{
Use: "start2",
Short: "Start2 API server",
Example: "OPCT server -c config/settings.yml -m config/casbin_model.conf",
PreRun: func(cmd *cobra.Command, args []string) {
// 初始化项目配置
setup()
},
RunE: func(cmd *cobra.Command, args []string) error {
return start2()
},
}
)
func init() {
rootCmd.AddCommand(StartCmd) // rootCmd 增加子命令行
StartCmd.AddCommand(StartCmd2)
// StartCmd 增加命令行参数
StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/app.toml", "Start server with provided configuration file")
StartCmd.PersistentFlags().StringVarP(&casbinModel, "casbinmodel", "m", "config/casbin_model.conf", "Start server with provided casbinmodel file")
}
func main() {
if err := rootCmd.Execute(); err != nil {
os.Exit(-1)
}
}
func setup() {
// 在start()之前运行,用作初始化项目
}
func start() error {
fmt.Println(config)
fmt.Println(casbinModel)
return nil
}
func start2() error {
fmt.Println("-------------------")
return nil
}
二级及更低等级命名的执行,必须带上它父级与更高级的执行命令