Cobra Overview
Cobra is a Go library for creating modern command-line applications with subcommands, flags, help, suggestions, shell completion, and generated documentation. It is used by projects including Kubernetes, Hugo, and GitHub CLI.
It exists to give CLI authors a consistent structure: applications read like commands, while Cobra provides surrounding interface behavior. A typical application keeps a small main.go that calls cmd.Execute(), with commands organized under a root command.
Sources: README.md:7-14, site/content/user_guide.md:16-25
Core concepts
Commands
A command represents an action in the application and is the central unit of interaction; commands can contain child commands and may run an action. In code, this unit is Command, whose definition requires usage and description as part of the command definition.
Sources: README.md:79-87, command.go:51-54
Args
Arguments are things in Cobra’s sentence-like command model. Cobra models positional-argument validation with PositionalArgs, a function receiving a *Command and an argument slice.
Sources: README.md:55-67, args.go:22-24
Flags
Flags modify command behavior. Cobra supports POSIX-style flags and flags that are local to one command or persist through child commands; flag functionality is provided by the pflag library.
The three concepts form a sentence-like command shape: APPNAME VERB NOUN --ADJECTIVE, also expressed as APPNAME COMMAND ARG --FLAG. Commands represent actions, Args are things, and Flags are modifiers for those actions.
For example, hugo server --port=1313 uses server as the command and port as the flag. The README also shows git clone URL --bare as an example of telling Git to clone a URL bare.
Sources: README.md:89-100, README.md:55-67, README.md:69-73, README.md:75-77
How the package is organized
The library centers on a command tree: applications define a root command, add child commands, and execute the root. The user guide shows rootCmd as a *cobra.Command, registers child commands with rootCmd.AddCommand, and exposes an Execute function that calls rootCmd.Execute().
The package also provides supporting behavior around that tree, including automatic help, nested commands, persistent and local flags, suggestions, shell completion, man pages, aliases, and customizable help and usage output.
The following architecture view focuses on the package-level extension points in cobra.go: template registration, template execution, and initialization or finalization hooks.
Evidence
- template-registrycobra.go:32
- single-func-registrationcobra.go:85
- batch-func-registrationcobra.go:91
- template-renderercobra.go:179
- initializer-registrycobra.go:42
- initializer-registrycobra.go:99
- finalizer-registrycobra.go:43
- finalizer-registrycobra.go:105
Sources: site/content/user_guide.md:40-63, site/content/user_guide.md:100-114, cobra.go:32-40, cobra.go:42, cobra.go:43, cobra.go:85-87, cobra.go:91-95, cobra.go:99-101, cobra.go:105-107, cobra.go:179-189
Package-level globals and template functions
cobra.go defines defaults for prefix matching, command sorting, case sensitivity, and traversal of run hooks. The corresponding exported variables are EnablePrefixMatching, EnableCommandSorting, EnableCaseInsensitive, and EnableTraverseRunHooks.
| Setting | Default | When to touch it |
|---|---|---|
EnablePrefixMatching | false | When command-name prefix matching should be changed. |
EnableCommandSorting | true | When command ordering should be changed. |
EnableCaseInsensitive | false | When command matching should ignore case. |
EnableTraverseRunHooks | false | When run hooks should traverse the command hierarchy. |
These package-level variables expose the four corresponding behavior switches and initialize from their declared defaults.
The package also exposes callback registries and template customization functions. initializers and finalizers are slices of callback functions. OnInitialize and OnFinalize append callbacks to those slices.
| Extension point | What it contains | Public entry point |
|---|---|---|
templateFuncs | Built-in template names such as trim, rpad, gt, and eq. | AddTemplateFunc, AddTemplateFuncs |
initializers | Functions registered for initialization. | OnInitialize |
finalizers | Functions registered for finalization. | OnFinalize |
| Mousetrap settings | Windows guidance text and display duration. | MousetrapHelpText, MousetrapDisplayDuration |
The built-in templateFuncs map binds template names to trimming, padding, comparison, and append helpers. Applications can add one template function with AddTemplateFunc, which assigns into templateFuncs. They can merge several functions with AddTemplateFuncs, which assigns each supplied entry into the same map.
When a template is rendered, tmpl creates a template, installs templateFuncs, parses the supplied text, and executes it against the provided data. Touch these APIs when customizing template vocabulary or registering application-specific initialization and finalization callbacks.
MousetrapHelpText contains Windows command-line guidance, and MousetrapDisplayDuration defines a five-second display duration.
Sources: cobra.go:46, cobra.go:47, cobra.go:48, cobra.go:49, cobra.go:55, cobra.go:59, cobra.go:62, cobra.go:66, cobra.go:42, cobra.go:43, cobra.go:99-101, cobra.go:105-107, cobra.go:32-40, cobra.go:85-87, cobra.go:91-95, cobra.go:179-189, cobra.go:72-75, cobra.go:81
Small package utilities
The package includes comparison helpers used by templates. Gt compares supported arrays, channels, maps, slices, integer values, or numeric strings by converting them to comparable int64 values. Eq compares supported integer or string values and rejects arrays, channels, maps, and slices with a panic.
Formatting helpers include trimRightSpace, appendIfNotPresent, and rpad; they trim trailing whitespace, avoid appending a string already present, and right-pad a string to a requested width.
For command-line error handling, CheckErr prints a non-nil error to standard error and exits with status 1. WriteStringAndCheck writes to an io.StringWriter and passes any write error to CheckErr.
Sources: cobra.go:114-139, cobra.go:144-157, cobra.go:159-161, cobra.go:166-171, cobra.go:174-177, cobra.go:235-240, cobra.go:243-246
How it connects
Application code normally defines the root and child commands in a cmd package, registers children with AddCommand, and calls Execute from main.go. Continue with Command Tree & Registration for the command hierarchy and registration rules.
Flags, positional arguments, execution hooks, completion, generated documentation, and platform behavior are separate concerns built around the command model. Use Command Execution Flow, Positional Argument Validators, Flag Parsing & Persistent Flags, and Help, Usage & Templates for those mechanisms.
The broader repository organization and contribution workflow are covered in Repository Layout & Development Setup, while generated reference formats connect to Man Page & Markdown Doc Generation and REST & YAML Doc Generation.
Sources: site/content/user_guide.md:16-25, site/content/user_guide.md:187-216
Key takeaways
- Cobra gives Go applications a command-tree model for building modern CLIs.
- Commands are actions, Args are things, and Flags are modifiers for those actions.
- The sentence-shaped interface is
APPNAME VERB NOUN --ADJECTIVEorAPPNAME COMMAND ARG --FLAG. - Package-level variables expose defaults for prefix matching, sorting, case sensitivity, and run-hook traversal.
- Template registration and initialization/finalization callbacks are exposed through separate cobra.go APIs.
Sources: README.md:7-14, README.md:55-67, README.md:64-67, cobra.go:46, cobra.go:47, cobra.go:48, cobra.go:49, cobra.go:55, cobra.go:59, cobra.go:62, cobra.go:66, cobra.go:85-87, cobra.go:91-95, cobra.go:99-101, cobra.go:105-107