简介
Cobra是一个用于创建强大的现代CLI应用程序的库。Cobra被用在很多Go项目中,比如Kubernetes、Hugo和GitHub CLI等等。
使用
创建新项目
mkdir cobra_learn
cd cobra_learn
go mod init cobra_learn
安装Cobra
go install github.com/spf13/cobra-cli@latest
查看安装的cobra-cli
执行上述命令安装后,会在GOPATH的bin目录下生成一个二进制文件
➜ bin ls
cobra-cli
➜ bin ./cobra-cli
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:
cobra-cli [command]
Available Commands:
add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell
help Help about any command
init Initialize a Cobra Application
Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra-cli
-l, --license string name of license for the project
--viper use Viper for configuration
Use "cobra-cli [command] --help" for more information about a command.
使用Cobra-cli初始化项目
在项目目录下执行cobra-cli init
➜ cobra_learn cobra-cli init
Your Cobra application is ready at
/home/tang/code/cobra_learn
当前项目目录结构如下
➜ cobra_learn ls
cmd go.mod go.sum LICENSE main.go
➜ cobra_learn tree
.
├── cmd
│ └── root.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go
1 directory, 5 files