Skip to content

qiref/clid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

clid

cobra 简介

cobra是 Go 语言的一个命令行程序库,可以用来编写命令行程序。同时,它也提供了一个脚手架, 用于生成基于 cobra 的应用程序框架。非常多知名的开源项目使用了 cobra 库构建命令行,如Kubernetes、Hugo、etcd等。

安装 cobra

cobra 是由大名鼎鼎的 spf13(golang 开发者) 开发的,GitHub 地址:https://github.com/spf13/cobra

// 安装
go get -u github.com/spf13/cobra
go install github.com/spf13/cobra-cli@latest
# 检查是否安装成功
cobra -h
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 [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
  -l, --license string   name of license for the project
      --viper            use Viper for configuration

Use "cobra [command] --help" for more information about a command.

创建 cobra 工程

# 创建 Go 工程
mkdir clid
cd clid
go mod init clid

# 创建 cobra 工程
cobra init
# 可以得到如下工程目录
D:\WORKSPACE\GOLANG\TRAINNING\CLID
│   go.mod
│   go.sum
│   LICENSE
│   main.go
│
└───cmd
        root.go

# 正常情况下,这个工程可以正常编译并且运行
go build -o ./bin/clid

增加自定义命令

cobra add version

tree /f
D:.
│   go.mod
│   go.sum
│   LICENSE
│   main.go
│
└───cmd
        root.go
        version.go

# 在 `cmd` 目录下新生成一个 `version.go` 的文件

从新生成的文件可以看出,核心方法就2个:

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "版本信息", // 命令提示
	Long: `版本信息描述`, // 命令说明
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("0.0.1-Alpha")
	},
}

func init() {
	rootCmd.AddCommand(versionCmd) // version 命令是 rootCmd 的一个子命令
}
#./clid
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:
  1 [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  version     版本信息
# ./clid version
0.0.1-Alpha
# ./clid version -h
版本信息描述

Usage:
  clid version [flags]

Flags:
  -h, --help   help for version

给子命令增加参数

重新增加命令测试

cobra add foo
var fooCmd = &cobra.Command{
	Use:   "foo",
	Short: "A brief description of your command",
	Long: `A longer description `,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("foo called")
		bar, err := cmd.Flags().GetString("bar")
		if err != nil {
			fmt.Println("请输入正确的bar")
		}
		fmt.Printf("输入值bar[%s]", bar)
	},
}

func init() {
	rootCmd.AddCommand(fooCmd)
	fooCmd.Flags().StringP("bar", "a", "默认值", "命令说明")
}

执行结果:

#./clid foo -h
A longer description 

Usage:
  clid foo [flags]

Flags:
  -a, --bar string   命令说明 (default "默认值")
  -h, --help         help for foo
# ./clid foo -a test
# ./clid foo --bar test 

foo called
输入值bar[test]

命令其他参数

以上是指定了 foo 命令的参数,cobra 还可以识别命令后的附加参数。

以下代码定义了一个多数求和的命令,执行命令后,在命令后带上需要求和的参数,即可完成求和。

var sumCmd = &cobra.Command{
	Use:   "sum",
	Short: "A brief description of your command",
	Long: `A longer description .`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("sum called")
		result := 0
		for _, v := range args {
			arg, err := strconv.Atoi(v)
			if err != nil {
				fmt.Printf("args: %s , %s cannot convert to int ", args, v)
				return
			}
			result += arg
		}
		fmt.Printf("result [%d]", result)
	},
}

测试结果:

# ./clid sum 1 2 3 4 5
sum called
result [15]

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages