This document covers creating, configuring, and managing Cobra commands including command structure, execution, argument validation, help/usage customization, and command groups.
type Command struct {
Use string
Aliases []string
SuggestFor []string
Short string
Long string
Example string
ValidArgs []Completion
ValidArgsFunction CompletionFunc
Args PositionalArgs
ArgAliases []string
BashCompletionFunction string
Deprecated string
Annotations map[string]string
Version string
GroupID string
PersistentPreRun func(cmd *Command, args []string)
PersistentPreRunE func(cmd *Command, args []string) error
PreRun func(cmd *Command, args []string)
PreRunE func(cmd *Command, args []string) error
Run func(cmd *Command, args []string)
RunE func(cmd *Command, args []string) error
PostRun func(cmd *Command, args []string)
PostRunE func(cmd *Command, args []string) error
PersistentPostRun func(cmd *Command, args []string)
PersistentPostRunE func(cmd *Command, args []string) error
FParseErrWhitelist FParseErrWhitelist
CompletionOptions CompletionOptions
TraverseChildren bool
Hidden bool
SilenceErrors bool
SilenceUsage bool
DisableFlagParsing bool
DisableAutoGenTag bool
DisableFlagsInUseLine bool
DisableSuggestions bool
SuggestionsMinimumDistance int
}Create a new command by initializing a Command struct:
cmd := &cobra.Command{
Use: "serve",
Short: "Start the HTTP server",
Long: "Start the HTTP server on the specified port and host",
Run: func(cmd *cobra.Command, args []string) {
// Command implementation
fmt.Println("Server starting...")
},
}Run hooks execute in this order (all receive cmd *Command and args []string):
The *E variants return errors instead of handling them directly. PreRun and PostRun hooks only execute if Run is defined.
rootCmd := &cobra.Command{
Use: "app",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Initialize resources, validate config
return nil
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
// Cleanup resources
},
}
subCmd := &cobra.Command{
Use: "process",
PreRun: func(cmd *cobra.Command, args []string) {
// Pre-processing specific to this command
},
RunE: func(cmd *cobra.Command, args []string) error {
// Main command logic
return nil
},
}func (c *Command) AddCommand(cmds ...*Command)
func (c *Command) RemoveCommand(cmds ...*Command)
func (c *Command) ResetCommands()
func (c *Command) Commands() []*Command
func (c *Command) Parent() *Command
func (c *Command) HasParent() bool
func (c *Command) HasSubCommands() bool
func (c *Command) HasAvailableSubCommands() bool
func (c *Command) HasHelpSubCommands() boolAdd subcommands to build command hierarchy:
rootCmd := &cobra.Command{Use: "app"}
serveCmd := &cobra.Command{Use: "serve"}
fetchCmd := &cobra.Command{Use: "fetch"}
rootCmd.AddCommand(serveCmd, fetchCmd)func (c *Command) Execute() error
func (c *Command) ExecuteC() (cmd *Command, err error)
func (c *Command) ExecuteContext(ctx context.Context) error
func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error)
func (c *Command) Context() context.Context
func (c *Command) SetContext(ctx context.Context)Execute the command tree starting from root:
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}With context:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}func (c *Command) Find(args []string) (*Command, []string, error)
func (c *Command) Traverse(args []string) (*Command, []string)
func (c *Command) Root() *Command
func (c *Command) Name() string
func (c *Command) DisplayName() string
func (c *Command) HasAlias(s string) bool
func (c *Command) NameAndAliases() string
func (c *Command) NamePadding() int
func (c *Command) CalledAs() string
func (c *Command) CommandPath() string
func (c *Command) CommandPathPadding() int
func (c *Command) IsAvailableCommand() bool
func (c *Command) IsAdditionalHelpTopicCommand() bool
func (c *Command) Runnable() bool
func (c *Command) SuggestionsFor(typedName string) []string
func (c *Command) VisitParents(fn func(*Command))type PositionalArgs func(cmd *Command, args []string) error
func NoArgs(cmd *Command, args []string) error
func ArbitraryArgs(cmd *Command, args []string) error
func OnlyValidArgs(cmd *Command, args []string) error
func MinimumNArgs(n int) PositionalArgs
func MaximumNArgs(n int) PositionalArgs
func ExactArgs(n int) PositionalArgs
func RangeArgs(min int, max int) PositionalArgs
func MatchAll(pargs ...PositionalArgs) PositionalArgs
func ExactValidArgs(n int) PositionalArgs
func (c *Command) ValidateArgs(args []string) errorSet the Args field to validate positional arguments:
cmd := &cobra.Command{
Use: "copy <source> <dest>",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
source := args[0]
dest := args[1]
// Copy logic
},
}Built-in validators:
Combine validators:
cmd := &cobra.Command{
Use: "process <file>...",
Args: cobra.MatchAll(cobra.MinimumNArgs(1), cobra.OnlyValidArgs),
ValidArgs: []cobra.Completion{"input.txt", "data.csv"},
}Get arguments in execution:
func (c *Command) ArgsLenAtDash() intArgsLenAtDash: Returns length of args before -- separator during parsing.
func (c *Command) Help() error
func (c *Command) Usage() error
func (c *Command) UsageString() string
func (c *Command) UsagePadding() int
func (c *Command) UseLine() string
func (c *Command) SetHelpFunc(f func(*Command, []string))
func (c *Command) SetUsageFunc(f func(*Command) error)
func (c *Command) SetHelpTemplate(s string)
func (c *Command) SetUsageTemplate(s string)
func (c *Command) SetVersionTemplate(s string)
func (c *Command) SetErrPrefix(s string)
func (c *Command) HelpFunc() func(*Command, []string)
func (c *Command) UsageFunc() func(*Command) error
func (c *Command) HelpTemplate() string
func (c *Command) UsageTemplate() string
func (c *Command) VersionTemplate() string
func (c *Command) ErrPrefix() string
func (c *Command) HasExample() bool
func (c *Command) InitDefaultHelpFlag()
func (c *Command) InitDefaultHelpCmd()
func (c *Command) InitDefaultVersionFlag()
func (c *Command) SetHelpCommand(cmd *Command)
func (c *Command) SetHelpCommandGroupID(groupID string)Customize help output:
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
fmt.Println("Custom help for", cmd.Name())
// Custom help logic
})
cmd.SetHelpTemplate(`Custom help template for {{.Name}}
{{.Short}}
{{if .Long}}{{.Long}}{{end}}
`)type Group struct {
ID string
Title string
}
func (c *Command) AddGroup(groups ...*Group)
func (c *Command) Groups() []*Group
func (c *Command) ContainsGroup(groupID string) bool
func (c *Command) AllChildCommandsHaveGroup() bool
func (c *Command) SetCompletionCommandGroupID(groupID string)Organize subcommands into groups:
rootCmd := &cobra.Command{Use: "app"}
rootCmd.AddGroup(&cobra.Group{
ID: "management",
Title: "Management Commands",
})
serveCmd := &cobra.Command{
Use: "serve",
GroupID: "management",
Short: "Start server",
}
rootCmd.AddCommand(serveCmd)func (c *Command) SetIn(r io.Reader)
func (c *Command) SetOut(w io.Writer)
func (c *Command) SetErr(w io.Writer)
func (c *Command) SetOutput(output io.Writer)
func (c *Command) InOrStdin() io.Reader
func (c *Command) OutOrStdout() io.Writer
func (c *Command) OutOrStderr() io.Writer
func (c *Command) ErrOrStderr() io.Writer
func (c *Command) Print(i ...interface{})
func (c *Command) Println(i ...interface{})
func (c *Command) Printf(format string, i ...interface{})
func (c *Command) PrintErr(i ...interface{})
func (c *Command) PrintErrln(i ...interface{})
func (c *Command) PrintErrf(format string, i ...interface{})Configure and use custom I/O streams:
var output bytes.Buffer
cmd.SetOut(&output)
cmd.Print("Message to output")
result := output.String()func (c *Command) SetArgs(args []string)
func (c *Command) DebugFlags()cmd := &cobra.Command{Use: "test"}
cmd.SetArgs([]string{"--flag=value", "arg1"})
err := cmd.Execute()var EnablePrefixMatching bool
var EnableCommandSorting bool
var EnableCaseInsensitive bool
var EnableTraverseRunHooks bool
var MousetrapHelpText string
var MousetrapDisplayDuration time.Duration
func OnInitialize(y ...func())
func OnFinalize(y ...func())
func AddTemplateFunc(name string, tmplFunc interface{})
func AddTemplateFuncs(tmplFuncs template.FuncMap)Configure global Cobra behavior:
cobra.EnablePrefixMatching = true // Allow "ser" to match "serve"
cobra.EnableCommandSorting = false // Disable alphabetical sorting
cobra.EnableCaseInsensitive = true // "Serve" matches "serve"
cobra.EnableTraverseRunHooks = true // Run all parent hooks
cobra.OnInitialize(func() {
// Runs when Execute is called
fmt.Println("Initializing...")
})
cobra.OnFinalize(func() {
// Runs when Execute terminates
fmt.Println("Cleaning up...")
})
cobra.AddTemplateFunc("customFunc", func(s string) string {
return strings.ToUpper(s)
})func CheckErr(msg interface{})
func WriteStringAndCheck(b io.StringWriter, s string)
func Gt(a interface{}, b interface{}) bool
func Eq(a interface{}, b interface{}) boolerr := someOperation()
cobra.CheckErr(err) // Exits if err != niltype FParseErrWhitelist = pflag.ParseErrorsAllowlistFParseErrWhitelist configures which flag parse errors to ignore. It's an alias for pflag.ParseErrorsAllowlist from the github.com/spf13/pflag package.
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error)
func (c *Command) FlagErrorFunc() func(*Command, error) errorcmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
fmt.Fprintf(os.Stderr, "Flag error: %v\n", err)
return err
})func (c *Command) SetGlobalNormalizationFunc(func(*pflag.FlagSet, string) pflag.NormalizedName)
func (c *Command) GlobalNormalizationFunc() func(*pflag.FlagSet, string) pflag.NormalizedNameFlag normalization converts flag names (e.g., normalize underscores to dashes):
cmd.SetGlobalNormalizationFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
return pflag.NormalizedName(strings.ReplaceAll(name, "_", "-"))
})