spf13/cobra
A Commander for modern Go CLI interactions
Healthy across the board
Permissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 2w ago
- ✓51+ active contributors
- ✓Distributed ownership (top contributor 11% of recent commits)
Show 3 more →Show less
- ✓Apache-2.0 licensed
- ✓CI configured
- ✓Tests present
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/spf13/cobra)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/spf13/cobra on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: spf13/cobra
Generated by RepoPilot · 2026-05-09 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/spf13/cobra shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across the board
- Last commit 2w ago
- 51+ active contributors
- Distributed ownership (top contributor 11% of recent commits)
- Apache-2.0 licensed
- CI configured
- Tests present
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live spf13/cobra
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/spf13/cobra.
What it runs against: a local clone of spf13/cobra — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in spf13/cobra | Confirms the artifact applies here, not a fork |
| 2 | License is still Apache-2.0 | Catches relicense before you depend on it |
| 3 | Default branch main exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 43 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of spf13/cobra. If you don't
# have one yet, run these first:
#
# git clone https://github.com/spf13/cobra.git
# cd cobra
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of spf13/cobra and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "spf13/cobra(\\.git)?\\b" \\
&& ok "origin remote is spf13/cobra" \\
|| miss "origin remote is not spf13/cobra (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
&& ok "license is Apache-2.0" \\
|| miss "license drift — was Apache-2.0 at generation time"
# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
&& ok "default branch main exists" \\
|| miss "default branch main no longer exists"
# 4. Critical files exist
test -f "command.go" \\
&& ok "command.go" \\
|| miss "missing critical file: command.go"
test -f "cobra.go" \\
&& ok "cobra.go" \\
|| miss "missing critical file: cobra.go"
test -f "args.go" \\
&& ok "args.go" \\
|| miss "missing critical file: args.go"
test -f "flag_groups.go" \\
&& ok "flag_groups.go" \\
|| miss "missing critical file: flag_groups.go"
test -f "completions.go" \\
&& ok "completions.go" \\
|| miss "missing critical file: completions.go"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 43 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~13d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/spf13/cobra"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
Cobra is a Go library for building powerful, modern CLI applications with minimal boilerplate. It provides a command/subcommand structure, POSIX-compliant flags, automatic help generation, shell completions (bash/zsh/fish/powershell), and man page generation. Used by Kubernetes, Hugo, and GitHub CLI, it handles the repetitive parts of CLI development so you focus on business logic. Flat, modular structure: core command orchestration (command.go, args.go, flag_groups.go) defines the Command and Flag API; completion backends are separated (bash_completions.go, fish_completions.go, powershell_completions.go, shell_completions.go); doc generation lives in doc/ subdirectory (md_docs.go, man_docs.go, yaml_docs.go); active_help.go handles runtime suggestions. Each component has parallel _test.go files.
👥Who it's for
Go developers building command-line tools and CLI applications who need structured command hierarchies, nested subcommands, and rich help/completion support without writing shell scripting or boilerplate themselves.
🌱Maturity & risk
Highly mature and production-ready. Cobra is trusted by major projects (Kubernetes, Hugo), has comprehensive test coverage across all major features (bash_completions_test.go, command_test.go, flag_groups_test.go), and maintains CI/CD via GitHub Actions (test.yml workflow). Actively maintained with well-established patterns and no major breaking changes in recent history.
Standard open source risks apply.
Active areas of work
Actively maintained with recent shell completion improvements (bash_completionsV2.go exists alongside bash_completions.go, suggesting version iteration), flag grouping enhancements (flag_groups.go with tests), and continued documentation work in site/content/. GitHub Actions CI runs on all commits. No major feature freeze visible.
🚀Get running
git clone https://github.com/spf13/cobra.git && cd cobra && go mod download && make test
Daily commands: make test runs the full test suite (Makefile present). For local development: go test ./... runs all tests. No dev server; this is a library, not an application.
🗺️Map of the codebase
command.go— Core Command struct and lifecycle methods (Execute, PreRun, etc.)—the foundation of all CLI command behavior.cobra.go— Package-level initialization and exported API entry points; every user starts here.args.go— Argument parsing and validation logic that determines how user input is processed.flag_groups.go— Flag grouping and mutual-exclusivity enforcement; critical for command-line interface correctness.completions.go— Shell completion infrastructure coordinator; enables the primary UX of modern CLIs.bash_completionsV2.go— Bash-specific completion implementation; widely used in production CLIs (Kubernetes, Hugo).
🧩Components & responsibilities
- Command (Go struct, interface{} for Run callback) — Represents a CLI command node; owns Use/Run/PreRun/PostRun, child commands, flags, and lifecycle hooks.
- Failure mode: Execute() returns error; caller must handle exit codes
- Argument Validator (Predefined validators in args.go; MatchAll chaining) — Enforces arg count rules (ArgsExact, ArgsAtLeast, ArgsRange, etc.) before Run.
- Failure mode: Returns error string; prevents Run execution
- Flag Parser (pflag.FlagSet, registered flags on *cobra.Command) — Delegates to spf13/pflag; handles boolean, string, int, slice flags with short/long names.
- Failure mode: Parsing error prevents Run; help text suggests correct usage
- Completion Engine (bash_completionsV2, zsh_completions, fish_completions, powershell_completions) — Generates shell-specific completion scripts; validates registered completions and invokes them when COMP_LINE or _COMPLETE env var is set.
- Failure mode: Invalid completion function panics or returns empty results; shell falls back to no suggestions
- Doc Generator (go-md2man, template rendering, file I/O) — Traverses command tree and emits Markdown, YAML, Man pages, or REST specs for offline documentation.
- Failure mode: I/O error or invalid template stops generation; no auto-recovery
🔀Data flow
User shell→Command.Execute()— Raw CLI args (os.Args[1:]) passed to command dispatcherCommand.Execute()→pflag.FlagSet.Parse()— Args split into flags and positional argumentspflag.FlagSet.Parse()→Argument Validator— Remaining positional args validated against ArgsExact/AtLeast/etc.Argument Validator→PreRun hook— If valid, hook is called with context and validated argsPreRun hook→Run callback— User code executes main command logic; can read flags via cmd.
🛠️How to make changes
Add a new root command with subcommands
- Create a new Command via cobra.Command{}; set Use, Short, Long, Run fields (
command.go) - Add child commands via rootCmd.AddCommand(subCmd) (
command.go) - Define PersistentFlags and Flags on the command instance (
command.go) - Call rootCmd.Execute() from main() to start the CLI (
cobra.go)
Add shell completion support to a command
- Register completion functions via cmd.RegisterFlagCompletionFunc(flagName, func) (
completions.go) - Implement ValidArgsFunction on the Command to suggest arguments (
command.go) - Test with bash_completionsV2.go or zsh_completions.go logic (
bash_completionsV2.go)
Enforce mutually-exclusive flags or flag groups
- Create a FlagGroup with NewFlagGroup() (
flag_groups.go) - Register flags to the group via flagGroup.RegisterFlagCompletionFunc() or direct assignment (
flag_groups.go) - Call cmd.MarkFlagsMutuallyExclusive(flag1, flag2, ...) in init or Run hook (
command.go) - Validation errors are returned from cmd.Execute() if mutual exclusivity is violated (
command.go)
Generate CLI documentation (Markdown or Man pages)
- Import doc package and call doc.GenMarkdownTree(cmd, outputDir) or doc.GenManTree(cmd, header, outputDir) (
doc/md_docs.go) - Optional: customize header info (Title, Section, Date) in GenManTree (
doc/man_docs.go) - Run once during build or CI to generate static docs (
Makefile)
🔧Why these technologies
- spf13/pflag — POSIX-compliant flag parsing with broader compatibility than stdlib flag; essential for modern CLI UX.
- cpuguy83/go-md2man — Converts Markdown command docs to man pages; enables single-source documentation for CLI and system help.
- yaml.v3 — Structured YAML output for machine-readable CLI specs; used by doc generators for tool integration.
⚖️Trade-offs already made
-
Single-threaded command execution model
- Why: Simplifies hook lifecycle, flag validation, and error handling; matches typical CLI usage patterns.
- Consequence: Concurrent subcommands or parallel execution must be implemented by user code; no built-in async support.
-
Separate completion implementations per shell (bash, zsh, fish, powershell)
- Why: Each shell has unique completion protocol; unified abstraction would lose shell-specific features.
- Consequence: Maintenance burden across multiple codebases; inconsistent behavior possible if not tested carefully.
-
Command tree immutability after Execute()
- Why: Prevents runtime modification bugs; enables safe parallel help/completion generation.
- Consequence: Dynamic command registration requires setup before Execute(); generated CLIs are static.
🚫Non-goals (don't propose these)
- Real-time command monitoring or structured logging—uses stdlib log only
- Authentication or authorization—delegates to user code
- Cross-platform terminal UI features (colors, boxes, tables)—integrates with external libraries
- Interactive prompts or REPL mode—single-shot command execution model only
🪤Traps & gotchas
No required environment variables or services. One subtle gotcha: flag.go does not exist in the file list—flags are attached directly to Command objects via pflag integration in command.go, not in a separate flag module, so looking for a 'flag' package may be confusing. Windows-specific behavior splits into command_win.go and command_notwin.go; behavior differs slightly on Windows (mousetrap for parent process detection). Completion tests assume shell availability on host; some tests may skip on unsupported shells.
🏗️Architecture
💡Concepts to learn
- POSIX-compliant flag parsing — Cobra's core value is handling POSIX conventions (short -h, long --help, flag stacking) correctly; understanding this standard is essential for designing good CLIs
- Recursive command composition — Cobra uses a tree of Command objects where each command can have subcommands; understanding recursion is key to designing nested CLI hierarchies like 'git remote add'
- Template-based code generation — Cobra auto-generates help text, man pages, and completions using Go's text/template; the template-based approach allows customization without code changes
- Shell completion protocols — Bash, zsh, fish, and PowerShell have different completion mechanisms (Bash uses sourced scripts, fish uses XML-style output); Cobra abstracts these differences, but understanding each protocol helps when debugging completion issues
- Flag inheritance and cascading — Cobra supports global flags (inherited by all subcommands), local flags (command-specific), and flag groups for organization; this cascading model is more complex than flat flag systems and requires careful understanding
- Active help (contextual suggestions) — Cobra's active_help.go provides dynamic suggestions ('did you mean?') at runtime; this is a sophisticated UX feature that requires understanding command context and edit distance algorithms
- Man page generation from commands — Cobra can auto-generate troff-formatted man pages (doc/man_docs.go) from command trees; understanding man page structure helps when documenting CLIs for Unix-like systems
🔗Related repos
spf13/pflag— The underlying POSIX flag parser Cobra wraps; understanding pflag is necessary to extend flag behaviorspf13/viper— Companion config management library; Cobra is explicitly designed for seamless integration with Viper for 12-factor appsurfave/cli— Alternative Go CLI framework with similar goals; useful for comparing design decisions and feature trade-offsgoogle/subcommands— Simpler Google-style subcommand library; good reference for minimal CLI patterns if Cobra feels over-engineeredcpuguy83/go-md2man— Dependency used by Cobra for man page generation; understanding this library is useful when customizing doc output
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive integration tests for flag_groups.go functionality
The flag_groups.go file (which manages mutually exclusive and required flag groups) has a corresponding test file, but based on the complexity of flag group interactions with command parsing, there are likely edge cases not covered. New contributors could add tests for: flag group conflicts with subcommands, flag group validation with custom validators, and flag group behavior with inherited flags. This directly improves reliability of a non-trivial feature.
- [ ] Review flag_groups.go and flag_groups_test.go to identify untested code paths
- [ ] Add test cases for flag group conflicts with subcommand execution
- [ ] Add test cases for flag group validation with inherited flags from parent commands
- [ ] Add test cases for error message clarity when flag group constraints are violated
- [ ] Run 'go test -cover' to verify new coverage and update test file
Expand shell completion tests for edge cases in all completion types
Cobra supports bash, zsh, fish, and powershell completions (bash_completions_test.go, zsh_completions_test.go, fish_completions_test.go, powershell_completions_test.go exist), but integration between active_help.go and shell completions lacks comprehensive test coverage. Contributors could add tests ensuring active help text is properly injected and escaped in all shell formats, particularly testing special characters, multiline descriptions, and completion directive combinations.
- [ ] Review active_help.go and active_help_test.go for feature scope
- [ ] Add tests in bash_completionsV2_test.go for active help injection with special characters
- [ ] Add tests in zsh_completions_test.go for active help rendering in zsh format
- [ ] Add tests in fish_completions_test.go and powershell_completions_test.go for consistency
- [ ] Test completion directives (CobraCompletionDirectiveError, etc.) work across all shells
Add missing documentation for dynamic completion and validation patterns in site/content/user_guide.md
The repository has robust completion support (completions.go, shell_completions.go, and multiple shell-specific files) and validation mechanisms (flag_groups.go), but the user guide likely doesn't document the recommended patterns for implementing ValidArgsFunction with external data sources, or how to properly structure custom completion logic. A PR adding specific examples and best practices would help users leverage these powerful features.
- [ ] Review completions.go to understand ValidArgsFunction and MatchAll/ShellCompDirective APIs
- [ ] Review flag_groups.go for constraint validation patterns
- [ ] Add new section 'Dynamic Completions' to site/content/user_guide.md with concrete examples
- [ ] Add new section 'Flag Validation & Groups' with examples from flag_groups_test.go
- [ ] Include example of combining ValidArgsFunction with active_help.go for rich completion UX
- [ ] Link to existing doc generation capabilities in site/content/docgen/ for completeness
🌿Good first issues
- Add comprehensive tests for the zsh completion backend: zsh_completions.go exists in structure but no zsh_completions_test.go is visible, unlike bash, fish, and powershell which have test files. Writing tests for zsh completion edge cases would be valuable.
- Document the difference between bash_completions.go and bash_completionsV2.go in site/content/completions: the codebase has both versions but no clear guidance on when to use each. A short migration guide in the docs would help users.
- Add integration tests for flag_groups.go with nested commands: flag_groups_test.go exists but likely doesn't cover deeply nested command hierarchies with flag inheritance; add examples to site/content/ showing this feature.
⭐Top contributors
Click to expand
Top contributors
- @marckhouzam — 11 commits
- @nirs — 10 commits
- @scop — 9 commits
- @dependabot[bot] — 8 commits
- @jpmcb — 5 commits
📝Recent commits
Click to expand
Recent commits
ad460ea— Add cobra unique args validator (#2397) (takanuva15)746ef07— fix: prevent completions from mutating os.Args via append side effect (#2356) (veeceey)f2878ba— Ignore the linter error (#2390) (marckhouzam)85c12c2— projects_using_cobra: add Ollama (#2389) (ArturAronov)61968e8— fix: quote args in fish shell completion (#2285) (n9v9)10d4b48— perf: Loop over the bash variable directly instead of starting subprocesses. (#2333) (JeffFaer)88b30ab— chore: Migrate from gopkg.in/yaml.v3 to go.yaml.in/yaml/v3 (#2336) (dims)346d408— fix: actions/setup-go v6 (#2337) (jpmcb)fc81d20— refactor: change minUsagePadding from var to const (#2325) (ssam18)117698a— refactor: replace several vars with consts (#2328) (htoyoda18)
🔒Security observations
The Cobra repository demonstrates a reasonable security posture with a documented vulnerability reporting policy (SECURITY.md) and GitHub workflows for testing. However, critical weaknesses exist: the Go version requirement is severely outdated (1.15 vs. current standards), and there's a suspicious YAML dependency using a non-standard domain that requires verification. The project would benefit from updating Go version requirements, verifying all dependencies use canonical sources, and implementing automated security scanning. No obvious injection vulnerabilities, hardcoded secrets, or exposed infrastructure issues were identified in the provided file structure.
- Medium · Outdated Go Version Requirement —
go.mod. The project specifies 'go 1.15' in go.mod, which is significantly outdated. Go 1.15 reached end-of-life in December 2020 and no longer receives security updates. This exposes the project and its users to known security vulnerabilities in the Go runtime. Fix: Update the minimum Go version to at least 1.21 or the latest stable release. Run 'go mod tidy' and test thoroughly with the new version. - Medium · Potentially Outdated YAML Dependency —
go.mod - github.com/spf13/cobra require section. The dependency 'go.yaml.in/yaml/v3 v3.0.4' uses an unusual domain 'go.yaml.in' instead of the canonical 'gopkg.in'. Additionally, v3.0.4 appears to be an older version. The canonical YAML v3 library is at 'gopkg.in/yaml.v3'. This may indicate a typo or use of an unofficial/unmaintained fork. Fix: Verify the correct import path and update to the official YAML library: 'gopkg.in/yaml.v3'. Ensure no typosquatting or supply chain attacks. Run 'go get -u gopkg.in/yaml.v3' and update all imports. - Low · Dependency on Mousetrap Without Clear Purpose —
go.mod. The dependency 'github.com/inconshreveable/mousetrap v1.1.0' is included but its purpose is not immediately clear from the codebase structure provided. Mousetrap is used for Windows CLI interactions, but undocumented dependencies increase maintenance burden and potential supply chain risk. Fix: Document why each dependency is required. Verify mousetrap is actively maintained. Consider if it's truly necessary or if functionality can be achieved with stdlib. - Low · Missing SBOM and Dependency Audit Documentation —
Repository root - missing security automation. While a SECURITY.md file exists with vulnerability reporting procedures, there is no evidence of automated dependency scanning, SBOM generation, or regular security audits. This is a best practice for a widely-used library. Fix: Add automated dependency scanning via Dependabot (partially configured in .github/dependabot.yml), implement SBOM generation, and document the security update process. Use 'go audit' or similar tools in CI/CD.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.