cobra-practice

Golang cobra-cli 生成实践

在 Go 中生成 CLI(命令行接口)命令代码可以使用几个流行的库,例如 cobra、urfave/cli 或 go-flags。其中,cobra 是最受欢迎的一个,广泛用于 Go 项目的 CLI 工具中,例如 kubectl、helm 等。

下面是如何使用 cobra 生成 CLI 命令代码的详细指南。

为了正确安装和使用 cobra,我们需要安装 cobra-cli 工具来初始化和添加命令。

以下是正确的步骤来安装 cobra-cli 和创建一个新的 Cobra 项目:

1. 安装 cobra-cli 工具

从 Go 1.17 版本开始,推荐使用 go install 命令来安装工具,而不是 go get。您可以通过以下命令安装 cobra-cli 工具:

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

2. 初始化一个新的 Cobra 项目

安装完 cobra-cli 工具后,您可以使用 cobra-cli 来初始化一个新的项目:

1
2
3
4
5
6
7
8
9
# 创建一个新的 Go 项目目录
mkdir mycli
cd mycli

# 初始化一个新的 Go 模块
go mod init github.com/yourusername/mycli

# 使用 cobra-cli 初始化新的 CLI 项目
cobra-cli init

此命令会在当前目录下创建一个新的 Cobra 项目,并生成基本的目录结构和文件。

3. 添加新命令

使用 cobra-cli 添加新命令。例如,添加一个 hello 命令:

1
cobra-cli add hello

这将在 cmd 目录下创建一个 hello.go 文件,其中包含 hello 命令的基础代码。

4. 编译和运行 CLI 应用

编译项目:

1
go build -o mycli

运行 CLI 应用:

1
./mycli

运行 hello 命令:

1
./mycli hello

示例代码

cmd/hello.go 文件的代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// cmd/hello.go

package cmd

import (
"fmt"
"github.com/spf13/cobra"
)

// helloCmd represents the hello command
var helloCmd = &cobra.Command{
Use: "hello",
Short: "Prints a hello message",
Long: `Prints a friendly hello message along with the provided name.`,
Run: func(cmd *cobra.Command, args []string) {
name, _ := cmd.Flags().GetString("name")
if name == "" {
name = "World"
}
fmt.Printf("Hello, %s!\n", name)
},
}

func init() {
rootCmd.AddCommand(helloCmd)

// Adding a flag to the hello command
helloCmd.Flags().StringP("name", "n", "", "Name to greet")
}

cmd/root.go 文件的代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// cmd/root.go

package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
Use: "mycli",
Short: "MyCLI is a simple CLI application",
Long: `MyCLI is a simple CLI application for demonstrating
how to build CLI applications using Cobra.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Welcome to MyCLI!")
},
}

// Execute executes the root command.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
// Define global flags for the root command
rootCmd.PersistentFlags().StringP("config", "c", "", "config file (default is $HOME/.mycli.yaml)")
}

总结

  • 安装工具:使用 go install 安装 cobra-cli 工具。
  • 项目初始化:使用 cobra-cli init 初始化项目。
  • 添加命令:使用 cobra-cli add 添加命令。
  • 运行应用:编译并运行 CLI 应用。

通过这些步骤,您可以正确安装并使用 cobra 来创建一个 Go 的 CLI 应用。
github 代码地址:https://github.com/qingwei8/cobra-cli-practice


cobra-practice
https://qingwei8.github.io/2024/07/25/cobra-2024-07-25-cobra-practice/
作者
qingwei
发布于
2024年7月25日
许可协议