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
This commit is contained in:
@@ -3,6 +3,9 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
"agent-wdd/config"
|
"agent-wdd/config"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
@@ -116,10 +119,12 @@ func Execute() {
|
|||||||
Short: "帮助信息",
|
Short: "帮助信息",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
// 在你的命令执行函数中
|
// 在你的命令执行函数中
|
||||||
cmd.Root().SetHelpFunc(func(c *cobra.Command, s []string) {
|
// cmd.Root().SetHelpFunc(func(c *cobra.Command, s []string) {
|
||||||
// 直接使用默认帮助模板
|
// // 直接使用默认帮助模板
|
||||||
c.Usage()
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user