golang-spf13-cobra
Golang CLI command tree library using spf13/cobra — cobra.Command, RunE vs Run, PersistentPreRunE hook chain, Args validators (NoArgs, ExactArgs, MatchAll, custom), persistent vs local flags, command groups, ValidArgsFunction, RegisterFlagCompletionFunc, ShellCompDirective, usage/help template custo
- 0
- Installs
- —
- Rating
- —
- Success rate
- 7
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 89acc845061e6d0a… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
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@latest
Cobra 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 → PersistentPostRunE
Always 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-cliscaffolder - testing.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
7- SKILL.md
f77b93e6f110.2 KB - evals/evals.json
6ba662758219.1 KB - references/commands-and-args.md
9c26741d545.5 KB - references/completions.md
e8bcf042bf4.4 KB - references/flags.md
fe465340714.3 KB - references/generators.md
73cfbec7062.5 KB - references/testing.md
059ca04ad14.3 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from samber/cc-skills-golang8
Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hot paths with pprof, interpreting CPU/memory/trace profiles, analyzing results with benchstat, setting up CI benchmark regression detection, or investigating production perf
Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also trig
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golan
Golang concurrency design — goroutine lifecycle and leak prevention, channels and `select`, channel ownership and direction, `sync.Mutex`/`RWMutex`/`sync.Map`/`sync.Once`/atomics, `errgroup`, `singleflight`, worker pools, and fan-out/fan-in pipelines. Use when writing or reviewing concurrent Go code
Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, c
GitHub Actions CI/CD pipeline configuration for Golang projects — workflow files for test, lint, SAST, coverage and vulnerability-scan jobs, Dependabot and Renovate config files, GoReleaser release pipelines, Docker build/push, repository security settings, and AI-driven PR review. Use when setting
Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when cho
Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interact
Related tooling skillsscan passed
Generate review drafts of counterparty master agreements from one template plus a JSON spec, with role-selected clauses and a Schedule A workflow limited to the executed agreement's notice authority. Use when you need reproducible drafting and separately reviewed execution preparation.
Web performance regression detection. (gstack)
Audit and improve CLAUDE.md files in repositories. Use when user asks to check, audit, update, improve, or fix CLAUDE.md files. Scans for all CLAUDE.md files, evaluates quality against templates, outputs quality report, then makes targeted updates. Also use when the user mentions "CLAUDE.md maintena
Helps you build and check a color system for your project. It generates palettes, names semantic tokens, converts between formats and measures contrast.
Creates a new Angular app using the Angular CLI. This skill should be used whenever a user wants to create a new Angular application and contains important guidelines for how to effectively create a modern Angular application.
Audit, diagnose, or optimize website loading and interaction performance, Core Web Vitals, and Lighthouse performance scores.