转载自: goland带参调试

GitHub.com/spf13/cobra Cli 工具的 path 参数调试文档

【说明】GPT辅助

简介

本文档介绍了如何使用 github.com/spf13/cobra 包开发一个带有 path 参数的 Cli 工具,并且提供了调试方法和示例代码。

前提条件

在开始之前,确保已经安装了 Go 语言开发环境,并且已经设置好了 GOPATH 和 PATH 环境变量。

步骤 1: 创建新的 Go 项目

在命令行中执行以下命令,创建一个新的 Go 项目:

$ mkdir zeroTool
$ cd zeroTool
$ go mod init github.com/codewithyou/zeroTool

步骤 2: 安装 Cobra 包 和cobra-cli

使用以下命令安装 Cobra 包:

$ go get -u github.com/spf13/cobra/cobra
$ go install github.com/spf13/cobra-cli@latest

步骤 3: 创建 Cli 工具

使用以下命令创建一个新的 Cli 工具,并生成基本的目录结构和文件:

$ cobra-cli init zeroTool --author codewithyou -l MIT

【目录结构】

1.1.cmd-tree.png

这将在当前目录下生成一个名为 zeroTool 的文件夹。

步骤 4: 添加 path 参数

进入 zeroTool 文件夹,在 cmd/root.go 文件中,使用以下代码片段在 rootCmd 命令中添加一个名为 path 的路径参数:

var path string

func init() {
    rootCmd.PersistentFlags().StringVarP(&path, "path", "p", "", "File path")
}

func initConfig() {
    if path != "" {
        // 在这里执行与路径参数相关的操作
    }
}

步骤 5: 编译和运行 Cli 工具

执行以下命令编译 Cli 工具:

$ go build -o zeroTool cmd/zeroTool/main.go

然后可以使用以下命令运行 Cli 工具,并传递 path 参数:

$ ./zeroTool --path /path/to/file

调试 Cli 工具

如果需要调试 Cli 工具,可以使用以下方法:

  1. 在代码中添加断点:在代码中添加合适的断点,然后使用调试器(如 Delve)启动 Cli 工具,并附加到正在运行的进程中。
  2. 使用 log 函数输出日志信息:在代码中使用 log 函数输出调试信息,然后通过查看输出信息来进行调试。

示例代码

以下是一个完整的示例代码,演示了如何使用 github.com/spf13/cobra 包开发一个带有 path 参数的 Cli 工具:

//main.go代码
/\*
Copyright © 2023 codewithyou

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*/
package main

import "github.com/codewithyou/zeroTool/cmd"

func main() {
	cmd.Execute()
}

//cmd/root.go代码
/\*
Copyright © 2023 codewithyou

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*/
package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "zeroTool",
	Short: "A brief description of your application",
	Long: `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.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd \*cobra.Command, args []string) {
		pathStr := path
		fmt.Println("pathStr==", pathStr)
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

var path string

func init() {
	rootCmd.PersistentFlags().StringVarP(&path, "path", "p", "", "File path")
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.zeroTool.yaml)")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

使用IDE调试代码

1.点击按钮启动项目,为下一步新增参数做准备

2.1.stat_project.png 【正确效果截图】

2.2.start_success.png

2.填充调试参数

2.3.1.debug_param.png 填充参数--path="demo/aaa"

2.3.2.debug_param.png

3.指定位置打断点并且启动调试

2.4.1.debug_param.png

2.4.2.debug_param.png 【启动结果】

2.4.3.debug_param.png

4.开始调试

【调试结果】

2.4.4.debug_param.png

2.4.5.debug_param.png 【调试截图】

2.4.6.debug_param.png