CodeMD repository analysis · example report

spf13/cobra

An analysis of github.com/spf13/cobra as it was on 2026-11-13.

62files analyzed
12features
251quality signals
0security findings

Overview

What the repository is and how it is built, written by AI from the analysis.

Cobra

Summary

Cobra is a Go library for creating powerful, modern command-line applications in the style of the git and go tools. It is built around a simple structure of commands, arguments and flags, so that applications read like sentences: APPNAME COMMAND ARG --FLAG, for example hugo server --port=1313. Cobra is used in many Go projects, including Kubernetes, Hugo and GitHub CLI. It is released under the Apache 2.0 license.

Key features

  • Subcommand-based CLIs: build tools with commands such as app server and app fetch, including nested subcommands for organizing complex applications.
  • POSIX-compliant flags: short and long versions, provided by the pflag library, with support for the Go flag package as well.
  • Flexible flag scope: global, local and cascading flags that persist through to child commands.
  • Intelligent suggestions: a mistyped app srver prompts "did you mean app server?"
  • Automatic help: help and usage are generated for commands and flags, and -h and --help are recognized automatically. Subcommands can be grouped in help output.
  • Shell autocompletion: generated completion scripts for bash, zsh, fish and powershell.
  • Man pages: generated automatically for your application.
  • Command aliases: change command names without breaking existing usage.
  • Customization: define your own help, usage and related output.
  • Viper integration: optional, for 12-factor applications.

Typical use cases

  • Building multi-command developer tools and infrastructure CLIs that follow the git or go model.
  • Organizing a large tool into a hierarchy of nested subcommands.
  • Shipping a polished user experience with shell completion, man pages and helpful error suggestions without writing that machinery by hand.
  • Evolving a CLI over time by adding aliases, so renamed commands keep working.
  • Creating applications whose configuration follows 12-factor practices, using viper.
  • Bootstrapping a new application quickly with cobra-cli, a companion program that generates application scaffolding and command files.

Architecture

Cobra is organized around three concepts:

  • Commands represent actions. A command is the central point of the application: each interaction the application supports is contained in a cobra.Command. A command can have child commands and can optionally run an action.
  • Args are the things the action operates on.
  • Flags are modifiers that change a command's behavior. Flags can persist through to child commands or be available only to the command that defines them. Flag handling is built on pflag, a fork of the standard library's flag package that keeps the same interface while adding POSIX compliance.

Applications define a tree of commands, and Cobra handles parsing, routing, help, suggestions and completion across that tree. Documentation for the library is available at cobra.dev and in the Cobra User Guide.

Features

12 features found in the code and documentation.

Subcommand-based CLIs

Lets you build git- or go-style command-line apps with commands like `app server` and `app fetch`.

Nested subcommands

Lets commands have child commands so you can organize complex tools into a hierarchy.

POSIX-compliant flags

Supports short and long flags that follow POSIX conventions, powered by the pflag library.

Global, local, and cascading flags

Lets you define flags that apply to one command or persist through to all its child commands.

Intelligent command suggestions

Suggests the closest matching command when users mistype one, such as offering `app server` for `app srver`.

Automatic help generation

Generates help and usage output for commands and flags, and recognizes `-h` and `--help` automatically.

Grouped subcommand help

Lets you organize subcommands into groups in the help output for easier reading.

Shell autocompletion

Automatically generates completion scripts for your app in bash, zsh, fish, and powershell.

Generated man pages

Automatically produces man pages for your application.

Command aliases

Lets you rename or add alternative names for commands without breaking existing usage.

Customizable help and usage

Gives you the flexibility to define your own help and usage output.

Viper integration

Optionally integrates with viper so apps can follow 12-factor configuration practices.

Static quality signals

Possible problems found without running the code.

251signals found
12high severity
12confirmed by the analysis
239need a human to check
KindSignalWhereSeverity
StructureDuplicate parsed function symbol
`bash_completions.nonCompletableFlag` is defined 3 times in `bash_completions.go`.
bash_completions.go:567high
StructureDuplicate parsed function symbol
`command.func` is defined 5 times in `command.go`.
command.go:491high
StructureDuplicate parsed function symbol
`command.commandNameMatches` is defined 2 times in `command.go`.
command.go:801high
StructureDuplicate parsed function symbol
`command_test.ExactArgs` is defined 7 times in `command_test.go`.
command_test.go:92high
StructureDuplicate parsed function symbol
`command_test.func` is defined 30 times in `command_test.go`.
command_test.go:1008high
StructureDuplicate parsed function symbol
`completions.len` is defined 2 times in `completions.go`.
completions.go:478high
StructureDuplicate parsed function symbol
`completions_test.func` is defined 10 times in `completions_test.go`.
completions_test.go:852high
StructureDuplicate parsed function symbol
`man_docs_test.func` is defined 2 times in `doc/man_docs_test.go`.
doc/man_docs_test.go:79high
Across filesMissing internal call target
`cobra.WriteStringAndCheck` calls `cobra.CheckErr`, but the target was not found in the parsed function index.
cobra.go:243high

A sample of the highest-ranked signals. These come from static analysis: they are leads to review, not confirmed bugs.

Unused functions

Functions nothing in the repository calls.

No unused functions were found.

Recent changes

What changed in the last 30 days, in plain language.

Cobra daily change summary (last 30 days, 10 commits, 10 authors; the final commit's data is truncated)

New feature

  • NoDuplicateArgs validator (ad460ea, takanuva15, 2026-04-25). Adds a new built-in positional-args validator in args.go. It returns duplicate argument "X" for "<command path>" when any argument value appears more than once. It works alone or combined with others via MatchAll(OnlyValidArgs, NoDuplicateArgs). Four new tests in args_test.go cover the success case, the duplicate case, the duplicate case with ValidArgs set, and the combined case. site/content/user_guide.md now lists it among the built-in validators. This is the highest-impact change in the window (impact score 77).

Bug fixes

  • Completion no longer mutates os.Args (746ef07, Varun Chawla, 2026-04-24). In getCompletions (completions.go), trimmedArgs was a sub-slice of the caller's args. A later append(finalArgs, "--") could write into the shared backing array and overwrite os.Args when TraverseChildren was on. The fix copies the slice with make and copy. The new regression test TestCompletionDoesNotMutateOsArgs refers to issue #2257 and checks that os.Args stays ["root", "__completeNoDesc", "x"].
  • Fish completion quoting (61968e8, Niklas Vogel, 2025-12-10). In fish_completions.go, the earlier args passed to the program are now escaped with string escape and joined with string join. Previously they were interpolated raw, so spaces or wildcards in args could break completion. The comment on the last arg now mentions wildcards too.

Performance

  • Bash completion V2 loop (10d4b48, Jeffrey Faer, 2025-12-06). In bash_completionsV2.go, the loop over completions now iterates "${completions[@]}" directly with for. It replaces while read ... < <(printf ...), which started a subprocess. This should make bash completion faster.

Maintenance and dependencies

  • YAML library migration (88b30ab, Davanum Srinivas, 2025-12-03). Replaces gopkg.in/yaml.v3 v3.0.1 with go.yaml.in/yaml/v3 v3.0.4 in doc/yaml_docs.go, go.mod and go.sum.
  • CI action bump (346d408, John McBride, 2025-12-03). actions/setup-go goes from v5 to v6 in two places in .github/workflows/test.yml.
  • minUsagePadding is now a constant (fc81d20, SamareshSingh, 2025-11-18). Changed from var to const in command.go, so it can no longer be modified at runtime.
  • Linter suppression (f2878ba, Marc Khouzam, 2026-04-15). Adds a //nolint:gosec comment in CompDebug in completions.go. It records that BASH_COMP_DEBUG_FILE is intentionally user-controlled. There is no behavior change.
  • macOS test link failure and lint rules (adbc881, Shudhanshu Singh, 2026-07-11). The title says it fixes a macOS test link failure and updates lint rules. It touches 3 files, including 5 added lines in .github/workflows/test.yml. The rest of the diff was cut off, so I can't give more detail.

Docs

  • Projects list (85c12c2, Artur Aronov, 2026-04-15). Adds Ollama to site/content/projects_using_cobra.md.

Overall

  • The user-facing changes are the new NoDuplicateArgs validator and three completion fixes, covering shell quoting, performance and os.Args safety. The rest is dependency, CI and lint upkeep. The static analysis reports no impacted callers for any changed function.

Ask about this repository

An example question, answered from the code.

What does this project do and how is it organised?

Question Summary

The user asks what this project does and how it is organised.

Direct Answer

  • [MARKUP] The project is Cobra, a Go library. README.md:14 says "This list contains a more extensive list of projects using Cobra" and links site/content/projects_using_cobra.md. CONDUCT.md:4 describes Cobra's release cadence and Semantic Versioning. [UNKNOWN] The evidence contains no README passage stating Cobra's purpose, so this is indirect.
  • [MARKUP] From the code, it builds command-line programs from Command objects. The test in completions_test.go:4076-4129 (TestCompletionDoesNotMutateOsArgs) creates a Command with Use, TraverseChildren, ValidArgsFunction and Run, sets output with SetOut/SetErr, and runs it with ExecuteC. [GRAPH] Its callees are Command.ExecuteC, Command.SetErr and Command.SetOut. TestValidArgsFuncCmdContext (completions_test.go:1276-1316) uses rootCmd.AddCommand(childCmd), so commands can have subcommands.
  • [MARKUP] A large visible part is shell completion. completions_test.go tests ShellCompNoDescRequestCmd, ShellCompDirective values and the default completion command (TestInitDefaultCompletionCmd, completions_test.go:3930-4017). The test at completions_test.go:4076-4129 guards against a bug in getCompletions() where append(finalArgs, "--") could write into the backing array of os.Args.
  • [UNKNOWN] The evidence does not show the full file layout, architecture documentation, or most non-test source files, so the organisation below is partial.

Organisation visible in the evidence

Go source and tests at the top level (package cobra)

  • [MARKUP] Test files sit at the top level: completions_test.go, command_test.go and bash_completionsV2_test.go. Source files include completions.go.
  • [GRAPH] Callgraph nodes are all named cobra.*, which indicates one shared package.

Completion logic (completions.go)

  • [GRAPH] Command.getCompletions calls checkIfFlagCompletion (completions.go:657-1024). That function calls Command.Name, findFlag and isFlagArg.
  • [GRAPH] isFlagArg (completions.go:696-782) is called by Command.Traverse and checkIfFlagCompletion.
  • [GRAPH] MinimumNArgs (completions.go:235-1024) is called by Command.initCompleteCmd and by many tests. This is [SEMANTIC] retrieval only, so treat it as a candidate. The line range overlaps other symbols, and I can't tell from the evidence why.

Test helpers (command_test.go)

  • [GRAPH] executeCommandWithContext (command_test.go:37-46) calls SetOut, SetErr, SetArgs and ExecuteContext. TestExecuteContext and TestHelpFuncExecuted call it.
  • [GRAPH] executeCommandWithContextC (command_test.go:59-68) calls ExecuteContextC after the same setup. TestExecuteContextC and TestValidArgsFuncCmdContext call it.
  • [SEMANTIC] TestHelpCommandExecutedWithoutVersionSet (command_test.go:2751-2763) calls AddCommand, checkStringContains, checkStringOmits and executeCommand.

Project docs and site

  • [MARKUP] README.md, CONDUCT.md (release policy, with exceptions for breaking changes in release branches at line 30) and CONTRIBUTING.md.
  • [MARKUP] site/content/projects_using_cobra.md is a list of projects that use Cobra.

Stored summaries

  • Two stored summaries mention other files, such as fish_completions.go, args_test.go and command.go. They are derived, not source truth. The snippets, callgraph and source-text matches supplied here do not show those files directly, so I have not relied on them.

Security review

An AI review of how outside input reaches risky operations.

No exploitable findings.

This repository is spf13/cobra, a Go library that applications use to build command-line tools. It has no network listener, no AI agent or tool invocation, and no credential handling. In the shipped (non-test) code, nothing runs a process or shell: every exec.Command call is in a test file (cobra_test.go and bash_completions_test.go). The file-writing sinks are GenBashCompletionFile(V2), GenFishCompletionFile, genZshCompletionFile, genPowerShellCompletionFile and the doc.Gen*Tree functions. Each one writes to a filename or directory chosen by the application developer, and the doc tree file names come from command names the developer defined, not from runtime input. In completions.go:960, CompDebug appends to a file named by the BASH_COMP_DEBUG_FILE environment variable. Anyone who can set that variable already controls the user's environment, so this crosses no trust boundary. The other environment variable reads (active help config, completion config, SOURCE_DATE_EPOCH) only change output formatting. The generated shell completion scripts embed the program and command names, but the developer writes those at build time, so they are not attacker-controlled. I found no path from untrusted input to code execution, arbitrary file write, or secret exfiltration.