// A Flag represents the state of a flag. type Flag struct { Name string// name as it appears on command line Shorthand string// one-letter abbreviated flag Usage string// help message Value Value // value as set DefValue string// default value (as text); for usage message Changed bool// If the user set the value (or if left to default) NoOptDefVal string// default value (as text); if the flag is on the command line without any options Deprecated string// If this flag is deprecated, this string is the new or now thing to use Hidden bool// used by cobra.Command to allow flags to be hidden from help/usage text ShorthandDeprecated string// If the shorthand of this flag is deprecated, this string is the new or now thing to use Annotations map[string][]string// used by cobra.Command bash autocomple code }
将 Flag 的值抽象成一个 interface 接口,可以自定义 Flag 类型
1 2 3 4 5 6 7
// Value is the interface to the dynamic value stored in a flag. // (The default value is represented as a string.) type Value interface { String() string// 将 Flag 类型的值转换为 string 类型的值,并返回 string 的内容 Set(string) error// 将 string 类型的值转换为 Flag 类型的值,转换失败报错 Type() string// 返回 Flag 的类型,如 string、int 等 }
var version string flags.StringVar(&version, "version", "v1.0.0", "Print version information and quit.")
err := flags.Parse(os.Args[1:]) if err != nil { panic(err) }
fmt.Printf("version: %+v\n", version) }
1 2
$ ./main --version v1.0.1 version: v1.0.1
CommandLine
使用全局 FlagSet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package main
import ( "fmt" "github.com/spf13/pflag" )
funcmain() { var version string pflag.StringVar(&version, "version", "v1.0.0", "Print version information and quit.")
pflag.Parse()
fmt.Printf("version: %+v\n", version) }
1 2
$ ./main --version v1.0.2 version: v1.0.2
CommandLine 是一个包级别的变量
1 2 3 4 5 6 7 8
// StringVar defines a string flag with specified name, default value, and usage string. // The argument p points to a string variable in which to store the value of the flag. funcStringVar(p *string, name string, value string, usage string) { CommandLine.VarP(newStringValue(value, p), name, "", usage) }
// CommandLine is the default set of command-line flags, parsed from os.Args. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
如果不需要定义子命令,可以直接使用 CommandLine
Usage
参数定义
函数名带 Var 将标志的值绑定到变量,否则将标志的值存储到指针中
函数名带 P 说明支持短选项,否则不支持短选项
支持长选项、默认值和使用文本,并将标志的值存储在指针中
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package main
import ( "github.com/spf13/pflag" "reflect" )
funcmain() { name := pflag.String("name", "zhongmingmao", "Input Your Name") pflag.Parse()
$ ./main --age 11.0 invalid argument "11.0" for "--age" flag: strconv.ParseInt: parsing "11.0": invalid syntax Usage of ./main: --age int age of the person (default 10) invalid argument "11.0" for "--age" flag: strconv.ParseInt: parsing "11.0": invalid syntax
$ echo $? 2
非选项参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package main
import ( "fmt" "github.com/spf13/pflag" )
funcmain() { name := pflag.String("name", "zhongmingmao", "help message for name")
fmt.Printf("Used configuration file is: %s\n", viper.ConfigFileUsed()) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
$ ./main --help Usage of ./main: -c, --config string Configuration file. -h, --help Show this help message. $ ./main -c config.yaml Used configuration file is: config.yaml
$ tree . ├── config ├── config.yaml ├── go.mod ├── go.sum ├── main └── main.go
$ ./main Used configuration file is: /Users/zhongmingmao/workspace/go/src/github.com/zhongmingmao/go101/config.yaml
var rootCmd = &cobra.Command{ Use: "hugo", Short: "Hugo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, }
var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of Hugo", Long: `All software has versions. This is Hugo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") }, }
compile & run
1 2 3 4
$ go build -v . github.com/spf13/cobra github.com/zhongmingmao/cobra101/cmd github.com/zhongmingmao/cobra101
$ ./cobra101 -h A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com
Usage: hugo [flags] hugo [command]
Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command version Print the version number of Hugo
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 hugo -l, --license licensetext Name of license for the project (can provide licensetext in config) -b, --projectbase string base project directory eg. github.com/spf13/ --viper Use Viper for configuration (default true)
Use "hugo [command] --help" for more information about a command.