Cobra — API Surface#
API types#
Library (primary) — Cobra is consumed purely as a Go library. There is no HTTP server, no gRPC service, and no standalone binary. The doc/ subpackage adds a secondary, optional library API for documentation generation.
REST/HTTP API#
Not applicable. Cobra does not expose any HTTP endpoints.
gRPC API#
Not applicable. No .proto files exist in the repository.
CLI (if applicable)#
Cobra does not itself produce a CLI binary. Rather, it is the framework that other CLIs are built with. However, Cobra injects several built-in subcommands into every application that uses it:
help [command]— auto-generated; shows usage for the root or any subcommand.completion [bash|zsh|fish|powershell]— auto-generated; prints the shell completion script for the chosen shell. Can be suppressed viaCompletionOptions.DisableDefaultCmd.__complete/__completeNoDesc— hidden; called by shell completion scripts to obtain dynamic completion candidates at runtime.
Flag patterns injected by cobra#
--help/-h— added lazily to every command viaInitDefaultHelpFlag()--version/-v— added lazily to any command that setsCommand.Version--no-descriptions— added tocompletionsubcommands for shells that support descriptions
Plugin / Extension system#
Cobra does not have a plugin system in the hashicorp/go-plugin or RPC sense. Its extensibility is purely interface/function-field–based:
Extension points#
| Extension point | Type | How to use |
|---|---|---|
Command.Run / RunE | func(*Command, []string) [error] | Primary user logic hook |
Command.PreRun / PreRunE | func(*Command, []string) [error] | Setup before Run |
Command.PostRun / PostRunE | func(*Command, []string) [error] | Teardown after Run |
Command.PersistentPreRun / PersistentPreRunE | func(*Command, []string) [error] | Inherited by children |
Command.PersistentPostRun / PersistentPostRunE | func(*Command, []string) [error] | Inherited by children |
Command.Args (PositionalArgs) | func(*Command, []string) error | Positional argument validation |
Command.ValidArgsFunction (CompletionFunc) | func(*Command, []string, string) ([]Completion, ShellCompDirective) | Dynamic shell completions for positional args |
OnInitialize(func()) | Package-level callback | Runs before each command execution (e.g., config loading) |
OnFinalize(func()) | Package-level callback | Runs after each command execution |
Command.SetUsageFunc(func(*Command) error) | Method | Replace usage output entirely |
Command.SetHelpFunc(func(*Command, []string)) | Method | Replace help output entirely |
Command.SetUsageTemplate(string) | Method | Replace usage text/template |
Command.SetHelpTemplate(string) | Method | Replace help text/template |
AddTemplateFunc(name, func) | Package-level | Inject custom functions into all templates |
Command.SetFlagErrorFunc(func(*Command, error) error) | Method | Override flag parse error handling |
Command.RegisterFlagCompletionFunc(flagName, CompletionFunc) | Method | Dynamic completions for a specific flag |
Command.SetGlobalNormalizationFunc(func) | Method | Normalize flag names globally |
Library API (primary usage mode)#
Core package (github.com/spf13/cobra)#
Exported types#
| Type | Kind | Purpose |
|---|---|---|
Command | struct (~260 fields/methods) | The single central abstraction; represents one node in the command tree |
Group | struct | Groups subcommands together in help output ({ID, Title string}) |
FParseErrWhitelist | type alias for pflag.ParseErrorsAllowlist | Selectively ignore flag parse errors |
PositionalArgs | func(*Command, []string) error | Type alias for positional argument validators |
ShellCompDirective | int bitmask | Hints to the shell about how to handle completions |
CompletionOptions | struct | Fine-grained control over the completion subcommand behavior |
Completion | type alias for string | A completion candidate (optionally TAB-separated with description) |
CompletionFunc | func(*Command, []string, string) ([]Completion, ShellCompDirective) | Signature for dynamic completion providers |
SliceValue | interface | Implemented by pflag slice types; enables multi-value completion |
Package-level variables (behavioral configuration)#
| Variable | Default | Purpose |
|---|---|---|
EnablePrefixMatching | false | Accept unambiguous prefix as command name |
EnableCommandSorting | true | Sort subcommands alphabetically in help |
EnableCaseInsensitive | false | Case-insensitive command name matching |
EnableTraverseRunHooks | false | Run ALL ancestor PersistentPreRun hooks vs. only closest |
MousetrapHelpText | (Windows guard text) | Text shown when CLI is launched from Windows Explorer |
MousetrapDisplayDuration | 5s | How long the Windows mousetrap text is shown |
Positional argument validators (package-level functions)#
| Function | Signature | Behavior |
|---|---|---|
NoArgs | PositionalArgs | Rejects any positional args |
ArbitraryArgs | PositionalArgs | Accepts any positional args without restriction |
OnlyValidArgs | PositionalArgs | Restricts to Command.ValidArgs list |
MinimumNArgs(n) | func(int) PositionalArgs | At least n args required |
MaximumNArgs(n) | func(int) PositionalArgs | At most n args allowed |
ExactArgs(n) | func(int) PositionalArgs | Exactly n args required |
RangeArgs(min, max) | func(int, int) PositionalArgs | Between min and max args |
MatchAll(pargs...) | func(...PositionalArgs) PositionalArgs | Compose multiple validators (all must pass) |
ExactValidArgs(n) | func(int) PositionalArgs | Exactly n args, each must be in ValidArgs |
Completion helpers (package-level functions)#
| Function | Purpose |
|---|---|
CompletionWithDesc(choice, desc) | Construct a Completion string with TAB-separated description |
NoFileCompletions(...) | Pre-built CompletionFunc — disables file completion |
FixedCompletions(choices, directive) | Returns a CompletionFunc always returning the given static choices |
AppendActiveHelp(compArray, msg) | Inject active-help text into a completion result |
GetActiveHelpConfig(cmd) | Read the ACTIVEHELP env var for a command |
CompDebug, CompDebugln, CompError, CompErrorln | Debug/error logging helpers for completion functions |
Flag annotation helpers (package-level functions on pflag.FlagSet)#
| Function | Purpose |
|---|---|
MarkFlagRequired(flags, name) | Mark a flag as required |
MarkFlagFilename(flags, name, exts...) | Mark flag for file-completion with extension filter |
MarkFlagDirname(flags, name) | Mark flag for directory-only completion |
MarkFlagCustom(flags, name, f) | Legacy: attach arbitrary bash completion function to a flag |
Key *Command methods — grouped by concern#
Execution:
Execute() error— entry point; parsesos.Args[1:]and dispatchesExecuteContext(ctx) error— Execute with a contextExecuteC() (*Command, error)— Execute returning the matched commandExecuteContextC(ctx) (*Command, error)— combination of above two
Tree management:
AddCommand(cmds ...*Command)— attach subcommandsRemoveCommand(cmds ...*Command)— detach subcommandsCommands() []*Command— list direct childrenResetCommands()— remove all childrenAddGroup(groups ...*Group)— register display groupsGroups() []*Group— list groupsParent() *Command/Root() *Command— navigationFind(args) (*Command, []string, error)— tree search by argsTraverse(args) (*Command, []string, error)— tree search with flag parsing
Flag management:
Flags() *pflag.FlagSet— local + inherited flagsPersistentFlags() *pflag.FlagSet— flags inherited by childrenLocalFlags() *pflag.FlagSet— flags local to this commandInheritedFlags() *pflag.FlagSet— flags from ancestorsParseFlags(args) error— invoke pflag parsingFlag(name) *pflag.Flag— lookup by nameMarkFlagRequired(name) error— require a flagMarkPersistentFlagRequired(name) errorMarkFlagFilename(name, exts...) errorMarkPersistentFlagFilename(name, exts...) errorMarkFlagDirname(name) errorMarkPersistentFlagDirname(name) errorMarkFlagsRequiredTogether(flagNames...)— cross-flag dependencyMarkFlagsOneRequired(flagNames...)— at-least-one-required groupMarkFlagsMutuallyExclusive(flagNames...)— mutual exclusion groupValidateFlagGroups() error— check cross-flag constraintsRegisterFlagCompletionFunc(name, CompletionFunc) error— per-flag dynamic completionsGetFlagCompletionFunc(name) (CompletionFunc, bool)
I/O:
SetOut(io.Writer)/OutOrStdout() io.WriterSetErr(io.Writer)/ErrOrStderr() io.WriterSetIn(io.Reader)/InOrStdin() io.ReaderPrint,Println,Printf,PrintErr,PrintErrln,PrintErrf— write to configured writers
Display / help:
SetHelpFunc(func(*Command, []string))— override help renderingSetHelpTemplate(string)— override help templateSetUsageFunc(func(*Command) error)— override usage renderingSetUsageTemplate(string)— override usage templateSetVersionTemplate(string)— override version outputSetErrPrefix(string)— prefix on error messagesSetHelpCommand(*Command)— replace the built-inhelpcommandHelp() error/Usage() error— manually invoke help/usage outputUsageString() string— capture usage as a string
Shell completions:
GenBashCompletionV2(w, includeDesc) error/GenBashCompletionFileV2(filename, includeDesc) errorGenBashCompletion(w) error/GenBashCompletionFile(filename) error(legacy V1)GenZshCompletion(w) error/GenZshCompletionFile(filename) errorGenZshCompletionNoDesc(w) error/GenZshCompletionFileNoDesc(filename) errorGenFishCompletion(w, includeDesc) error/GenFishCompletionFile(filename, includeDesc) errorGenPowerShellCompletion(w) error/GenPowerShellCompletionFile(filename) errorGenPowerShellCompletionWithDesc(w) error/GenPowerShellCompletionFileWithDesc(filename) errorInitDefaultCompletionCmd(args...)— manually trigger injection ofcompletionsubcommand
Inspection / metadata:
Name() string/DisplayName() string/CommandPath() stringHasSubCommands() bool/IsAvailableCommand() bool/Runnable() boolHasFlags() bool/HasPersistentFlags() bool/HasAvailableFlags() boolSuggestionsFor(typedName) []string— Levenshtein-based suggestionsCalledAs() string— alias or name actually used at runtimeArgsLenAtDash() int— index of--separator in args
Context:
Context() context.ContextSetContext(ctx context.Context)
doc/ subpackage (github.com/spf13/cobra/doc)#
Exported types#
| Type | Kind | Purpose |
|---|---|---|
GenManHeader | struct | Metadata injected into man page front-matter (Title, Section, Date, Source, Manual) |
GenManTreeOptions | struct | Options for GenManTreeFromOpts (header, separator, file prepender) |
Exported functions — grouped by output format#
| Format | Tree (dir) | Single command (io.Writer) | Notes |
|---|---|---|---|
| Man page | GenManTree(cmd, header, dir) | GenMan(cmd, header, w) | GenManTreeFromOpts for full control |
| Markdown | GenMarkdownTree(cmd, dir) | GenMarkdown(cmd, w) | GenMarkdownCustom / GenMarkdownTreeCustom for link/prepender hooks |
| reStructuredText | GenReSTTree(cmd, dir) | GenReST(cmd, w) | GenReSTCustom / GenReSTTreeCustom |
| YAML | GenYamlTree(cmd, dir) | GenYaml(cmd, w) | GenYamlCustom / GenYamlTreeCustom |
All functions recursively walk the command tree via a shared Walk(cmd, fn) utility.
API style and design observations#
Fluent struct literal construction (primary idiom)#
Cobra’s API is designed around constructing Command structs with named fields in a struct literal — not via constructors or builders. This is the idiomatic entrypoint:
rootCmd := &cobra.Command{
Use: "myapp",
Short: "A brief description",
RunE: func(cmd *cobra.Command, args []string) error {
return doWork(args)
},
}This makes command definitions readable and self-documenting but requires understanding a large struct.
Function fields over interfaces#
Hooks (Run, PreRun, ValidArgsFunction, etc.) are function fields, not interface methods. This avoids forcing consumers to define named types and enables inline closures. It is the dominant extensibility mechanism.
Method chaining is absent#
Cobra does not use a builder pattern. Configuration calls are independent method calls (cmd.Flags().StringVar(...), cmd.MarkFlagRequired(...)), not chained.
Backward compatibility#
Cobra maintains strong backward compatibility. Legacy APIs (GenBashCompletion V1, ExactValidArgs, MarkZshCompPositionalArgument*) are kept alongside their modern replacements. The doc/ package is separately versioned to avoid dragging doc-gen dependencies into the core.
pflag re-export#
Cobra does not re-export pflag types directly but exposes them through Flags(), PersistentFlags(), etc. Consumers must import pflag separately to call StringVar, BoolP, and similar flag definition methods.