# Add a --version Flag to a Cobra CLI

Yes. An agent sets Version on your Cobra root command from the module's build info with an ldflags override, adds a version template and a test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-version-flag/cobra/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the root command before adding a flag, because Cobra adds `--version` itself once `Version` is set, and the work is in where the value comes from. In a tool like spf13/cobra-cli, `go.mod` names `github.com/spf13/cobra` 1.6.1 and `viper` 1.12 on a `go 1.15` directive, `main.go` calls `cmd.Execute()`, and `cmd/root.go` builds `rootCmd` with `Use` `cobra-cli`, persistent flags `--config`, `--author`, `--license` and `--viper`, and `cobra.OnInitialize(initConfig)` for the Viper config file. There is no `Version` field, so `cobra-cli --version` answers `unknown flag: --version`. Tests already exist for `add`, `init`, the helpers and the project templates, with golden files under `cmd/testdata/`. `Makefile` builds with `gox` and tests with `richgo`, and `.github/workflows/test.yml` runs that on Go 1.14 through 1.17 on Ubuntu and macOS, under MSYS2 on Windows, plus golangci-lint. `README.md` tells users to install with `go install github.com/spf13/cobra-cli@latest`.

That install path decides the design. A binary built with `go install module@version` carries the module version in `runtime/debug.BuildInfo`'s `Main.Version`, while a `go build` in a checkout reports `(devel)`. The agent adds `cmd/version.go` with a package variable `version` that `-ldflags "-X github.com/spf13/cobra-cli/cmd.version=..."` can set at build time, and a `resolveVersion()` that prefers the variable, falls back to `Main.Version` from `debug.ReadBuildInfo()`, and prints `devel` when neither says anything. It reads only `Main.Version`, not the `Settings` list with VCS data, because that field appeared in Go 1.18 and the workflow still tests 1.14.

In `root.go` the agent sets `rootCmd.Version = resolveVersion()` in `init`, which makes Cobra register `--version` and, since no other flag uses it, the `-v` shorthand, with the output `cobra-cli version <value>`. It sets `SetVersionTemplate` to add the Go version from `runtime.Version()` on the same line, which is what people paste into bug reports, and adds `-ldflags` to the `gox` call in `Makefile` so a release build stamps the tag. A `cmd/version_test.go` executes `rootCmd` with `--version` against a buffer and asserts the `cobra-cli version ` prefix and a non-empty value, in the style of the existing command tests.

The agent runs `go build ./...`, `go vet ./...`, `gofmt -l`, and `go test ./...` with the Go toolchain in the sandbox, builds the binary with and without the ldflags to show both outputs, and runs `cobra-cli --version` and `cobra-cli -v` on each. It notes in the pull request that `.golangci.yml` enables linters that recent golangci-lint versions have dropped, which is independent of this change and left alone.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a --version flag to this Cobra CLI. Read go.mod, main.go, cmd/root.go, cmd/init.go, cmd/helpers.go, cmd/helpers_test.go, Makefile, .github/workflows/test.yml and README.md first. Add cmd/version.go with a package-level version variable settable through -ldflags -X, and a resolveVersion function that uses that variable, else Main.Version from runtime/debug.ReadBuildInfo, else devel; read only Main.Version so the Go 1.14 jobs in the workflow still compile. Set rootCmd.Version from it in init so Cobra adds --version and the -v shorthand, and set a version template that also prints runtime.Version(). Add -ldflags to the gox build in the Makefile. Write cmd/version_test.go that executes the root command with --version against a buffer and asserts the output prefix and a non-empty value. Run go build ./..., go vet ./..., gofmt -l and go test ./..., build the binary with and without the ldflags and run --version on both, and open a pull request that shows both outputs and explains the resolution order.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `cmd/version.go` and `cmd/version_test.go`, changes `cmd/root.go` to set `Version` and the template, and adds `-ldflags` to the `Makefile`. The description shows the output of `--version` from a plain `go build` and from a build with the ldflags set, explains the three-step resolution order, and says why `Settings` is not read.

The run's record keeps the build, vet, gofmt and test output and the two binary invocations, so a reviewer sees that the existing golden-file tests still pass and what the flag prints in each case.

Before merging, a reviewer decides whether release builds come from `go install module@tag`, where `Main.Version` is enough, or from a release pipeline, where the ldflags path should be wired into it, and whether `-v` should be reserved for a future verbose flag.

## Run it on every new CLI repository

A team with several Cobra tools can run this once per repository from its own server: one `POST /o/{org}/sessions` per repository, each with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than a second pull request.

After that, the last step of the release workflow calls an automation's `webhook` trigger with an `Authorization` header of `Bearer <its secret>` and an `Idempotency-Key` header that is a UUID v5 of the tag, so a redelivery starts nothing new, and sends the tag name as the payload. The automation's prompt "build the binary at this tag with the Makefile's ldflags, run --version, and comment on the release if the output does not match the tag" catches a release that forgot to stamp; the payload becomes the event text after the prompt.

## Why run it on Rush?

The flag is one field; the value is the part that is wrong in practice, printing `(devel)` from a release binary or failing to compile on the oldest Go the workflow tests. The agent builds and runs the binary both ways in a sandbox, with and without ldflags, and checks the oldest toolchain the matrix names, so the pull request shows what users will see rather than what the code intends.

Every build and invocation stays with the run, so the pull request can paste the two outputs and the passing suite, including the golden-file tests that would catch a template change leaking into generated projects.

## Frequently asked questions

### Why not just hard-code a version string?

Because it goes stale on the first release. With `go install module@v1.2.3` the Go toolchain already records the version in the binary, and `Main.Version` reads it; the ldflags variable covers builds that bypass modules, such as a release pipeline, and `devel` is the honest answer for a local build.

### Will -v conflict with a verbose flag later?

Cobra gives `--version` the `-v` shorthand only if no other flag uses it. The root command's flags today are `--config`, `--author`, `--license` and `--viper`, so `-v` is free. If you plan a verbose flag, say so and the agent defines a `-v` flag first so Cobra skips the shorthand.

### Why doesn't it print the git commit?

The commit lives in `BuildInfo.Settings` under `vcs.revision`, a field that exists from Go 1.18. The workflow tests back to Go 1.14, so reading it would break those jobs. The pull request shows the two-line change to add it once the matrix moves.

### Does it touch the generated project templates?

No. The flag is on `cobra-cli` itself, not on the `tpl/` templates that `init` and `add` write into users' projects, and the golden-file tests confirm the templates are byte-identical after the change.

## More Cobra jobs

- [Migrate a Cobra CLI to golangci-lint v2](https://getrush.ai/run/migrate-golangci-lint-v2/cobra/)
- [Update the GitHub Actions in a Cobra CLI's Workflow](https://getrush.ai/run/update-github-actions/cobra/)
- [Upgrade Go Modules Weekly for a Cobra CLI](https://getrush.ai/run/upgrade-go-modules/cobra/)

## More jobs like this: Hand off a long task

- [Add Versioned Docs to a Docusaurus Site](https://getrush.ai/run/add-versioned-docs/docusaurus/)
- [Add a Version Menu to a Hugo Docsy Site](https://getrush.ai/run/add-versioned-docs/hugo/)
- [Add Versioned Documentation to an MkDocs Site With mike](https://getrush.ai/run/add-versioned-docs/mkdocs/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
