Cobra是一个库,其提供简单的接口来创建强大现代的CLI接口,类似于git或者go工具。同时,它也是一个应用,用来生成个人应用框架,从而开发以Cobra为基础的应用。
Cobra基于三个基本概念commands,arguments和flags。
基本模型如下:
appName command argument --flag
# clone是commands,URL是arguments,brae是flags
git clone URL --bare
go get -u github.com/spf13/cobra/cobra
mport "github.com/spf13/cobra"
func createConfigSetCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "configset",
Aliases: []string{"cfgset"}, # 别名
Short: "create configset",
Long: "create ConfigSet for application",
Example: `
.......
`,
RunE: handleCreateConfigSet,
}
// command line flags.
cmd.Flags().StringP("name", "n", "", "settings new ConfigSet name")
cmd.Flags().StringP("app", "a", "", "settings app that ConfigSet belongs to.")
cmd.Flags().StringP("path", "p", "", "settings sub file path of ConfigSet.")
cmd.MarkFlagRequired("name") # 标准对应 flag 必填
cmd.MarkFlagRequired("app") # 标准对应 flag 必填
# 可变参数
cmd.Flags().StringArrayP("app", "a", make([]string,0), "application name that ConfigSet belongs to")
cmd.MarkFlagRequired("app")
return cmd
}
▾ appName/
▾ cmd/
root.go
version.go
commands.go
main.go
package main
import (
"cobraLearn/cmd"
)
func main() {
cmd.Execute()
}
package cmd
import (
"fmt"
"os"
"cobraLearn/imp"
"github.com/spf13/cobra"
)
var name string
var age int
var varGlobal string
var RootCmd = &cobra.Command{
Use: "cobraLearn",
Short: "A command for user",
Long: `CobraLearn is a command for get user's info`,
Run: func(cmd *cobra.Command, args []string) {
if len(name) == 0 {
cmd.Help()
return
}
imp.Show(name, age)
},
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
// Local Flags 只作用与当前命令 version命令不可以使用
RootCmd.Flags().StringVarP(&name, "name", "n", "", "user's name")
RootCmd.Flags().IntVarP(&age, "age", "a", 0, "user's age")
// Persistent Flags 作用于全局命令 version 命令页可以使用
RootCmd.PersistentFlags().StringVarP(&varGlobal, "global", "g", "", "global var")
}
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
func init() {
RootCmd.AddCommand(versionCmd)
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of cobraLearn",
Long: `All software has versions. This is User's`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Cobra User Version: v1.0 -- HEAD")
},
}
编码完成后,go install 生成可执行文件,去 $GOPATH/bin 目录下寻找:
(因为我的项目名称为 cobraLearn 所以生成执行文件名称也为此)