gitmyhub

cobra

Go ★ 44k updated 1mo ago

A Commander for modern Go CLI interactions

Cobra is a Go library that makes building command-line apps with subcommands, flags, and auto-generated help easy, used by Kubernetes, Hugo, and the GitHub CLI.

Gosetup: easycomplexity 2/5

Cobra is a Go library for building structured command-line applications with subcommands, flags, and automatic help generation. The problem it solves is that building a CLI tool in Go from scratch requires a lot of boilerplate: parsing arguments, routing to the right function based on subcommand names, handling flags in a POSIX-compliant way, generating usage text, and supporting shell autocompletion. Cobra packages all of that into a simple, organized framework.

In Cobra, you build your CLI by defining Command objects. Each command has a name, a description, an optional list of flags (configuration options like --port or -v), and a run function that executes when the command is invoked. Commands can have child commands, creating a tree that reads naturally: kubectl get pods, git commit --message "fix bug", or hugo server --port 1313. Cobra's pattern encourages CLIs that read like sentences.

Once you define your command tree, Cobra automatically generates help text that is displayed when users run --help or invoke an unknown command. It also generates shell autocompletion scripts for bash, zsh, fish, and PowerShell, so users can tab-complete your subcommands and flags. If a user makes a typo — typing app srver instead of app server — Cobra suggests the correct command. Man page generation is built in as well.

Cobra integrates with a companion library called Viper for configuration file management, allowing environment variables, config files, and command-line flags to be merged automatically — useful for twelve-factor app patterns.

You would use Cobra any time you're building a Go command-line tool beyond a simple single-command program. It is used by some of the most prominent Go projects in existence — Kubernetes (kubectl), Hugo, and the official GitHub CLI (gh) all rely on it. It is installed as a Go module and licensed under Apache 2.0.

Where it fits