今天需要用Golang寫一個簡單的命令行小工具,雖然標準庫的flag包也能實現,但是實現起來有些麻煩,而且對多級子命令更不支持,於是在網上找了這幾個spf13、cobra和urfave/cli等,我反正不需要太複雜的,對比了下感覺cli這個庫看上去要相對簡單一些,於是就用這個庫開發了。 git庫地址 ...
今天需要用Golang寫一個簡單的命令行小工具,雖然標準庫的flag包也能實現,但是實現起來有些麻煩,而且對多級子命令更不支持,於是在網上找了這幾個spf13、cobra和urfave/cli等,我反正不需要太複雜的,對比了下感覺cli這個庫看上去要相對簡單一些,於是就用這個庫開發了。
git庫地址:urfave/cli
它有v1和v2版本,我用的是v2,文檔地址是
直接安裝
go get github.com/urfave/cli/v2
代碼實例
package main
import (
"fmt"
"log"
"os"
"sort"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Name:"ZC-Web-Deploy",
Usage:"項目打包平臺",
Description:"項目打包平臺,將打好的包上傳至存儲中心上面,運維人員作發佈",
Commands: []*cli.Command{
{
Name: "project",
Aliases: []string{"p"},
Usage: "deploy project",
Subcommands:[]*cli.Command{
{
Name: "init",
Aliases: []string{"i"},
Usage: "init the project",
Action: func(c *cli.Context) error {
project.InitProject()
return nil
},
},
{
Name: "build",
Aliases: []string{"b"},
Usage: "build the project as tar to ftp",
Action: func(c *cli.Context) error {
var (
deployProject *common.DeployProject
)
deployProject = &common.DeployProject{
Domain:c.String("domain"),
Tag:c.String("tag"),
}
if deployProject.Domain == "" || deployProject.Tag == "" {
fmt.Println("構建的項目功能變數名稱或Tag不能為空")
return nil
}
project.Deploy(deployProject)
return nil
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "domain, d",
Value: "xxxx",
Usage: "指定工程的功能變數名稱",
Required:true,
},
&cli.StringFlag{
Name: "tag, t",
Value: "release-tag",
Usage: "打包項目的git的tag發佈版本號",
Required:true,
},
},
},
{
Name: "list",
Aliases: []string{"ls"},
Usage: "list the project",
Action: func(c *cli.Context) error {
var (
projectList []string
p string
)
projectList = project.ListProject()
if len(projectList) > 0 {
for _, p = range projectList {
fmt.Println(p)
}
} else {
fmt.Println("暫無項目,可以初始化建立project init")
}
return nil
},
},
},
Action: func(c *cli.Context) error {
fmt.Println("請指定具體操作: init、ls、build或用 -h 查看命令")
return nil
},
},
},
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
輸入下麵的命令,看到project支持的子命令都看到了
$ go run main.go project -h
NAME:
ZC-Web-Deploy project - deploy project
USAGE:
ZC-Web-Deploy project command [command options] [arguments...]
COMMANDS:
init, i init the project
build, b build the project as tar to ftp
list, ls list the project
help, h Shows a list of commands or help for one command
OPTIONS:
--help, -h show help (default: false)
子命令輸出
$ go run main.go project ls
xxx.com
總體來說,cli的使用還是不難的,填充 cli.App
結構體自已需要的欄位就行了,然後在Action執行自已的業務邏輯。