golang的命令行程序开发
程序员文章站
2022-06-27 20:24:14
今天需要用Golang写一个简单的命令行小工具,虽然标准库的flag包也能实现,但是实现起来有些麻烦,而且对多级子命令更不支持,于是在网上找了这几个spf13、cobra和urfave/cli等,我反正不需要太复杂的,对比了下感觉cli这个库看上去要相对简单一些,于是就用这个库开发了。 git库地址 ......
今天需要用golang写一个简单的命令行小工具,虽然标准库的flag包也能实现,但是实现起来有些麻烦,而且对多级子命令更不支持,于是在网上找了这几个spf13、cobra和urfave/cli等,我反正不需要太复杂的,对比了下感觉cli这个库看上去要相对简单一些,于是就用这个库开发了。
git库地址:
它有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执行自已的业务逻辑。