英文:
Recursively generate golang cobra --help text?
问题
如果我有一个由Cobra管理的Golang应用程序,我可以调用mycommand --help
来查看顶级帮助和命令列表,mycommand cmd1 --help
来查看第一个命令的帮助信息,等等。
在使用Cobra库的情况下,有没有一种方法可以递归地一次性打印出所有的命令、标志和帮助文本?
https://github.com/spf13/cobra
英文:
If I have a cobra-managed golang application, I can invoke mycommand --help
to see the top level help and list of commands, mycommand cmd1 --help
to see the same for the first command, etc.
Is there a way using the cobra library to recursively print all the commands, flags, and help text in one pass?
答案1
得分: 1
我能够编写一些代码。这只是一个简单的递归函数,通过命令名称过滤掉一些噪音(例如,我跳过自动生成的帮助和bash完成命令)。
var dumpAllHelp = "dump-all-help"
var recHelpCmd = &cobra.Command{
Use: dumpAllHelp,
Short: "dump all help texts",
Long: "dump all help texts",
Run: func(_ *cobra.Command, _ []string) {
dumpHelp(rootCmd, true)
},
}
func dumpHelp(c *cobra.Command, root bool) {
if !root {
fmt.Println("")
fmt.Println("========================================================")
fmt.Println("")
}
c.Help()
for _, child := range c.Commands() {
if child.Hidden || child.Name() == "completion" || child.Name() == "help" || child.Name() == dumpAllHelp {
continue
}
dumpHelp(child, false)
}
}
func init() {
rootCmd.AddCommand(recHelpCmd)
}
希望这对你有帮助!
英文:
I was able to hack something up. This is just a simple recursive function that filters out some noise by command name (e.g I skip over autogenerated help and bash completion commands)
var dumpAllHelp = "dump-all-help"
var recHelpCmd = &cobra.Command{
Use: dumpAllHelp,
Short: "dump all help texts",
Long: "dump all help texts",
Run: func(_ *cobra.Command, _ []string) {
dumpHelp(rootCmd, true)
},
}
func dumpHelp(c *cobra.Command, root bool) {
if !root {
fmt.Println("")
fmt.Println("========================================================")
fmt.Println("")
}
c.Help()
for _, child := range c.Commands() {
if child.Hidden || child.Name() == "completion" || child.Name() == "help" || child.Name() == dumpAllHelp {
continue
}
dumpHelp(child, false)
}
}
func init() {
rootCmd.AddCommand(recHelpCmd)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论