Golang Spf13 Cobra
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Cobra is the industry-standard library for creating CLI applications in Go. It provides a robust framework for defining command hierarchies, managing persistent and local flags, validating positional arguments, and generating shell completion scripts. This skill covers the lifecycle of cobra commands, including the RunE hook chain, argument validation patterns, and testing strategies for CLI tools.
What it does
- Defines hierarchical command and subcommand trees for Go CLIs.
- Handles flag parsing and validation using pflag.
- Provides a structured hook system (PersistentPreRunE to PersistentPostRunE) for command execution.
- Implements positional argument validation with built-in and custom validators.
- Generates shell completion scripts for bash, zsh, fish, and PowerShell.
- Supports automated documentation generation including man pages and markdown.
When to use it
- When building a new Go CLI application that requires subcommands.
- When you need to implement complex flag parsing or argument validation.
- When you want to provide native shell completion support for your users.
- When you need to generate documentation or man pages for your CLI tool.
Advantages
- Standardizes CLI structure across Go projects.
- Separates command logic from configuration management (when paired with viper).
- Enables testable CLI code through output redirection and command execution.
- Reduces boilerplate for common CLI tasks like help text and flag parsing.
Usage examples
- “How do I define a root command with a subcommand in cobra?”
- You create a root cobra.Command and use the AddCommand method to register subcommands, typically within an init function or the main package.
- “How can I validate that a command receives exactly one argument?”
- Set the Args field of your cobra.Command to cobra.ExactArgs(1) to ensure cobra handles validation and error reporting before your RunE logic executes.
- “How do I test a cobra command without writing to stdout?”
- Use SetOut and SetErr on your command instance with a bytes.Buffer, then call Execute to capture the output for assertions in your test.
- “Where should I initialize configuration in a cobra CLI?”
- Use the PersistentPreRunE hook on your root command to initialize configuration, as it runs before every subcommand execution.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-spf13-cobra/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-spf13-cobra.zip -d .agents/skills
Documentation by samber
Persona: You are a Go CLI engineer building command trees that feel native to the Unix shell. You design the user-facing surface first, then wire behavior into the right hook.
Modes:
Build — creating a new CLI from scratch: follow command tree setup, hook wiring, and flag sections sequentially.
Extend — adding subcommands, flags, or completions to an existing CLI: read the current command tree first, then apply changes consistent with the existing structure.
Review — auditing an existing CLI: check the Common Mistakes table, verify
RunEusage,OutOrStdout(), hook chain ordering, and args validation.
Using spf13/cobra for CLI command trees in Go
Cobra is the de facto standard for Go CLI applications. It provides the command/subcommand tree, flag parsing (via pflag), args validation, shell completion generation, and documentation generation. It does not handle configuration layering — that's viper's job.
Official Resources:
This skill is not exhaustive — refer to library documentation and code examples for more information:
For Go package docs, symbols, versions, importers, and known vulnerabilities, → See
samber/cc-skills-golang@golang-pkg-go-devskill (godig), preferred over Context7 for Go package facts.To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See
samber/cc-skills-golang@golang-goplsskill (gopls).Context7 remains a fallback for docs not indexed on pkg.go.dev.
go get github.com/spf13/cobra@latestCobra vs. viper
These libraries do fundamentally different things and can be used independently.
| Concern | cobra | viper |
|---|---|---|
| Owns | Command tree, flags, arg validation, completions | Configuration value resolution |
| User-facing? | Yes — subcommands, flags, help text | No — purely a key-value resolver |
| Without the other? | Yes — a CLI with flags only needs cobra | Yes — a daemon reading YAML + env needs only viper |
| Integration seam | Hands pflag.Flag to viper via BindPFlag | Treats the cobra flag as the highest-precedence layer |
Use cobra alone when your binary takes flags and args but needs no config file or env resolution. Use viper alone when you have a long-running service reading config from YAML + env with no CLI subcommands. Use both when you need both — bind at PersistentPreRunE on the root command.
→ See samber/cc-skills-golang@golang-spf13-viper for the viper side of this integration.
Command tree
Every cobra CLI has a root command plus zero or more subcommands registered with AddCommand. The root command name is the binary name.
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "One-line summary",
SilenceUsage: true, // ✓ prevents usage wall on every error
SilenceErrors: true, // ✓ lets you control error output format
}Use AddGroup to label subcommands in help output — register groups before the AddCommand calls that reference them; cobra does not retroactively assign groups.
The Run* family
Cobra commands have five run hooks executed in order:
PersistentPreRunE → PreRunE → RunE → PostRunE → PersistentPostRunEAlways use *E variants — the non-E forms cannot return errors. Key rules:
PersistentPreRunEon the root runs before every subcommand — use it for config init and auth checks.A child
PersistentPreRunEreplaces the parent's entirely — call the parent explicitly if you need both.PostRunEruns only ifRunEsucceeded.
For the full lifecycle and inheritance rules, see commands-and-args.md.
Args validators
Cobra validates positional arguments before RunE runs. Never write len(args) checks inside RunE — that bypasses cobra's standard error messages and arg count tracking.
Built-ins: NoArgs, ExactArgs(n), MinimumNArgs(n), MaximumNArgs(n), RangeArgs(min,max), OnlyValidArgs, ExactValidArgs(n). Compose with MatchAll(v1, v2). Custom validator: func(cmd *cobra.Command, args []string) error.
For the full validator set with examples and MatchAll patterns, see commands-and-args.md.
Flags primer
Cobra delegates flag parsing to pflag. Persistent flags (PersistentFlags()) are inherited by all subcommands; local flags (Flags()) apply only to the declaring command.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file path") // inherited by all subcommands
serveCmd.Flags().IntVar(&port, "port", 8080, "listen port") // local to serveCmd only
serveCmd.MarkFlagRequired("port")
serveCmd.MarkFlagsMutuallyExclusive("json", "yaml")For pflag types, custom flag values, flag groups, and viper binding, see flags.md.
Completions primer
Cobra generates shell completions automatically. Extend them with:
ValidArgs []string— static positional arg completion.ValidArgsFunction— dynamic:func(cmd, args, toComplete string) ([]string, ShellCompDirective). ReturnShellCompDirectiveNoFileCompto suppress file fallback.RegisterFlagCompletionFunc(name, fn)— flag value completion.
For ShellCompDirective values, annotations, and testing, see completions.md.
Testing commands
Test commands by executing them programmatically. Never use os.Stdout / os.Stderr directly in command handlers — use cmd.OutOrStdout() / cmd.ErrOrStderr() so tests can redirect output.
func TestServeCmd(t *testing.T) {
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetArgs([]string{"serve", "--port", "9090"})
require.NoError(t, rootCmd.Execute())
assert.Contains(t, buf.String(), "listening on :9090")
}Cobra accumulates flag state across Execute() calls — build a fresh command tree per test. For isolation patterns, golden files, and testing completions, see testing.md.
Best Practices
Always use
RunE, neverRun—Runcannot return an error; the only escape isos.Exitor panic, bypassing defers.Put config initialization in
PersistentPreRunE— it runs before every subcommand; the right place for viper binding and auth checks.Validate positional args with
Args, not insideRunE—Argsgives cobra's standard error messages;MatchAllcomposes validators.Use
cmd.OutOrStdout()/cmd.ErrOrStderr()for all output — directos.Stdoutwrites cannot be captured by tests.Re-create the command tree per test — cobra accumulates flag state across
Execute()calls on the same instance.
Common Mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
Using Run instead of RunE | Cannot return an error — only escape is os.Exit or panic, bypassing defers | Use RunE — return the error, let cobra handle the exit |
Writing len(args) checks in RunE | Bypasses cobra's standard error messages ("accepts 1 arg, received 2") | Declare Args: cobra.ExactArgs(1) on the command |
Writing to os.Stdout directly | Tests cannot capture output — os-level file handles can't be redirected | Use cmd.OutOrStdout() / cmd.ErrOrStderr() |
Child PersistentPreRunE silently drops parent's | Cobra does not chain — the child replaces the parent's hook entirely | Call parent.PersistentPreRunE(cmd, args) from the child's hook |
| Reusing a root command across tests | Cobra accumulates flag state; second Execute() sees flags from the first | Build a fresh command tree per test |
Further Reading
commands-and-args.md — full PreRun*/PostRun* chain, every Args validator, PersistentPreRunE inheritance rules
flags.md — pflag types, required/exclusive/oneRequired groups, custom value types, viper binding
completions.md — ShellCompDirective set, annotation-based completions, testing completions
generators.md — man page, markdown, YAML, RST doc generation;
cobra-cliscaffoldertesting.md — isolation patterns, golden files, testing completions, table-driven command tests
Cross-References
→ See
samber/cc-skills-golang@golang-cliskill for general CLI architecture — project layout, exit codes, signal handling, I/O patterns→ See
samber/cc-skills-golang@golang-spf13-viperskill for configuration layering alongside cobra (flag → env → file → default precedence)→ See
samber/cc-skills-golang@golang-testingskill for general Go testing patterns
If you encounter a bug or unexpected behavior in spf13/cobra, open an issue at https://github.com/spf13/cobra/issues.
Files
- ATTRIBUTION.mdAdded by AutoGineer911 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md10.2 KiB
- evals/evals.json19.1 KiB
- references/commands-and-args.md5.5 KiB
- references/completions.md4.4 KiB
- references/flags.md4.3 KiB
- references/generators.md2.5 KiB
- references/testing.md4.3 KiB
references/flags.md
Cobra Flags Reference
Cobra delegates all flag parsing to github.com/spf13/pflag. cobra.Command exposes two *pflag.FlagSets:
cmd.Flags()— local flags, only available on this command.cmd.PersistentFlags()— inherited by all subcommands.
Table of Contents
Common flag types
StringSlice vs StringArray
Flag constraints
Persistent flag patterns
Custom flag value types
Flag groups (required together)
Accessing flag values
Flag changed vs default
Common flag types
// String
cmd.Flags().String("name", "default", "description")
cmd.Flags().StringP("name", "n", "default", "description") // with shorthand
// With pointer binding (no Lookup needed later)
var name string
cmd.Flags().StringVar(&name, "name", "default", "description")
cmd.Flags().StringVarP(&name, "name", "n", "default", "description")
// Other types follow the same pattern:
cmd.Flags().Int / IntVar / IntVarP
cmd.Flags().Bool / BoolVar / BoolVarP
cmd.Flags().Float64 / Float64Var
cmd.Flags().Duration / DurationVar // parses "1h30m", "500ms"
cmd.Flags().StringSlice / StringSliceVar // comma-separated or repeated flags
cmd.Flags().StringArray / StringArrayVar // repeated flags only (no comma splitting)
cmd.Flags().IntSlice / IntSliceVar
cmd.Flags().StringToString // --label key=value --label k2=v2StringSlice vs StringArray
| Flag type | Input | Result |
|---|---|---|
StringSlice | --tags a,b --tags c | ["a", "b", "c"] — commas split |
StringArray | --tags a,b --tags c | ["a,b", "c"] — commas NOT split |
Use StringArray when values may legitimately contain commas.
Flag constraints
// Fail if flag not provided
cmd.MarkFlagRequired("output")
// Fail if both provided
cmd.MarkFlagsMutuallyExclusive("json", "yaml", "table")
// Fail if none provided
cmd.MarkFlagsOneRequired("file", "stdin")
// Require flag only if another flag is set
cmd.MarkFlagsMutuallyExclusive("tls", "no-tls")Persistent flag patterns
func init() {
// global flags on root
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default: $HOME/.myapp.yaml)")
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "log level (debug, info, warn, error)")
// bind to viper immediately after defining
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
}Custom flag value types
Implement pflag.Value to parse arbitrary types:
type enumValue struct {
val string
allowed []string
}
func (e *enumValue) String() string { return e.val }
func (e *enumValue) Type() string { return "enum" }
func (e *enumValue) Set(s string) error {
for _, a := range e.allowed {
if s == a {
e.val = s
return nil
}
}
return fmt.Errorf("must be one of %v", e.allowed)
}
var outputFmt = &enumValue{val: "table", allowed: []string{"table", "json", "yaml"}}
cmd.Flags().Var(outputFmt, "output", "output format (table, json, yaml)")Flag groups (required together)
Mark a set of flags that must all be provided if any one of them is provided:
cmd.Flags().String("tls-cert", "", "TLS certificate file")
cmd.Flags().String("tls-key", "", "TLS key file")
cmd.MarkFlagsRequiredTogether("tls-cert", "tls-key")Accessing flag values
Prefer pointer binding (StringVar, IntVar, etc.) for type-safe access. When you need the flag post-parse:
port, err := cmd.Flags().GetInt("port")
name, err := cmd.Flags().GetString("name")
tags, err := cmd.Flags().GetStringSlice("tags")Flag changed vs default
if cmd.Flags().Changed("port") {
// user explicitly provided --port
// useful when distinguishing "user set 0" from "flag not provided"
}Changed() is also how viper knows which flags are explicit overrides — it only promotes a flag to the highest precedence layer if Changed() is true.
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-spf13-cobra · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-spf13-cobra.zip