varrootCmd=&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
},}funcExecute(){iferr:=rootCmd.Execute();err!=nil{fmt.Println(err)os.Exit(1)}}
import("fmt""os"homedir"github.com/mitchellh/go-homedir""github.com/spf13/cobra""github.com/spf13/viper")funcinit(){cobra.OnInitialize(initConfig)rootCmd.PersistentFlags().StringVar(&cfgFile,"config","","config file (default is $HOME/.cobra.yaml)")rootCmd.PersistentFlags().StringVarP(&projectBase,"projectbase","b","","base project directory eg. github.com/spf13/")rootCmd.PersistentFlags().StringP("author","a","YOUR NAME","Author name for copyright attribution")rootCmd.PersistentFlags().StringVarP(&userLicense,"license","l","","Name of license for the project (can provide `licensetext` in config)")rootCmd.PersistentFlags().Bool("viper",true,"Use Viper for configuration")viper.BindPFlag("author",rootCmd.PersistentFlags().Lookup("author"))viper.BindPFlag("projectbase",rootCmd.PersistentFlags().Lookup("projectbase"))viper.BindPFlag("useViper",rootCmd.PersistentFlags().Lookup("viper"))viper.SetDefault("author","NAME HERE <EMAIL ADDRESS>")viper.SetDefault("license","apache")}funcinitConfig(){// Don't forget to read config either from cfgFile or from home directory!
// 不要忘记从cfgFile或家目录读取配置!
ifcfgFile!=""{// Use config file from the flag.
// 使用配置文件中的标志。
viper.SetConfigFile(cfgFile)}else{// Find home directory.
// 查找家目录。
home,err:=homedir.Dir()iferr!=nil{fmt.Println(err)os.Exit(1)}// Search config in home directory with name ".cobra" (without extension).
// 在家目录中搜索名为".cobra"的配置文件(不包括扩展名)。
viper.AddConfigPath(home)viper.SetConfigName(".cobra")}iferr:=viper.ReadInConfig();err!=nil{fmt.Println("Can't read config:",err)os.Exit(1)}}
创建您的main.go
With the root command you need to have your main function execute it. Execute should be run on the root for clarity, though it can be called on any command.
有了 root 命令,您需要在 main 函数执行它。为了清晰起见,应该在 root 上调用 Execute,尽管可以在任何命令上调用它。
packagecmdimport("fmt""github.com/spf13/cobra")funcinit(){rootCmd.AddCommand(versionCmd)}varversionCmd=&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")},}
varauthorstringfuncinit(){rootCmd.PersistentFlags().StringVar(&author,"author","YOUR NAME","Author name for copyright attribution")viper.BindPFlag("author",rootCmd.PersistentFlags().Lookup("author"))}
varcmd=&cobra.Command{Short:"hello",Args:func(cmd*cobra.Command,args[]string)error{iflen(args)<1{returnerrors.New("requires at least one arg")}ifmyapp.IsValidColor(args[0]){returnnil}returnfmt.Errorf("invalid color specified: %s",args[0])},Run:func(cmd*cobra.Command,args[]string){fmt.Println("Hello, World!")},}
packagemainimport("fmt""strings""github.com/spf13/cobra")funcmain(){varechoTimesintvarcmdPrint=&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," "))},}varcmdEcho=&cobra.Command{Use:"echo [string to echo]",Short:"Echo anything to the screen",Long:`echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,Args:cobra.MinimumNArgs(1),Run:func(cmd*cobra.Command,args[]string){fmt.Println("Print: "+strings.Join(args," "))},}varcmdTimes=&cobra.Command{Use:"times [# times] [string to echo]",Short:"Echo anything to the screen more times",Long:`echo things multiple times back to the user by providing
a count and a string.`,Args:cobra.MinimumNArgs(1),Run:func(cmd*cobra.Command,args[]string){fori:=0;i<echoTimes;i++{fmt.Println("Echo: "+strings.Join(args," "))}},}cmdTimes.Flags().IntVarP(&echoTimes,"times","t",1,"times to echo the input")varrootCmd=&cobra.Command{Use:"app"}rootCmd.AddCommand(cmdPrint,cmdEcho)cmdEcho.AddCommand(cmdTimes)rootCmd.Execute()}
$ cobra helpCobra 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.
Usage:
cobra [command]Available Commands:
add Add a command to a Cobra Application
help Help about any command init Initialize a Cobra Application
Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) -h, --help helpfor cobra
-l, --license string name of license for the project
--viper use Viper for configuration (default true)Use "cobra [command] --help"for more information about a command.
$ cobra --invalid
Error: unknown flag: --invalid
Usage:
cobra [command]Available Commands:
add Add a command to a Cobra Application
help Help about any command init Initialize a Cobra Application
Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) -h, --help helpfor cobra
-l, --license string name of license for the project
--viper use Viper for configuration (default true)Use "cobra [command] --help"for more information about a command.
如果根命令的 Version 字段已设置,Cobra会添加顶层的"--version“标志。使用”--version“标志运行应用程序将使用版本模板将版本打印到标准输出(stdout)。可以使用 cmd.SetVersionTemplate(s string) 函数自定义模板。
PreRun和PostRung钩子 - PreRun and PostRun Hooks
It is possible to run functions before or after the main Run function of your command. The PersistentPreRun and PreRun functions will be executed before Run. PersistentPostRun and PostRun will be executed after Run. The Persistent*Run functions will be inherited by children if they do not declare their own. These functions are run in the following order:
您可以在命令的主要 Run 函数之前或之后运行函数。PersistentPreRun 和 PreRun 函数将在 Run 函数之前执行。PersistentPostRun 和 PostRun 将在 Run 之后执行。如果子命令没有声明自己的钩子函数,它们将继承 Persistent*Run 函数。这些函数按照以下顺序运行:
packagemainimport("fmt""github.com/spf13/cobra")funcmain(){varrootCmd=&cobra.Command{Use:"root [sub]",Short:"My root command",PersistentPreRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n",args)},PreRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside rootCmd PreRun with args: %v\n",args)},Run:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside rootCmd Run with args: %v\n",args)},PostRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside rootCmd PostRun with args: %v\n",args)},PersistentPostRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n",args)},}varsubCmd=&cobra.Command{Use:"sub [no options!]",Short:"My subcommand",PreRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside subCmd PreRun with args: %v\n",args)},Run:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside subCmd Run with args: %v\n",args)},PostRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside subCmd PostRun with args: %v\n",args)},PersistentPostRun:func(cmd*cobra.Command,args[]string){fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n",args)},}rootCmd.AddCommand(subCmd)rootCmd.SetArgs([]string{""})rootCmd.Execute()fmt.Println()rootCmd.SetArgs([]string{"sub","arg1","arg2"})rootCmd.Execute()}
输出结果:
Inside rootCmd PersistentPreRun with args: []
Inside rootCmd PreRun with args: []
Inside rootCmd Run with args: []
Inside rootCmd PostRun with args: []
Inside rootCmd PersistentPostRun with args: []
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
Inside subCmd PreRun with args: [arg1 arg2]
Inside subCmd Run with args: [arg1 arg2]
Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]