spf13/cobraApache-2.0adbc881Report / request removal

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.

Help and usage resolution — How does Cobra choose and render help or usage text?

Evidence

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.

Rendering a help request — What call order turns a help request into output?

Evidence

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:

FunctionPlain-language purpose
trimRemoves surrounding whitespace.
trimRightSpaceRemoves whitespace at the right edge.
trimTrailingWhitespacesAlias for right-edge whitespace removal.
appendIfNotPresentAppends text only when it is absent.
rpadPads text to a requested width.
gtCompares supported values using greater-than semantics.
eqCompares 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 caseSelection ruleResult
No groupslen(c.Groups()) == 0One available-command list.
Defined groupsubcmd.GroupID == group.IDChild appears under that group title.
Ungrouped childsubcmd.GroupID == ""Child appears under Additional Commands when needed.
Unavailable childIsAvailableCommand() is falseChild 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 defaultUsageTemplate and defaultHelpTemplate; both render against a *Command.
  • SetHelpTemplate and SetUsageTemplate customize text, while SetHelpFunc and SetUsageFunc replace rendering behavior.
  • Available template helpers come from templateFuncs, and applications can extend it with AddTemplateFunc or AddTemplateFuncs.
  • Grouped help output uses GroupID, Group.Title, and Group.ID, with ungrouped commands placed in Additional Commands when 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

Want this for your repos?

Try Angada AI Wiki