Skip to content

Cobra (Go)

cobra_usage converts a Cobra command tree into a usage spec.

Installation

bash
go get github.com/jdx/usage/integrations/cobra

Quick Start

go
import cobra_usage "github.com/jdx/usage/integrations/cobra"

// Print usage spec as KDL
fmt.Print(cobra_usage.Generate(rootCmd))

Integration Pattern

The recommended pattern is to check for a --usage-spec flag before Execute():

go
for _, arg := range os.Args[1:] {
    if arg == "--usage-spec" {
        fmt.Print(cobra_usage.Generate(rootCmd))
        return
    }
}
rootCmd.Execute()

Then pipe the output to usage:

bash
mycli --usage-spec | usage generate completion bash
mycli --usage-spec | usage generate md --out-file docs.md
mycli --usage-spec | usage generate manpage --out-file mycli.1

API

FunctionDescription
Generate(cmd) stringReturns the usage spec as a KDL string
GenerateJSON(cmd) ([]byte, error)Returns the usage spec as JSON
GenerateToFile(cmd, path) errorWrites the KDL spec to a file
GenerateJSONToFile(cmd, path) errorWrites the JSON spec to a file

Feature Mapping

CobraUsage Spec
cmd.Name()name, bin
cmd.Shortabout (root), help (subcommand)
cmd.Longlong_about (root), long_help (subcommand)
cmd.Versionversion
cmd.Aliasesalias
cmd.Hiddenhide=#true
cmd.Deprecateddeprecated="message"
cmd.Use args (<required>, [optional], ...)arg nodes
cmd.ValidArgschoices on first arg
Persistent flagsglobal=#true
flag.Shorthand-s in flag name
flag.Name--long in flag name
flag.Usagehelp="..."
flag.Hiddenhide=#true
flag.Deprecateddeprecated="..."
flag.DefValuedefault="value"
Bool flagsNo arg child
Count flags (CountP)count=#true var=#true
Other flagsarg <UPPER_NAME> child
MarkFlagRequiredrequired=#true

Example

See example/main.go for a complete example CLI.

bash
cd integrations/cobra/example
go run . --usage-spec

Licensed under the MIT License. Maintained by @jdx and friends.