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 via CompletionOptions.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 via InitDefaultHelpFlag()
  • --version / -v — added lazily to any command that sets Command.Version
  • --no-descriptions — added to completion subcommands 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 pointTypeHow to use
Command.Run / RunEfunc(*Command, []string) [error]Primary user logic hook
Command.PreRun / PreRunEfunc(*Command, []string) [error]Setup before Run
Command.PostRun / PostRunEfunc(*Command, []string) [error]Teardown after Run
Command.PersistentPreRun / PersistentPreRunEfunc(*Command, []string) [error]Inherited by children
Command.PersistentPostRun / PersistentPostRunEfunc(*Command, []string) [error]Inherited by children
Command.Args (PositionalArgs)func(*Command, []string) errorPositional argument validation
Command.ValidArgsFunction (CompletionFunc)func(*Command, []string, string) ([]Completion, ShellCompDirective)Dynamic shell completions for positional args
OnInitialize(func())Package-level callbackRuns before each command execution (e.g., config loading)
OnFinalize(func())Package-level callbackRuns after each command execution
Command.SetUsageFunc(func(*Command) error)MethodReplace usage output entirely
Command.SetHelpFunc(func(*Command, []string))MethodReplace help output entirely
Command.SetUsageTemplate(string)MethodReplace usage text/template
Command.SetHelpTemplate(string)MethodReplace help text/template
AddTemplateFunc(name, func)Package-levelInject custom functions into all templates
Command.SetFlagErrorFunc(func(*Command, error) error)MethodOverride flag parse error handling
Command.RegisterFlagCompletionFunc(flagName, CompletionFunc)MethodDynamic completions for a specific flag
Command.SetGlobalNormalizationFunc(func)MethodNormalize flag names globally

Library API (primary usage mode)#

Core package (github.com/spf13/cobra)#

Exported types#

TypeKindPurpose
Commandstruct (~260 fields/methods)The single central abstraction; represents one node in the command tree
GroupstructGroups subcommands together in help output ({ID, Title string})
FParseErrWhitelisttype alias for pflag.ParseErrorsAllowlistSelectively ignore flag parse errors
PositionalArgsfunc(*Command, []string) errorType alias for positional argument validators
ShellCompDirectiveint bitmaskHints to the shell about how to handle completions
CompletionOptionsstructFine-grained control over the completion subcommand behavior
Completiontype alias for stringA completion candidate (optionally TAB-separated with description)
CompletionFuncfunc(*Command, []string, string) ([]Completion, ShellCompDirective)Signature for dynamic completion providers
SliceValueinterfaceImplemented by pflag slice types; enables multi-value completion

Package-level variables (behavioral configuration)#

VariableDefaultPurpose
EnablePrefixMatchingfalseAccept unambiguous prefix as command name
EnableCommandSortingtrueSort subcommands alphabetically in help
EnableCaseInsensitivefalseCase-insensitive command name matching
EnableTraverseRunHooksfalseRun ALL ancestor PersistentPreRun hooks vs. only closest
MousetrapHelpText(Windows guard text)Text shown when CLI is launched from Windows Explorer
MousetrapDisplayDuration5sHow long the Windows mousetrap text is shown

Positional argument validators (package-level functions)#

FunctionSignatureBehavior
NoArgsPositionalArgsRejects any positional args
ArbitraryArgsPositionalArgsAccepts any positional args without restriction
OnlyValidArgsPositionalArgsRestricts to Command.ValidArgs list
MinimumNArgs(n)func(int) PositionalArgsAt least n args required
MaximumNArgs(n)func(int) PositionalArgsAt most n args allowed
ExactArgs(n)func(int) PositionalArgsExactly n args required
RangeArgs(min, max)func(int, int) PositionalArgsBetween min and max args
MatchAll(pargs...)func(...PositionalArgs) PositionalArgsCompose multiple validators (all must pass)
ExactValidArgs(n)func(int) PositionalArgsExactly n args, each must be in ValidArgs

Completion helpers (package-level functions)#

FunctionPurpose
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, CompErrorlnDebug/error logging helpers for completion functions

Flag annotation helpers (package-level functions on pflag.FlagSet)#

FunctionPurpose
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; parses os.Args[1:] and dispatches
  • ExecuteContext(ctx) error — Execute with a context
  • ExecuteC() (*Command, error) — Execute returning the matched command
  • ExecuteContextC(ctx) (*Command, error) — combination of above two

Tree management:

  • AddCommand(cmds ...*Command) — attach subcommands
  • RemoveCommand(cmds ...*Command) — detach subcommands
  • Commands() []*Command — list direct children
  • ResetCommands() — remove all children
  • AddGroup(groups ...*Group) — register display groups
  • Groups() []*Group — list groups
  • Parent() *Command / Root() *Command — navigation
  • Find(args) (*Command, []string, error) — tree search by args
  • Traverse(args) (*Command, []string, error) — tree search with flag parsing

Flag management:

  • Flags() *pflag.FlagSet — local + inherited flags
  • PersistentFlags() *pflag.FlagSet — flags inherited by children
  • LocalFlags() *pflag.FlagSet — flags local to this command
  • InheritedFlags() *pflag.FlagSet — flags from ancestors
  • ParseFlags(args) error — invoke pflag parsing
  • Flag(name) *pflag.Flag — lookup by name
  • MarkFlagRequired(name) error — require a flag
  • MarkPersistentFlagRequired(name) error
  • MarkFlagFilename(name, exts...) error
  • MarkPersistentFlagFilename(name, exts...) error
  • MarkFlagDirname(name) error
  • MarkPersistentFlagDirname(name) error
  • MarkFlagsRequiredTogether(flagNames...) — cross-flag dependency
  • MarkFlagsOneRequired(flagNames...) — at-least-one-required group
  • MarkFlagsMutuallyExclusive(flagNames...) — mutual exclusion group
  • ValidateFlagGroups() error — check cross-flag constraints
  • RegisterFlagCompletionFunc(name, CompletionFunc) error — per-flag dynamic completions
  • GetFlagCompletionFunc(name) (CompletionFunc, bool)

I/O:

  • SetOut(io.Writer) / OutOrStdout() io.Writer
  • SetErr(io.Writer) / ErrOrStderr() io.Writer
  • SetIn(io.Reader) / InOrStdin() io.Reader
  • Print, Println, Printf, PrintErr, PrintErrln, PrintErrf — write to configured writers

Display / help:

  • SetHelpFunc(func(*Command, []string)) — override help rendering
  • SetHelpTemplate(string) — override help template
  • SetUsageFunc(func(*Command) error) — override usage rendering
  • SetUsageTemplate(string) — override usage template
  • SetVersionTemplate(string) — override version output
  • SetErrPrefix(string) — prefix on error messages
  • SetHelpCommand(*Command) — replace the built-in help command
  • Help() error / Usage() error — manually invoke help/usage output
  • UsageString() string — capture usage as a string

Shell completions:

  • GenBashCompletionV2(w, includeDesc) error / GenBashCompletionFileV2(filename, includeDesc) error
  • GenBashCompletion(w) error / GenBashCompletionFile(filename) error (legacy V1)
  • GenZshCompletion(w) error / GenZshCompletionFile(filename) error
  • GenZshCompletionNoDesc(w) error / GenZshCompletionFileNoDesc(filename) error
  • GenFishCompletion(w, includeDesc) error / GenFishCompletionFile(filename, includeDesc) error
  • GenPowerShellCompletion(w) error / GenPowerShellCompletionFile(filename) error
  • GenPowerShellCompletionWithDesc(w) error / GenPowerShellCompletionFileWithDesc(filename) error
  • InitDefaultCompletionCmd(args...) — manually trigger injection of completion subcommand

Inspection / metadata:

  • Name() string / DisplayName() string / CommandPath() string
  • HasSubCommands() bool / IsAvailableCommand() bool / Runnable() bool
  • HasFlags() bool / HasPersistentFlags() bool / HasAvailableFlags() bool
  • SuggestionsFor(typedName) []string — Levenshtein-based suggestions
  • CalledAs() string — alias or name actually used at runtime
  • ArgsLenAtDash() int — index of -- separator in args

Context:

  • Context() context.Context
  • SetContext(ctx context.Context)

doc/ subpackage (github.com/spf13/cobra/doc)#

Exported types#

TypeKindPurpose
GenManHeaderstructMetadata injected into man page front-matter (Title, Section, Date, Source, Manual)
GenManTreeOptionsstructOptions for GenManTreeFromOpts (header, separator, file prepender)

Exported functions — grouped by output format#

FormatTree (dir)Single command (io.Writer)Notes
Man pageGenManTree(cmd, header, dir)GenMan(cmd, header, w)GenManTreeFromOpts for full control
MarkdownGenMarkdownTree(cmd, dir)GenMarkdown(cmd, w)GenMarkdownCustom / GenMarkdownTreeCustom for link/prepender hooks
reStructuredTextGenReSTTree(cmd, dir)GenReST(cmd, w)GenReSTCustom / GenReSTTreeCustom
YAMLGenYamlTree(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.