递归生成 golang cobra –help 文本?

huangapple go评论117阅读模式
英文:

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?

https://github.com/spf13/cobra

答案1

得分: 1

我能够编写一些代码。这只是一个简单的递归函数,通过命令名称过滤掉一些噪音(例如,我跳过自动生成的帮助和bash完成命令)。

  1. var dumpAllHelp = "dump-all-help"
  2. var recHelpCmd = &cobra.Command{
  3. Use: dumpAllHelp,
  4. Short: "dump all help texts",
  5. Long: "dump all help texts",
  6. Run: func(_ *cobra.Command, _ []string) {
  7. dumpHelp(rootCmd, true)
  8. },
  9. }
  10. func dumpHelp(c *cobra.Command, root bool) {
  11. if !root {
  12. fmt.Println("")
  13. fmt.Println("========================================================")
  14. fmt.Println("")
  15. }
  16. c.Help()
  17. for _, child := range c.Commands() {
  18. if child.Hidden || child.Name() == "completion" || child.Name() == "help" || child.Name() == dumpAllHelp {
  19. continue
  20. }
  21. dumpHelp(child, false)
  22. }
  23. }
  24. func init() {
  25. rootCmd.AddCommand(recHelpCmd)
  26. }

希望这对你有帮助!

英文:

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)

  1. var dumpAllHelp = "dump-all-help"
  2. var recHelpCmd = &cobra.Command{
  3. Use: dumpAllHelp,
  4. Short: "dump all help texts",
  5. Long: "dump all help texts",
  6. Run: func(_ *cobra.Command, _ []string) {
  7. dumpHelp(rootCmd, true)
  8. },
  9. }
  10. func dumpHelp(c *cobra.Command, root bool) {
  11. if !root {
  12. fmt.Println("")
  13. fmt.Println("========================================================")
  14. fmt.Println("")
  15. }
  16. c.Help()
  17. for _, child := range c.Commands() {
  18. if child.Hidden || child.Name() == "completion" || child.Name() == "help" || child.Name() == dumpAllHelp {
  19. continue
  20. }
  21. dumpHelp(child, false)
  22. }
  23. }
  24. func init() {
  25. rootCmd.AddCommand(recHelpCmd)
  26. }

huangapple
  • 本文由 发表于 2022年6月29日 05:29:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/72793344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定