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 https://gohugo.io/documentation/`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, }
var tryCmd = &cobra.Command{ Use: "try", Short: "Try and possibly fail at something", RunE: func(cmd *cobra.Command, args []string)error { if err := someFunc(); err != nil { return err } returnnil }, }
添加 flags
Flags 分:
Persistent Flags, 子命令同样可以用
Local Flags, 当前命令使用
如给 rootCmd 添加 Persistent flag, 且为 Bool 类型, 如:
1 2
var Verbose bool rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
解释 BoolVarP 的几个参数:
&Verbose, 表明从命令行获取到的参数保存到这个变量中
verbose 为 long
v 为 short
false 为初始值
verbose output 为 help 打印的信息
给 localCmd 添加 Local flag, 且为 String 类型, 如:
1 2
var Source string localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Required flags
即必须附带上的 flag:
1 2
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") rootCmd.MarkFlagRequired("region")
Flag Groups
即多个 flag 必须一起使用(或不能一起使用)才行.
需一起使用如:
1 2 3
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") rootCmd.MarkFlagsRequiredTogether("username", "password")
不能一起使用如:
1 2 3
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
其中一个 persistent:
1 2 3 4
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") rootCmd.MarkFlagsOneRequired("json", "yaml") rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
Positional and Custom Arguments
都在 Args 之下设置.
参数数量设置:
NoArgs
ArbitraryArgs
MinimumNArgs(int)
MaximumNArgs(int)
ExactArgs(int)
RangeArgs(min, max)
参数的内容:
OnlyValidArgs
如:
1 2 3 4 5 6 7 8 9 10
var cmdPrint = &cobra.Command{ Use: "print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, }