本站总访问量 cobra-一个强大的cli构建工具 - Jerry的小站

Jerry Gao

上帝就是真理,真理就是上帝

概述

Cobra用于构建一个强大的现代cli应用程序的工具,它被Kubernetes、github cli、Hugo等著名的项目所使用。

作为一个使用广泛的工具,Cobra支持智能建议(app srver… did you mean app server?),自动生成shell/bash/sh等,自动生成帮助信息…可以说是一个非常强大的工具。

该项目的项目地址如下:

https://github.com/spf13/cobra

如何使用

安装

1
go get -u github.com/spf13/cobra@latest

导入

1
import "github.com/spf13/cobra"

使用

生成模版文件

先安装cobra-cli:

1
go install github.com/spf13/cobra-cli@latest

在根目录下,执行

1
cobra-cli init

添加标记

首先将程序名称设置为artifact,然后修改命令介绍。

1
2
3
4
5
6
7
8
9
10
11
rootCmd = &cobra.Command{
Use: "artifact",
Short: "artifact是制品包下载器工具",
Long: `artifact是制品包的下载工具,可用于从文件服务器拉取制品包,然后从文件服务器下载连接器。
输入制品包版本号或者时间戳,arfact将自动检测包是否存在,并按照指定的连接器列表下载连接器,最后将他们打包成最终的制品包文件。`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
fmt.Println()
},
}

在init函数增加记录:

1
2
3
4
5
6
7
8

var version string

func init() {
rootCmd.PersistentFlags().StringVarP(&version, "version", "v", "", "版本号") // 1
rootCmd.MarkPersistentFlagRequired("version") // 2
viper.BindPFlag("version", rootCmd.PersistentFlags().Lookup("version")) // 3
}
  1. 定义version标记,可以使用快捷命令”-v”,或者长命令”–version”,定义默认值为空,而且帮助信息为“版本号”。
  2. 设置version为必填,这里表示必须在命令行指定,在配置文件中指定是不行的
  3. 将version与配置文件中的version关联起来,这里命令行优先级大于配置文件

在根目录下运行go run main.go -h,即可输出帮助信息。

添加子命令

运行cobra-cli add list,表示列出制品包列表,这样会在cmd目录下生成一个list目录,配置方法与上文类似,这里不再多说。

具体配置方法可以参照官方说明文档。

For complete details on using the Cobra-CLI generator, please read The Cobra Generator README
For complete details on using the Cobra library, please read the The Cobra User Guide.

评论