Help, Usage & Templates
Cobra’s help and usage system turns a Command into human-readable text. It provides default templates, renders them with the command as data, and sends help to standard output or usage to standard error unless the command configures another writer.
The design exists so applications can change presentation without replacing command metadata or execution behavior. You can override a template, replace the whole help or usage function, or add template functions while retaining Cobra’s command-tree data model.
Sources: command.go:484-501, command.go:444-460, command.go:318-324, command.go:358-364, cobra.go:85-87, cobra.go:91-95
Core concepts
Command data
A command’s descriptive fields are the data rendered by templates: Use, Short, Long, Example, aliases, grouping information, and flag state.
The default help template reads Long or Short, then includes usage when the command is runnable or has subcommands. The default usage template reads command methods and fields such as UseLine, CommandPath, Aliases, Example, groups, and flags.
Sources: command.go:54-260, command.go:2042-2044, command.go:1942-1971
Usage template
A usage template formats the command’s invocation syntax, aliases, examples, subcommands, and flags. The built-in value is defaultUsageTemplate, and the built-in renderer is defaultUsageFunc.
Sources: command.go:1942-1971, command.go:1974-2040
Help template
A help template formats descriptive text and delegates the detailed command layout to usage output. The built-in value is defaultHelpTemplate, and the built-in renderer is defaultHelpFunc.
Sources: command.go:2042-2044, command.go:2047-2062
Template function
A template function is a named helper callable from a Go template. Cobra initially registers whitespace, padding, comparison, and string helpers in templateFuncs.
Sources: cobra.go:32-40
Command group
A command group is an ID and Title pair used to place child commands under named headings.
Sources: command.go:45-48
How default help and usage are rendered
The default templates live in command.go as defaultUsageTemplate and defaultHelpTemplate; their renderers receive the input as *Command.
func tmpl(text string) *tmplFunc {
return &tmplFunc{
tmpl: text,
fn: func(w io.Writer, data interface{}) error {
t := template.New("top")
t.Funcs(templateFuncs)
template.Must(t.Parse(text))
return t.Execute(w, data)
},
}
}This is the important boundary: Cobra creates a template, installs templateFuncs, parses the template text, and executes it against the supplied command data.
The normal help path resolves a custom help function first; otherwise it inherits a parent function or creates a default function that merges persistent flags, resolves the help template, and executes it with c as data. Usage follows the same pattern, but writes through OutOrStderr.
Evidence
- command-requestcommand.go:520
- function-selectioncommand.go:484
- template-selectioncommand.go:505
- command-datacommand.go:54
- rendered-outputcobra.go:179
When Help is called, it invokes HelpFunc; when Usage is called, it invokes UsageFunc. A help request during execution is surfaced through HelpFunc, while a usage string is also available through UsageString, which temporarily redirects both output writers into a buffer.
Evidence
- callercommand.go:520
- help-functioncommand.go:484
- flag-mergecommand.go:484
- template-renderercommand.go:484
- template-renderercobra.go:179
- outputcommand.go:484
Sources: command.go:1942-1971, command.go:2042-2044, command.go:1974-2040, command.go:2047-2062, cobra.go:179-189, command.go:484-501, command.go:444-460, command.go:520-523, command.go:478-480, command.go:1084-1170, command.go:526-542
How to customize templates and functions
Call SetUsageTemplate or SetHelpTemplate with non-empty template text to store a parsed tmplFunc; passing an empty string clears the command-local override. The corresponding UsageTemplate and HelpTemplate accessors return the local template, otherwise walk to the parent, and finally return the default template.
A local template therefore affects the command where it is set and can be inherited by descendants through parent lookup. The same parent fallback applies to the resolved renderer functions.
You can replace the whole behavior instead of only the template by calling SetUsageFunc or SetHelpFunc. Those setters store a function directly, and the function lookup methods prefer that stored function before checking the parent.
The built-in template functions are:
| Function | Plain-language purpose |
|---|---|
trim | Removes surrounding whitespace. |
trimRightSpace | Removes whitespace at the right edge. |
trimTrailingWhitespaces | Alias for right-edge whitespace removal. |
appendIfNotPresent | Appends text only when it is absent. |
rpad | Pads text to a requested width. |
gt | Compares supported values using greater-than semantics. |
eq | Compares supported integer or string values for equality. |
These names are registered in templateFuncs, and tmpl installs that map before parsing any template.
Applications can add one function with AddTemplateFunc or merge several functions with AddTemplateFuncs; both update the shared template function map used by later template execution.
Sources: command.go:318-324, command.go:358-364, command.go:592-601, command.go:605-614, command.go:464-473, command.go:505-515, command.go:313-315, command.go:333-335, command.go:444-460, command.go:484-501, cobra.go:32-40, cobra.go:179-189, cobra.go:85-87, cobra.go:91-95
How Cobra groups subcommands in help output
A parent command stores child commands in its command list and stores declared group definitions through AddGroup; Groups exposes the group list. Commands can identify their group with GroupID.
The default usage renderer first checks whether available subcommands exist. With no groups, it prints one Available Commands section. With groups, it prints each group title and includes only children whose GroupID matches that group’s ID.
| Help-output case | Selection rule | Result |
|---|---|---|
| No groups | len(c.Groups()) == 0 | One available-command list. |
| Defined group | subcmd.GroupID == group.ID | Child appears under that group title. |
| Ungrouped child | subcmd.GroupID == "" | Child appears under Additional Commands when needed. |
| Unavailable child | IsAvailableCommand() is false | Child is omitted, except the help command name is allowed. |
The renderer adds Additional Commands when not every child command has a group, while AllChildCommandsHaveGroup treats available commands and the help command as the relevant children for that check.
A command is available when it is not deprecated or hidden and is either runnable or has available subcommands; help-topic commands have a separate IsAdditionalHelpTopicCommand test and appear under Additional help topics.
Before execution, Cobra checks that every non-empty child GroupID exists in the parent’s group list; an undefined group causes a panic naming the group and command path.
Command ordering is also deterministic when EnableCommandSorting is enabled: Commands sorts with commandSorterByName, whose Less method compares command names.
Sources: command.go:1342-1368, command.go:1396-1398, command.go:1371-1373, command.go:54-260, command.go:1974-2040, command.go:1376-1383, command.go:1607-1621, command.go:1628-1643, command.go:1205-1214, command.go:1332-1339, command.go:1329
How it connects
Command construction and parent relationships determine template inheritance, command paths, padding, and which children are visible to help. See Command Tree & Registration.
Execution initializes the default help command, checks command groups, and invokes help or usage when flags request help or execution fails. See Command Execution Flow.
Flags are merged before help and usage render, so local and inherited flag sections reflect the command’s effective flag sets. See Flag Parsing & Persistent Flags.
Generated reference documentation walks the same command tree but is implemented in the doc package rather than these interactive templates. See Man Page & Markdown Doc Generation and REST & YAML Doc Generation.
Sources: command.go:1342-1368, command.go:1465-1470, command.go:1677-1679, command.go:1084-1170, command.go:1263-1314, command.go:444-460, command.go:484-501, command.go:1974-2040
Key takeaways
- Default templates are
defaultUsageTemplateanddefaultHelpTemplate; both render against a*Command. SetHelpTemplateandSetUsageTemplatecustomize text, whileSetHelpFuncandSetUsageFuncreplace rendering behavior.- Available template helpers come from
templateFuncs, and applications can extend it withAddTemplateFuncorAddTemplateFuncs. - Grouped help output uses
GroupID, Group.Title, and Group.ID, with ungrouped commands placed inAdditional Commandswhen applicable. - Help and usage inherit through the command’s parent chain until a local or root default is found.
Sources: command.go:1942-1971, command.go:2042-2044, command.go:318-324, command.go:358-364, command.go:313-315, command.go:333-335, cobra.go:32-40, cobra.go:85-87, cobra.go:91-95, command.go:45-48, command.go:1974-2040, command.go:464-473, command.go:505-515, command.go:592-601, command.go:605-614