or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

command-basics.mdcompletions.mddoc-generation.mdflags.mdindex.md
tile.json

command-basics.mddocs/

Command Basics

This document covers creating, configuring, and managing Cobra commands including command structure, execution, argument validation, help/usage customization, and command groups.

Command Creation

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...")
    },
}

Command Field Descriptions

  • Use: One-line usage message (first word becomes the command name)
  • Aliases: Alternative names for the command
  • SuggestFor: Command names this will be suggested for (typo correction)
  • Short: Brief description shown in parent's help
  • Long: Detailed description shown in command's help
  • Example: Usage examples shown in help
  • ValidArgs: List of valid non-flag arguments for completion
  • ValidArgsFunction: Dynamic argument completion function
  • Args: Positional argument validator function
  • ArgAliases: Accepted but not suggested argument aliases
  • BashCompletionFunction: Custom bash completion (legacy, use ValidArgsFunction)
  • Deprecated: Deprecation message if command is deprecated
  • Annotations: Key-value metadata for custom use
  • Version: Version string (auto-adds --version flag if set)
  • GroupID: Group ID for organizing in help output

Run Hooks

Run hooks execute in this order (all receive cmd *Command and args []string):

  1. PersistentPreRun / PersistentPreRunE: Inherited by children, runs before PreRun
  2. PreRun / PreRunE: Not inherited, runs before Run
  3. Run / RunE: Main command logic
  4. PostRun / PostRunE: Not inherited, runs after Run
  5. PersistentPostRun / PersistentPostRunE: Inherited by children, runs after PostRun

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
    },
}

Boolean Configuration Fields

  • TraverseChildren: Parse flags on all parents before executing child
  • Hidden: Hide command from help output
  • SilenceErrors: Suppress error messages downstream
  • SilenceUsage: Suppress usage output when error occurs
  • DisableFlagParsing: Pass all flags as arguments without parsing
  • DisableAutoGenTag: Omit "Auto generated by spf13/cobra" in docs
  • DisableFlagsInUseLine: Don't show [flags] in usage line
  • DisableSuggestions: Disable command suggestions on typos
  • SuggestionsMinimumDistance: Minimum Levenshtein distance for suggestions (must be > 0)

Command Structure Management

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() bool

Add subcommands to build command hierarchy:

rootCmd := &cobra.Command{Use: "app"}
serveCmd := &cobra.Command{Use: "serve"}
fetchCmd := &cobra.Command{Use: "fetch"}

rootCmd.AddCommand(serveCmd, fetchCmd)
  • AddCommand: Add one or more child commands
  • RemoveCommand: Remove child commands
  • ResetCommands: Reset command tree (clears parent, commands, help command, and parent flags)
  • Commands: Get sorted list of child commands
  • Parent: Get parent command
  • HasParent: Check if command has parent
  • HasSubCommands: Check if command has children
  • HasAvailableSubCommands: Check if has non-hidden children
  • HasHelpSubCommands: Check if has help topic commands

Command Execution

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)
}
  • Execute: Execute using os.Args[1:], returns error
  • ExecuteC: Execute and return the executed command plus error
  • ExecuteContext: Execute with context (sets context on command)
  • ExecuteContextC: ExecuteC with context
  • Context: Get command context (set via ExecuteContext or SetContext)
  • SetContext: Manually set command context

Command Discovery

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))
  • Find: Find target command given args (searches down tree)
  • Traverse: Traverse command tree with args
  • Root: Get root command (traverses up parent chain)
  • Name: Get command name (first word in Use)
  • DisplayName: Get display name (may differ from Name via annotation)
  • HasAlias: Check if string is command alias
  • NameAndAliases: Get command name and all aliases
  • NamePadding: Get padding for command name in help output
  • CalledAs: Get name/alias used to invoke command (empty if not called)
  • CommandPath: Get full command path (e.g., "app serve start")
  • CommandPathPadding: Get padding for command path in help
  • IsAvailableCommand: Check if available (not hidden/deprecated)
  • IsAdditionalHelpTopicCommand: Check if help topic command
  • Runnable: Check if command has Run or RunE function defined
  • SuggestionsFor: Get command suggestions for a typed name (used for typo correction)
  • VisitParents: Visit all parent commands by calling function on each parent

Argument Validation

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) error

Set 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:

  • NoArgs: Returns error if any args provided
  • ArbitraryArgs: Accepts any number of args (always returns nil)
  • OnlyValidArgs: Only accepts args in ValidArgs field
  • MinimumNArgs(n): Requires at least n args
  • MaximumNArgs(n): Accepts at most n args
  • ExactArgs(n): Requires exactly n args
  • RangeArgs(min, max): Requires between min and max args
  • MatchAll(pargs...): Combines multiple validators (all must pass)
  • ExactValidArgs(n): Requires exactly n args AND they must be in ValidArgs (deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs))
  • ValidateArgs: Validates args using the command's Args validator (uses ArbitraryArgs if none set)

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() int

ArgsLenAtDash: Returns length of args before -- separator during parsing.

Help and Usage

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}}
`)
  • Help: Display help using HelpFunc
  • Usage: Display usage using UsageFunc
  • UsageString: Get usage string as string (captures Usage() output)
  • UsagePadding: Get padding for usage string in help output
  • UseLine: Get usage line (e.g., "app serve [flags]")
  • SetHelpFunc: Set custom help function
  • SetUsageFunc: Set custom usage function
  • SetHelpTemplate: Set custom help template
  • SetUsageTemplate: Set custom usage template
  • SetVersionTemplate: Set custom version template
  • SetErrPrefix: Set error message prefix
  • HelpFunc: Get current help function (command's or parent's)
  • UsageFunc: Get current usage function
  • HelpTemplate: Get help template (kept for backwards compatibility)
  • UsageTemplate: Get usage template
  • VersionTemplate: Get version template
  • ErrPrefix: Get error message prefix
  • HasExample: Check if command has example field set
  • InitDefaultHelpFlag: Add default --help flag
  • InitDefaultHelpCmd: Add default help command
  • InitDefaultVersionFlag: Add default --version flag
  • SetHelpCommand: Set custom help command
  • SetHelpCommandGroupID: Set group ID for help command

Command Groups

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)
  • AddGroup: Add one or more command groups
  • Groups: Get all command groups
  • ContainsGroup: Check if group exists by ID
  • AllChildCommandsHaveGroup: Check if all children assigned to groups
  • SetCompletionCommandGroupID: Set group ID for completion command

Input/Output Configuration

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()
  • SetIn: Set custom input reader
  • SetOut: Set custom output writer
  • SetErr: Set custom error writer
  • SetOutput: Set both output and error writer to the same writer
  • InOrStdin: Get input reader or stdin if not set
  • OutOrStdout: Get output writer or stdout if not set
  • OutOrStderr: Get output writer for errors or stderr if not set
  • ErrOrStderr: Get error writer or stderr if not set
  • Print: Print to output writer
  • Println: Print line to output writer
  • Printf: Printf to output writer
  • PrintErr: Print to error writer
  • PrintErrln: Print line to error writer
  • PrintErrf: Printf to error writer

Testing and Configuration

func (c *Command) SetArgs(args []string)
func (c *Command) DebugFlags()
  • SetArgs: Set arguments for testing (replaces os.Args)
  • DebugFlags: Print debug info about flag assignments
cmd := &cobra.Command{Use: "test"}
cmd.SetArgs([]string{"--flag=value", "arg1"})
err := cmd.Execute()

Global Configuration

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)
})
  • EnablePrefixMatching: Allow automatic prefix matching (default: false)
  • EnableCommandSorting: Sort commands alphabetically (default: true)
  • EnableCaseInsensitive: Allow case-insensitive command names (default: false)
  • EnableTraverseRunHooks: Execute persistent hooks from all parents (default: false)
  • MousetrapHelpText: Help text shown on Windows when launched from explorer
  • MousetrapDisplayDuration: Duration to display mousetrap (default: 5s, set 0 to wait for key)
  • OnInitialize: Register functions to run when Execute is called
  • OnFinalize: Register functions to run when Execute terminates
  • AddTemplateFunc: Add single template function for help/usage templates
  • AddTemplateFuncs: Add multiple template functions

Utility Functions

func CheckErr(msg interface{})
func WriteStringAndCheck(b io.StringWriter, s string)
func Gt(a interface{}, b interface{}) bool
func Eq(a interface{}, b interface{}) bool
  • CheckErr: Print error with "Error:" prefix and exit with code 1 if not nil
  • WriteStringAndCheck: Write string to StringWriter and CheckErr on error
  • Gt: Greater-than comparison for templates (arrays/slices compare lengths, ints direct, strings parsed as ints)
  • Eq: Equality comparison for templates (supports int and string)
err := someOperation()
cobra.CheckErr(err) // Exits if err != nil

Type Aliases

type FParseErrWhitelist = pflag.ParseErrorsAllowlist

FParseErrWhitelist configures which flag parse errors to ignore. It's an alias for pflag.ParseErrorsAllowlist from the github.com/spf13/pflag package.

Flag Error Handling

func (c *Command) SetFlagErrorFunc(f func(*Command, error) error)
func (c *Command) FlagErrorFunc() func(*Command, error) error
  • SetFlagErrorFunc: Set custom flag error handler
  • FlagErrorFunc: Get flag error handler (command's or parent's)
cmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
    fmt.Fprintf(os.Stderr, "Flag error: %v\n", err)
    return err
})

Normalization

func (c *Command) SetGlobalNormalizationFunc(func(*pflag.FlagSet, string) pflag.NormalizedName)
func (c *Command) GlobalNormalizationFunc() func(*pflag.FlagSet, string) pflag.NormalizedName
  • SetGlobalNormalizationFunc: Set flag name normalization function
  • GlobalNormalizationFunc: Get global normalization function

Flag 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, "_", "-"))
})