递归生成 golang cobra –help 文本?

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

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完成命令)。

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)
}

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:

确定