Cobra既是一個用來建立強大的現代CLI命令行的golang庫,也是一個生成程序應用和命令行文件的程序。下面是Cobra使用的一個演示:
上面全部列出的功能我沒有一一去使用,下面我來簡單介紹一下如何使用Cobra,基本可以知足通常命令行程序的需求,若是須要更多功能,能夠研究一下源碼github。git
Cobra是很是容易使用的,使用go get
來安裝最新版本的庫。固然這個庫仍是相對比較大的,可能須要安裝它可能須要至關長的時間,這取決於你的速網。安裝完成後,打開GOPATH目錄,bin目錄下應該有已經編譯好的cobra.exe程序,固然你也可使用源代碼本身生成一個最新的cobra程序。github
> go get -v github.com/spf13/cobra/cobra
假設如今咱們要開發一個基於CLIs的命令程序,名字爲demo。首先打開CMD,切換到GOPATH的src目錄下[^1],執行以下指令:
[^1]:cobra.exe只能在GOPATH目錄下執行golang
src> ..\bin\cobra.exe init demo Your Cobra application is ready at C:\Users\liubo5\Desktop\transcoding_tool\src\demo Give it a try by going there and running `go run main.go` Add commands to it by running `cobra add [cmdname]`
在src目錄下會生成一個demo的文件夾,以下:express
▾ demo ▾ cmd/ root.go main.go
若是你的demo程序沒有subcommands,那麼cobra生成應用程序的操做就結束了。apache
接下來就是能夠繼續demo的功能設計了。例如我在demo下面新建一個包,名稱爲imp。以下:bash
▾ demo ▾ cmd/ root.go ▾ imp/ imp.go imp_test.go main.go
imp.go文件的代碼以下:app
package imp import( "fmt" ) func Show(name string, age int) { fmt.Printf("My Name is %s, My age is %d\n", name, age) }
demo程序成命令行接收兩個參數name和age,而後打印出來。打開cobra自動生成的main.go文件查看:less
// Copyright © 2016 NAME HERE <EMAIL ADDRESS> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import "demo/cmd" func main() { cmd.Execute() }
能夠看出main函數執行cmd包,因此咱們只須要在cmd包內調用imp包就能實現demo程序的需求。接着打開root.go文件查看:函數
// Copyright © 2016 NAME HERE <EMAIL ADDRESS> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" "os" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "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 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/.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 != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.SetConfigName(".demo") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path 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()) } }
從源代碼來看cmd包進行了一些初始化操做並提供了Execute接口。十分簡單,其中viper是cobra集成的配置文件讀取的庫,這裏不須要使用,咱們能夠註釋掉(不註釋可能生成的應用程序很大約10M,這裏沒喲用到最好是註釋掉)。cobra的全部命令都是經過cobra.Command這個結構體實現的。爲了實現demo功能,顯然咱們須要修改RootCmd。修改後的代碼以下:fetch
// Copyright © 2016 NAME HERE <EMAIL ADDRESS> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" "os" "github.com/spf13/cobra" // "github.com/spf13/viper" "demo/imp" ) //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 } imp.Show(name, age) }, } // Execute adds all child commands to the root command 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/.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") RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name") RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age") } // initConfig reads in config file and ENV variables if set. //func initConfig() { // if cfgFile != "" { // enable ability to specify config file via flag // viper.SetConfigFile(cfgFile) // } // viper.SetConfigName(".demo") // name of config file (without extension) // viper.AddConfigPath("$HOME") // adding home directory as first search path // 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的功能已經實現了,咱們編譯運行一下看看實際效果:
>demo.exe Demo is a test appcation for print things Usage: demo [flags] Flags: -a, --age int person's age -h, --help help for demo -n, --name string person's name
>demo -n borey --age 26 My Name is borey, My age is 26
在執行cobra.exe init demo
以後,繼續使用cobra爲demo添加子命令test:
src\demo>..\..\bin\cobra add test test created at C:\Users\liubo5\Desktop\transcoding_tool\src\demo\cmd\test.go
在src目錄下demo的文件夾下生成了一個cmd\test.go文件,以下:
▾ demo ▾ cmd/ root.go test.go main.go
接下來的操做就和上面修改root.go文件同樣去配置test子命令。效果以下:
src\demo>demo Demo is a test appcation for print things Usage: demo [flags] demo [command] Available Commands: test A brief description of your command Flags: -a, --age int person's age -h, --help help for demo -n, --name string person's name Use "demo [command] --help" for more information about a command.
能夠看出demo既支持直接使用標記flag,又能使用子命令
src\demo>demo test -h 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. Usage: demo test [flags]
調用test命令輸出信息,這裏沒有對默認信息進行修改。
src\demo>demo tst Error: unknown command "tst" for "demo" Did you mean this? test Run 'demo --help' for usage. unknown command "tst" for "demo" Did you mean this? test
這是錯誤命令提示功能
Cobra的使用就介紹到這裏,更新細節可去github詳細研究一下。這裏只是一個簡單的使用入門介紹,若是有錯誤之處,敬請指出,謝謝~