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

Quickstart

go
package main

import (
    "fmt"

    "github.com/spf13/cobra"
    cobra_usage "github.com/jdx/usage/integrations/cobra"
)

func main() {
    root := &cobra.Command{
        Use:     "mycli",
        Short:   "My CLI tool",
        Version: "1.0.0",
    }
    // ... add subcommands, flags, args ...

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

Expose the spec

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
    }
}
if err := rootCmd.Execute(); err != nil {
    os.Exit(1)
}

Then pipe the output to usage, passing -f - to read the spec from stdin:

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

For completions, --usage-cmd 'mycli --usage-spec' can replace the pipe and -f -, letting the completion script fetch a fresh spec itself at runtime.

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.Exampleexample node (top-level for root)
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

Cobra's Example is a single free-form block rather than a list of structured examples, so it maps to one example node holding the whole text, dedented. Comment lines the author wrote stay inside the example code.

Example

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

bash
cd integrations/cobra/example
go run . --usage-spec
MIT LicenseCopyright © 2026jdx.dev