命令行工具cobra的使用
生活随笔
收集整理的這篇文章主要介紹了
命令行工具cobra的使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
安裝cobra
go get -v github.com/spf13/cobra/cobra切換到GOPATH的src目錄下并創(chuàng)建一個(gè)新文件夾:demo
cd $GOPATH/src mkdir demo cd demo初始cobra
$ ../../bin/cobra Cobra 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 Applicationhelp Help about any commandinit Initialize a Cobra ApplicationFlags:-a, --author string author name for copyright attribution (default "YOUR NAME")--config string config file (default is $HOME/.cobra.yaml)-h, --help help for 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支持兩個(gè)命令,一個(gè)是init, 一個(gè)是add,其中init是初始化一個(gè)cobra工程,add是給工程中添加一個(gè)子命令
初始化該項(xiàng)目:
$ ../../bin/cobra init --pkg-name demo執(zhí)行完上述命令后會(huì)生成如下幾個(gè)文件及文件夾
$ tree . ├── cmd │ └── root.go ├── LICENSE └── main.go1 directory, 3 filesmain.go
package mainimport "imgctl/cmd"func main() {cmd.Execute() }cmd/root.go
package cmdimport ("fmt""os""github.com/spf13/cobra"homedir "github.com/mitchellh/go-homedir""github.com/spf13/viper")var cfgFile string// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{Use: "cobra-demo",Short: "A brief description of your application",Long: `A longer description that spans multiple lines and likely contains examples and usage of using your application. For example:Cobra 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.`,// Uncomment the following line if your bare application// has an action associated with it:// Run: func(cmd *cobra.Command, args []string) { }, }// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() {if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)} }func init() {cobra.OnInitialize(initConfig)// Here you will define your flags and configuration settings.// Cobra supports persistent flags, which, if defined here,// will be global for your application.rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-demo.yaml)")// Cobra also supports local flags, which will only run// when this action is called directly.rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }// initConfig reads in config file and ENV variables if set. func initConfig() {if cfgFile != "" {// Use config file from the flag.viper.SetConfigFile(cfgFile)} else {// Find home directory.home, err := homedir.Dir()if err != nil {fmt.Println(err)os.Exit(1)}// Search config in home directory with name ".cobra-demo" (without extension).viper.AddConfigPath(home)viper.SetConfigName(".cobra-demo")}viper.AutomaticEnv() // read in environment variables that match// If a config file is found, read it in.if err := viper.ReadInConfig(); err == nil {fmt.Println("Using config file:", viper.ConfigFileUsed())} }如果要實(shí)現(xiàn)一個(gè)沒(méi)有子命令的CLI工具,那么由cobra生成程序的操作就結(jié)束了,由于cobra的所有命令都是通過(guò)cobra.Command這個(gè)結(jié)構(gòu)體實(shí)現(xiàn)的,因此這里就需要對(duì)root.go文件中的RootCmd進(jìn)行修改:
cmd/root.go
package cmdimport ("fmt""os""github.com/spf13/cobra"homedir "github.com/mitchellh/go-homedir""github.com/spf13/viper")var cfgFile string var name string var age int// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{Use: "demo",Short: "A test demo",Long: `Demo is a test appcation for print things`,// Uncomment the following line if your bare application// has an action associated with it:Run: func(cmd *cobra.Command, args []string) {if len(name) == 0 {cmd.Help()return}fmt.Println(name, age)}, }// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() {if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)} }func init() {cobra.OnInitialize(initConfig)// Here you will define your flags and configuration settings.// Cobra supports persistent flags, which, if defined here,// will be global for your application.rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-demo.yaml)")rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")rootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")// Cobra also supports local flags, which will only run// when this action is called directly.rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }// initConfig reads in config file and ENV variables if set. func initConfig() {if cfgFile != "" {// Use config file from the flag.viper.SetConfigFile(cfgFile)} else {// Find home directory.home, err := homedir.Dir()if err != nil {fmt.Println(err)os.Exit(1)}// Search config in home directory with name ".cobra-demo" (without extension).viper.AddConfigPath(home)viper.SetConfigName(".cobra-demo")}viper.AutomaticEnv() // read in environment variables that match// If a config file is found, read it in.if err := viper.ReadInConfig(); err == nil {fmt.Println("Using config file:", viper.ConfigFileUsed())} }到此我們的demo功能就編碼完成了,下面編譯運(yùn)行
解決依賴
go mod init go mod vendor運(yùn)行demo
$ go run main.go Demo is a test appcation for print thingsUsage:demo [flags]Flags:-a, --age int person's age-h, --help help for demo-n, --name string person's name添加命令
$ ../../bin/cobra add [cmdname] # 執(zhí)行后會(huì)在cmd目錄下生成一個(gè)cmdname.go的文件,具體處理函數(shù)在該文件中編輯 $ ../../bin/cobra add server $ tree . ├── cmd │ ├── root.go │ └── server.go # rootCmd的子命令 ├── LICENSE └── main.go1 directory, 4 filescmd/server.go
package cmdimport ("fmt""github.com/spf13/cobra" )// serverCmd represents the server command var serverCmd = &cobra.Command{Use: "server",Short: "A brief description of your command",Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example:Cobra 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.`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("server called")}, }func init() {rootCmd.AddCommand(serverCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// serverCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }$ ../../bin/cobra add create -p "serverCmd" #執(zhí)行該命令是為server子命令再創(chuàng)建一級(jí)子命令,-p --parent $ tree . ├── cmd │ ├── create.go # serverCmd的子命令 │ ├── root.go │ └── server.go ├── LICENSE └── main.go1 directory, 5 filescmd/create.go
package cmdimport ("fmt""github.com/spf13/cobra" )// creatCmd represents the creat command var creatCmd = &cobra.Command{Use: "creat",Short: "A brief description of your command",Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example:Cobra 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.`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("creat called")}, }func init() {serverCmd.AddCommand(creatCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// creatCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// creatCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }總結(jié)
以上是生活随笔為你收集整理的命令行工具cobra的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Go语言接口(interface)简单应
- 下一篇: 二分查找的一种实现