cobra简介
cobra是一个命令行程序库,可以用来编写命令行程序,非常简单易用,类似于Go标准库中的Flag包,不过它比Flag包强大很多。它提供了一个脚手架,可以生成基于cobra的应用程序框架。
cobra的github地址是https://github.com/spf13/cobra,可以看到很多知名的项目Kubernetes/Docker/Hugo/Etcd都在使用。
cobra的作者是spf13,它是Google工程师,也是Go项目团队成员。
使用cobra写的很多项目在github上都有过万⭐️,非常受欢迎,例如hugo静态博客生成器。
cobra包功能
- 轻松创建基于子命令的 CLI:如
app server
、app fetch
等。 - 自动添加
-h
,--help
等帮助性Flag - 自动生成命令和Flag的帮助信息
- 创建完全符合 POSIX 的Flag(标志)(包括长、短版本)
- 支持嵌套子命令
- 支持全局、本地和级联Flag
- 智能建议(
app srver
... did you meanapp server
?) - 为应用程序自动生成 shell 自动完成功能(bash、zsh、fish、powershell)
- 为应用程序自动生成man page
- 命令别名,可以在不破坏原有名称的情况下进行更改
- 支持灵活自定义help、usege等。
- 无缝集成viper构建12-factor应用
规则
cobra遵循commands
, arguments
& flags
结构。
Cobra 结构由三部分组成:命令 (commands)、参数 (arguments)、标志 (flags),遵循commands
, arguments
& flags
结构。基本模型如下:
APPNAME VERB NOUN --ADJECTIVE 或者 APPNAME COMMAND ARG --FLAG
案例一:不带参数
hugo server --port=1313
- hugo:根命令
- server:子命令
- --port:标志
案例二:带参数
git clone URL --bare
- git:根命令
- clone:子命令
- URL:参数,即 clone 作用的对象
- --bare:标志
总结下:
- commands 代表行为,是应用的中心点
- arguments 代表行为作用的对象
- flags 是行为的修饰符
cobra安装
前提条件:go环境已经安装。
安装cobra包和二进制工具cobra-cli,cobra-cli可以帮助我们快速创建出一个cobra基础代码结构。
go get -u github.com/spf13/cobra@latest
go install github.com/spf13/cobra-cli@latest
启用GO111MODULE=on
,我们初始化一个xpower
# mkdir sretools
# go mod init sretools
go: creating new go.mod: module sretools
使用cobra-cli初始化基础代码结构
# ~/go/bin/cobra-cli init
# ls
LICENSE cmd go.mod go.sum main.go
# tree sretools
sretools
├── cmd
│ └── root.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go
添加子命令
# ~/go/bin/cobra-cli add kubeconfcheck
kubeconfcheck created at /Users/mingyu/code/src/sretools
# tree sretools
sretools
├── cmd
│ ├── root.go
│ └── kubeconfcheck.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go
# ./sretools -h
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.
Usage:
sretools [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command
kubeconfcheck A brief description of your command
Flags:
-h, --help help for sretools
-t, --toggle Help message for toggle
Use "sretools [command] --help" for more information about a command.
参数管理
args
cobra内置的参数验证,可用来校验内置参数,具体可查看源码args.go。
flags
flag包含局部和全局两种,全局flag在父命令定义后子命令也会生效,而局部flag则在哪定义就在哪生效。