golang的命令行程序开发
今天需要用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执行自已的业务逻辑。