Mark Harrison
Mark Harrison

Reputation: 304654

Recursively generate golang cobra --help text?

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

Upvotes: 2

Views: 377

Answers (1)

Havin Leung
Havin Leung

Reputation: 303

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

Upvotes: 3

Related Questions