1// Copyright © 2015 Steve Francia <spf@spf13.com>.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package main
15
16import (
17 "os"
18
19 "github.com/spf13/cobra/cobra/cmd"
20)
21
22func main() {
23 if err := cmd.Execute(); err != nil {
24 os.Exit(1)
25 }
26}
main.go 调用了 cmd
的 Excute
函数,如果没有错误信息则正常退出
1var (
2 // Used for flags.
3 cfgFile string
4 userLicense string
5
6 rootCmd = &cobra.Command{
7 Use: "cobra",
8 Short: "A generator for Cobra based Applications",
9 Long: `Cobra is a CLI library for Go that empowers applications.
10This application is a tool to generate the needed files
11to quickly create a Cobra application.`,
12 }
13)
首先定义了一些变量,cfgFile,userLicense,rootCmd
其中 rootCmd 是指针类型的 Command 结构体,传入了 Use,Short,Long,看一下 cobra 包下的 Command 结构体类型
1type Command struct {
2 // Use is the one-line usage message.
3 Use string
4
5 // Aliases is an array of aliases that can be used instead of the first word in Use.
6 Aliases []string
7
8 // SuggestFor is an array of command names for which this command will be suggested -
9 // similar to aliases but only suggests.
10 SuggestFor []string
11
12 // Short is the short description shown in the 'help' output.
13 Short string
14
15 // Long is the long message shown in the 'help <this-command>' output.
16 Long string
17
18 // Example is examples of how to use the command.
19 Example string
20
21 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
22 ValidArgs []string
23 // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
24 // It is a dynamic version of using ValidArgs.
25 // Only one of ValidArgs and ValidArgsFunction can be used for a command.
26 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
27
28 // Expected arguments
29 Args PositionalArgs
30
31 // ArgAliases is List of aliases for ValidArgs.
32 // These are not suggested to the user in the bash completion,
33 // but accepted if entered manually.
34 ArgAliases []string
35
36 // BashCompletionFunction is custom functions used by the bash autocompletion generator.
37 BashCompletionFunction string
38
39 // Deprecated defines, if this command is deprecated and should print this string when used.
40 Deprecated string
41
42 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
43 Hidden bool
44
45 // Annotations are key/value pairs that can be used by applications to identify or
46 // group commands.
47 Annotations map[string]string
48
49 // Version defines the version for this command. If this value is non-empty and the command does not
50 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
51 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
52 // command does not define one.
53 Version string
54
55 // The *Run functions are executed in the following order:
56 // * PersistentPreRun()
57 // * PreRun()
58 // * Run()
59 // * PostRun()
60 // * PersistentPostRun()
61 // All functions get the same args, the arguments after the command name.
62 //
63 // PersistentPreRun: children of this command will inherit and execute.
64 PersistentPreRun func(cmd *Command, args []string)
65 // PersistentPreRunE: PersistentPreRun but returns an error.
66 PersistentPreRunE func(cmd *Command, args []string) error
67 // PreRun: children of this command will not inherit.
68 PreRun func(cmd *Command, args []string)
69 // PreRunE: PreRun but returns an error.
70 PreRunE func(cmd *Command, args []string) error
71 // Run: Typically the actual work function. Most commands will only implement this.
72 Run func(cmd *Command, args []string)
73 // RunE: Run but returns an error.
74 RunE func(cmd *Command, args []string) error
75 // PostRun: run after the Run command.
76 PostRun func(cmd *Command, args []string)
77 // PostRunE: PostRun but returns an error.
78 PostRunE func(cmd *Command, args []string) error
79 // PersistentPostRun: children of this command will inherit and execute after PostRun.
80 PersistentPostRun func(cmd *Command, args []string)
81 // PersistentPostRunE: PersistentPostRun but returns an error.
82 PersistentPostRunE func(cmd *Command, args []string) error
83
84 // SilenceErrors is an option to quiet errors down stream.
85 SilenceErrors bool
86
87 // SilenceUsage is an option to silence usage when an error occurs.
88 SilenceUsage bool
89
90 // DisableFlagParsing disables the flag parsing.
91 // If this is true all flags will be passed to the command as arguments.
92 DisableFlagParsing bool
93
94 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
95 // will be printed by generating docs for this command.
96 DisableAutoGenTag bool
97
98 // DisableFlagsInUseLine will disable the addition of [flags] to the usage
99 // line of a command when printing help or generating docs
100 DisableFlagsInUseLine bool
101
102 // DisableSuggestions disables the suggestions based on Levenshtein distance
103 // that go along with 'unknown command' messages.
104 DisableSuggestions bool
105 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
106 // Must be > 0.
107 SuggestionsMinimumDistance int
108
109 // TraverseChildren parses flags on all parents before executing child command.
110 TraverseChildren bool
111
112 // FParseErrWhitelist flag parse errors to be ignored
113 FParseErrWhitelist FParseErrWhitelist
114
115 ctx context.Context
116
117 // commands is the list of commands supported by this program.
118 commands []*Command
119 // parent is a parent command for this command.
120 parent *Command
121 // Max lengths of commands' string lengths for use in padding.
122 commandsMaxUseLen int
123 commandsMaxCommandPathLen int
124 commandsMaxNameLen int
125 // commandsAreSorted defines, if command slice are sorted or not.
126 commandsAreSorted bool
127 // commandCalledAs is the name or alias value used to call this command.
128 commandCalledAs struct {
129 name string
130 called bool
131 }
132
133 // args is actual args parsed from flags.
134 args []string
135 // flagErrorBuf contains all error messages from pflag.
136 flagErrorBuf *bytes.Buffer
137 // flags is full set of flags.
138 flags *flag.FlagSet
139 // pflags contains persistent flags.
140 pflags *flag.FlagSet
141 // lflags contains local flags.
142 lflags *flag.FlagSet
143 // iflags contains inherited flags.
144 iflags *flag.FlagSet
145 // parentsPflags is all persistent flags of cmd's parents.
146 parentsPflags *flag.FlagSet
147 // globNormFunc is the global normalization function
148 // that we can use on every pflag set and children commands
149 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
150
151 // usageFunc is usage func defined by user.
152 usageFunc func(*Command) error
153 // usageTemplate is usage template defined by user.
154 usageTemplate string
155 // flagErrorFunc is func defined by user and it's called when the parsing of
156 // flags returns an error.
157 flagErrorFunc func(*Command, error) error
158 // helpTemplate is help template defined by user.
159 helpTemplate string
160 // helpFunc is help func defined by user.
161 helpFunc func(*Command, []string)
162 // helpCommand is command with usage 'help'. If it's not defined by user,
163 // cobra uses default help command.
164 helpCommand *Command
165 // versionTemplate is the version template defined by user.
166 versionTemplate string
167
168 // inReader is a reader defined by the user that replaces stdin
169 inReader io.Reader
170 // outWriter is a writer defined by the user that replaces stdout
171 outWriter io.Writer
172 // errWriter is a writer defined by the user that replaces stderr
173 errWriter io.Writer
174}
Command 结构体中定义了好多属性,挨个看看都是干嘛的
variable | type | description |
---|---|---|
Use | String | 一行如何使用 Command 的信息 |
Aliases | []string | Command 的别名数组 |
SuggestFor | []string | 建议使用此命令的命令名称数组,建议 |
Short | []string | 帮助输出中显示的简短描述。 |
Long | []string | 帮助输出中显示的长 miao shu |
Example | string | 如何使用 Command 的信息 |
ValidArgs | []string | bash 中接受的所有有效,非标志参数的列表 |
ValidArgsFunction | func(*Command,args[]string,toComplete string)([]string,ShellCompDirective) | 和 ValidArgs 相同,但提供函数,二者只能选一种 |
Args | PositionalArgs | 预期参数 |
ArgAliases | []string | ValidArgs 的别名列表 |
BashCompletionFunction | string | bash 自动完成生成器使用的自定义函数 |
Deprecated | string | 弃用信息 |
Hidden | bool | 是否隐藏 |
Annotations | map[string]string | 可供应用程序用来识别或分组 |
Version | string | 版本号 |
PresistentPreRun | func(cmd*Command,args []string) | 此命令的子级将继承并执行。 |
PresistentPreRunE | func(cmd *Command,args []string)error | 此命令的子级将继承并执行,返回 error |
PreRun | func(cmd *Command,args []string) | 此命令的子级将不会继承 |
PreRunE | func(cmd *Command,args []string)error | 同上但返回 error |
PostRun | func(cmd *Command,args []string) | 在 Run 后执行 Command |
PostRunE | ||
Run | func(cmd *Command,args []string) | run |
RunE | ||
PresistenPostRun | func(cmd *Command,args []string) | |
PresistenPostRunE | ||
SilenceErrors | bool | |
SilenceUsage | bool | |
DisableFlagParsing | bool | 禁用 flag 解析 |
DsiableAutoGenTag | bool | 是否通过生成此命令的文档来打印 gen 标签 |
DsiableFlagsInUseLine | bool | 当打印帮助或生成文档时,将禁止在命令的行中添加[flags] |
DisableSuggestions | bool | |
SuggestionsMiniumDistance | int | |
TravereChildren | bool | 在执行子命令之前解析所有父项上的标志。 |
FParseErrWhitelist | FParseErrWhitelist | 标志解析要忽略的错误 |
ctx | context.Context | |
commands | []*Command | 程序支持的命令列表 |
parent | *Command | 此命令的父命令 |
commandsMaxUseLen | int | 用于填充的命令字符串最大长度 |
commandsMaxCommandPathLen | int | |
commandsMaxNameLen | int | |
commandAreSorted | bool | 是否对命令片排序 |
commandCalledAs | struct{name sstring,called bool} | 调用此命令的名称或别名值 |
args | []strings | 从标志解析的实际 args |
flagErrorBuf | *bytes.Buffer | 包含来自 pflag 的所有错误消息。 |
flags | *flag.FlagSet | 标志 |
pflags | *flag.FlagSet | persistent 标志 |
lflags | *flag.FlagSet | local 标志 |
iflags | *flag.FlagSet | inherited 标志 |
parentsPflags | *flag.FlagSet | cmd 父母的所有永久标志 |
globNormFunc | func(f *flag.FlagSet,name string)flag.NormalizedName | 全局函数 |
useageFunc | func(*Command)error | 用户定义的用法功能 |
flagErrorFunc | func(*Command,error)error | |
helpTemplate | string | 用户定义的帮助模板 |
helpFunc | func(*Command,[]string) | 用户定义的帮助功能 |
helpCommand | *Command | 用法为“ help”的命令 |
versionTemplate | string | 用户定义的版本模板 |
inReader | io.Reader | stdin |
outWriter | io.Writer | stdout |
errWriter | io.Writer | stderr |
然后是 init 函数,使用 root 文件 cmd.Excute 时自动调用
1cobra.OnInitialize(initConfig)
这条代码调用到
1func SetConfigFile(in string) { v.SetConfigFile(in) }
2func (v *Viper) SetConfigFile(in string) {
3 if in != "" {
4 v.configFile = in
5 }
6}
SetConfigFile
调用结构体 Viper
的 SetConfigFIle 函数
viper 包的 init
函数
1func New() *Viper {
2 v := new(Viper)
3 v.keyDelim = "."
4 v.configName = "config"
5 v.configPermissions = os.FileMode(0644)
6 v.fs = afero.NewOsFs()
7 v.config = make(map[string]interface{})
8 v.override = make(map[string]interface{})
9 v.defaults = make(map[string]interface{})
10 v.kvstore = make(map[string]interface{})
11 v.pflags = make(map[string]FlagValue)
12 v.env = make(map[string]string)
13 v.aliases = make(map[string]string)
14 v.typeByDefValue = false
15
16 return v
17}
viper 是个什么东西呢,康康
1type Viper struct {
2 // 分隔键列表的定界符
3 // 用于一次性访问嵌套值
4 keyDelim string
5
6 // 查找配置文件的路径
7 configPaths []string
8
9 // 读取配置文件地址的类型
10 fs afero.Fs
11
12 // 一组远程提供程序以搜索配置
13 remoteProviders []*defaultRemoteProvider
14
15 // 配置文件名称
16 configName string
17 configFile string
18 configType string
19 // 文件权限
20 configPermissions os.FileMode
21 // 环境前缀
22 envPrefix string
23 automaticEnvApplied bool
24 envKeyReplacer *strings.Replacer
25 allowEmptyEnv bool
26
27 config map[string]interface{}
28 override map[string]interface{}
29 defaults map[string]interface{}
30 kvstore map[string]interface{}
31 pflags map[string]FlagValue
32 env map[string]string
33 aliases map[string]string
34 typeByDefValue bool
35
36 //将读取的属性存储在对象上,以便我们可以按顺序写回并带有注释。
37 //仅当读取的配置是属性文件时才使用。
38 properties *properties.Properties
39
40 onConfigChange func(fsnotify.Event)
41}
1func SetConfigFile(in string) { v.SetConfigFile(in) }
2func (v *Viper) SetConfigFile(in string) {
3 if in != "" {
4 // 将viper结构体重的 configFile配置成
5 v.configFile = in
6 }
7}
1func initConfig() {
2 if cfgFile != "" {
3 // 如果配置了配置文件地址则 viper结构体设置此文件
4 viper.SetConfigFile(cfgFile)
5 } else {
6 // 否则从home开始找配置文件
7 home, err := homedir.Dir()
8 if err != nil {
9 er(err)
10 }
11 // viper配置寻找配置文件的目录
12 viper.AddConfigPath(home)
13 // 寻找以.cobra结尾的文件
14 viper.SetConfigName(".cobra")
15 }
16 // 自动判断系统环境并应用
17 // 这个函数将viper.automaticEnvApplied gai we
18 viper.AutomaticEnv()
19 // 如果读取配置文件出错
20 if err := viper.ReadInConfig(); err == nil {
21 fmt.Println("Using config file:", viper.ConfigFileUsed())
22 }
23}
24
然后看下一句
1rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
1// 返回当前命令中设置的持久性FlagSet
2func (c *Command) PersistentFlags() *flag.FlagSet {
3 // 如果command的pflgs-FlagSet为空
4 if c.pflags == nil {
5 // 那么新建一个
6 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
7 if c.flagErrorBuf == nil {
8 c.flagErrorBuf = new(bytes.Buffer)
9 }
10 c.pflags.SetOutput(c.flagErrorBuf)
11 }
12 // return 回这个FlagSet,指针类型
13 return c.pflags
14}
什么是 flag 呢,比如 xxx create --name ferried
,在这段 command 中,create 为 command,--name 为 create 的 flag
看一眼 FlagSet 结构体
1type FlagSet struct {
2 Usage func()
3 SortFlags bool
4 ParseErrorsWhitelist ParseErrorsWhitelist
5 name string
6 parsed bool
7 actual map[NormalizedName]*Flag
8 orderedActual []*Flag
9 sortedActual []*Flag
10 formal map[NormalizedName]*Flag
11 orderedFormal []*Flag
12 sortedFormal []*Flag
13 shorthands map[byte]*Flag
14 args []string // arguments after flags
15 argsLenAtDash int
16 errorHandling ErrorHandling
17 output io.Writer
18 interspersed bool args
19 normalizeNameFunc func(f *FlagSet, name string) NormalizedName
20 addedGoFlagSets []*goflag.FlagSet
21}
StringVar
1func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
2 f.VarP(newStringValue(value, p), name, "", usage)
3}
最后走到,新建一个 Flag,然后加入到 FlagSet 中
1func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
2 // Remember the default value as a string; it won't change.
3 flag := &Flag{
4 Name: name,
5 Shorthand: shorthand,
6 Usage: usage,
7 Value: value,
8 DefValue: value.String(),
9 }
10 f.AddFlag(flag)
11 return flag
12}
Flag 结构体,一个 FlagSet 对应多个 Flag
1type Flag struct {
2 Name string // name as it appears on command line
3 Shorthand string // one-letter abbreviated flag
4 Usage string // help message
5 Value Value // value as set
6 DefValue string // default value (as text); for usage message
7 Changed bool // If the user set the value (or if left to default)
8 NoOptDefVal string // default value (as text); if the flag is on the command line without any options
9 Deprecated string // If this flag is deprecated, this string is the new or now thing to use
10 Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
11 ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
12 Annotations map[string][]string // used by cobra.Command bash autocomple code
13}
至此一个 flag 就加入到 command 中了。
再往下看
1// 这里除了StringP 其余都与 上面的函数相同
2rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
不同点在于 shorthand
属性
举例
command create --name ferried
command create -n ferried
这里 --name 和 -n 分别对应 StringVar,StringP
再来重新对比一下三个 String 函数
1StringP
2StringVar
3StringVarP
1func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
2 p := new(string)
3 f.StringVarP(p, name, shorthand, value, usage)
4 return p
5}
1func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
2 f.VarP(newStringValue(value, p), name, "", usage)
3}
1func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
2 f.VarP(newStringValue(value, p), name, shorthand, usage)
3}
区别就在于 shorthand 和*string
再往下看
1rootCmd.PersistentFlags().Bool
1func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
2 return f.BoolP(name, "", value, usage)
3}
4
5func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
6 p := new(bool)
7 f.BoolVarP(p, name, shorthand, value, usage)
8 return p
9}
10
11func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
12 flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
13 flag.NoOptDefVal = "true"
14}
15
16func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
17 // Remember the default value as a string; it won't change.
18 flag := &Flag{
19 Name: name,
20 Shorthand: shorthand,
21 Usage: usage,
22 Value: value,
23 DefValue: value.String(),
24 }
25 f.AddFlag(flag)
26 return flag
27}
也是处理一下值的转换然后 shorhand 不同,加一个 Flag 结构体到 Command 的 pflag 中
再往下看
1// 绑定 author ,第二个参数是 查找出的flag
2viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
3
4// lookup调用了FlagSet.lookup函数,传入了normalize配置的函数来 format一下flag的name
5func (f *FlagSet) Lookup(name string) *Flag {
6 return f.lookup(f.normalizeFlagName(name))
7}
8// 最后return 出去这个Flag
9func (f *FlagSet) lookup(name NormalizedName) *Flag {
10 return f.formal[name]
11}
12// 然后调用 Viper结构体中的BindPFlag
13func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
14func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
15 return v.BindFlagValue(key, pflagValue{flag})
16}
17// return error或者nil
18func BindFlagValue(key string, flag FlagValue) error {
19 return v.BindFlagValue(key, flag)
20}
21
22func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
23 // 如果 flag为空
24 if flag == nil {
25 // 异常信息
26 return fmt.Errorf("flag for %q is nil", key)
27 }
28 // 如果可以找到,那么viper的pflugs这个FlagSet[key]设置成flag结构体,返回nil
29 v.pflags[strings.ToLower(key)] = flag
30 return nil
31}
再往下看
1 // 绑定好了就可以设置默认值了
2 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
3 viper.SetDefault("license", "apache")
看一下命令执行结果
然后看下面两条 cobra 下的子 command
1rootCmd.AddCommand(addCmd)
2rootCmd.AddCommand(initCmd)
首先定义了一些变量
1var (
2 // string变量
3 pkgName string
4 // 一个Command
5 initCmd = &cobra.Command{
6 // 一些使用命令时的输出信息
7 Use: "init [name]",
8 Aliases: []string{"initialize", "initialise", "create"},
9 Short: "Initialize a Cobra Application",
10 Long: `Initialize (cobra init) will create a new application, with a license
11and the appropriate structure for a Cobra-based CLI application.
12
13 * If a name is provided, it will be created in the current directory;
14 * If no name is provided, the current directory will be assumed;
15 * If a relative path is provided, it will be created inside $GOPATH
16 (e.g. github.com/spf13/hugo);
17 * If an absolute path is provided, it will be created;
18 * If the directory already exists but is empty, it will be used.
19
20Init will not use an existing directory with contents.`,
21
22 // 使用命令时实际运行的函数
23 // 第一参为command结构体,第二参是传入的参数
24 Run: func(cmd *cobra.Command, args []string) {
25
26 wd, err := os.Getwd()
27 if err != nil {
28 er(err)
29 }
30
31 if len(args) > 0 {
32 if args[0] != "." {
33 wd = fmt.Sprintf("%s/%s", wd, args[0])
34 }
35 }
36
37 project := &Project{
38 AbsolutePath: wd,
39 PkgName: pkgName,
40 Legal: getLicense(),
41 Copyright: copyrightLine(),
42 Viper: viper.GetBool("useViper"),
43 AppName: path.Base(pkgName),
44 }
45
46 if err := project.Create(); err != nil {
47 er(err)
48 }
49
50 fmt.Printf("Your Cobra application is ready at\n%s\n", project.AbsolutePath)
51 },
52 }
53