From 3ad2533550a72fc1fd9bdc6665c87a8e85944872 Mon Sep 17 00:00:00 2001 From: zeaslity Date: Thu, 27 Feb 2025 14:42:34 +0800 Subject: [PATCH] Enhance Help Command with Recursive Command Listing - Replaced default help function with a custom implementation - Added `printAllCommands` function to recursively list available commands - Improved command help display with indentation and description - Supports nested command hierarchy visualization --- agent-wdd/cmd/root.go | 45 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/agent-wdd/cmd/root.go b/agent-wdd/cmd/root.go index 7343a75..947f316 100644 --- a/agent-wdd/cmd/root.go +++ b/agent-wdd/cmd/root.go @@ -3,6 +3,9 @@ package cmd import ( "agent-wdd/config" "fmt" + "io" + "os" + "strings" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -116,10 +119,12 @@ func Execute() { Short: "帮助信息", Run: func(cmd *cobra.Command, args []string) { // 在你的命令执行函数中 - cmd.Root().SetHelpFunc(func(c *cobra.Command, s []string) { - // 直接使用默认帮助模板 - c.Usage() - }) + // cmd.Root().SetHelpFunc(func(c *cobra.Command, s []string) { + // // 直接使用默认帮助模板 + // c.Usage() + // }) + + printAllCommands(cmd.Root(), os.Stdout) }, } @@ -143,3 +148,35 @@ func Execute() { } } + +func printAllCommands(cmd *cobra.Command, writer io.Writer) { + // 打印命令标题 + fmt.Fprintf(writer, "Available commands:\n") + + // 递归打印命令树 + var traverse func(*cobra.Command, int) + traverse = func(c *cobra.Command, depth int) { + if c.Hidden || c.Deprecated != "" { + return + } + + // 生成命令前缀缩进 + indent := strings.Repeat(" ", depth) + + // 打印当前命令信息 + fmt.Fprintf(writer, "%s%-20s%s\n", + indent, + c.Name(), + strings.TrimSpace(c.Short)) + + // 递归子命令 + for _, subCmd := range c.Commands() { + traverse(subCmd, depth+1) + } + } + + // 从根命令开始遍历 + for _, c := range cmd.Commands() { + traverse(c, 0) + } +}