# Add a --dry-run Flag to a Cobra CLI

Yes. An agent adds a persistent --dry-run flag to your Cobra CLI that prints every file and command a subcommand would run, keeps the golden tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-dry-run-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 what each command writes before it adds a flag that promises not to. In a CLI like spf13/cobra-cli, `go.mod` is on `go 1.15` with `github.com/spf13/cobra v1.6.1` and `github.com/spf13/viper v1.12.0`. `cmd/root.go` defines the persistent flags `--config`, `--author`, `--license` and `--viper`, binds `author` and `useViper` to Viper, and reads `$HOME/.cobra.yaml` in `initConfig`. `cmd/init.go` calls `initializeProject`, which builds a `Project` from `go list -json -m` and calls `project.Create()`, then runs `go get github.com/spf13/cobra` through `exec.Command` and, when `useViper` is set, `go get github.com/spf13/viper`, and prints `Your Cobra application is ready at` with `fmt.Printf`. `cmd/add.go` builds a `Command` and calls `command.Create()`, printing `<name> created at <path>`. `cmd/project.go` does the writing: `Project.Create` makes the directory with `os.Mkdir`, creates `main.go`, `cmd/root.go` and `LICENSE` with `os.Create` and executes the templates from `tpl/main.go` straight into the files; `Command.Create` writes `cmd/<name>.go` the same way, and all four paths are built with `fmt.Sprintf("%s/cmd/%s.go", …)` rather than `filepath.Join`.

The flag goes on the root as `rootCmd.PersistentFlags().Bool("dry-run", false, …)` so `init` and `add` both take it, and it is read with `cmd.Flags().GetBool` rather than bound to Viper, because a setting in `.cobra.yaml` should not silently turn a real `init` into a rehearsal. `Project` and `Command` gain a `DryRun bool` and an `io.Writer`, and `Create` is split so the template is executed into a `bytes.Buffer` first; in dry-run mode the buffer is discarded and one line per file is written to the writer, prefixed `would write` or `would overwrite` after an `os.Stat`, and the `os.Mkdir` and `os.Create` calls are skipped. `init` prints `would run go get github.com/spf13/cobra` instead of calling `goGet`, with the Viper line when `--viper` is set, and the closing `Your Cobra application is ready at` is replaced by a count of files. Rendering the template even in dry-run mode means a bad template still fails loudly, which the description points out.

Output goes through `cmd.OutOrStdout()` instead of `fmt.Printf`. That matters here because `cmd/golden_test.go` calls `SetOut` and `SetErr` with buffers on `addCmd` and `initCmd` to mute the commands under test, and the existing `fmt.Printf` lines bypass those buffers; the new lines respect them, so dry-run output in tests can be asserted and the real commands stay quiet. Paths in the output keep the `%s/cmd/%s.go` form the code uses, so the lines match on the MINGW64 job in `.github/workflows/test.yml` as well as on the Ubuntu and macOS matrix from Go 1.14 to 1.17.

Tests sit beside the golden ones: `TestDryRunInit` runs `initializeProject` with `DryRun` set in a temporary directory, asserts that `main.go`, `cmd/root.go` and `LICENSE` do not exist afterwards and that the buffer lists those three paths and the `go get` line; `TestDryRunAdd` does the same for `cmd/<name>.go`, and a third case runs `add` against a directory that already has that file and expects `would overwrite`. `TestGoldenInitCmd` and `TestGoldenAddCmd` are untouched, because the non-dry-run path still writes the same bytes through the buffer. The agent runs `make fmt`, `go test ./...` and `golangci-lint run` with the repository's `.golangci.yml`, which enables `errcheck`, `goimports`, `golint`, `govet` and others, and keeps the output; the `README.md` usage section gains the flag.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a --dry-run flag to this Cobra CLI. Read go.mod, main.go, cmd/root.go, cmd/init.go, cmd/add.go, cmd/project.go, cmd/helpers.go, cmd/golden_test.go, cmd/init_test.go, cmd/add_test.go, tpl/main.go, the Makefile, .golangci.yml and the CI workflow first. Add dry-run as a persistent bool flag on the root command, not bound to Viper, and say why in the PR. Give Project and Command a DryRun field and a writer; render each template into a buffer first, and in dry-run mode skip every Mkdir and Create and print one would write or would overwrite line per file, checking with os.Stat. In init, print the go get commands instead of running them. Send all new output through cmd.OutOrStdout so the SetOut buffers in golden_test.go capture it, and keep the existing path format so the Windows job matches. Add tests for dry-run init, dry-run add and the overwrite case that assert no files were created, and leave the golden tests unchanged. Run make fmt, go test ./... and golangci-lint with the repository config, include the output, document the flag in the README, and open a pull request.",
  "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 changes `cmd/root.go`, `cmd/init.go`, `cmd/add.go`, `cmd/project.go` and `README.md`, and adds `cmd/dryrun_test.go`. `tpl/main.go`, the golden files under `cmd/testdata/` and `go.mod` are unchanged.

The description explains the Viper decision, the buffer-first rendering, and the switch to `cmd.OutOrStdout`, and quotes the `go test` and `golangci-lint` output. The commands and their full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer runs `cobra-cli init --dry-run` in an empty module and `cobra-cli add serve --dry-run` in an existing project and reads the lines. A follow-up message to the same session can add a `--verbose` that prints the rendered contents under each path, or extend the flag to a command the reader's own CLI has.

## Run it on every CLI subcommand that writes files or shells out

A team with several Go CLIs sends one `POST /o/{org}/sessions` per repository with this prompt as `input` and the repository in `resources`. Each run reads its own commands, so a CLI whose writes go through `os.WriteFile` or `exec.Command` in a different package gets the flag threaded to those call sites, and one that already uses `cmd.OutOrStdout` keeps its output convention.

Send a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with `session_url` for the pull request link and the test output.

## Why run it on Rush?

A dry-run flag is only as honest as the code paths it covers: one forgotten `os.Create`, one `go get` that still runs, and the flag lies. The agent reads every write and every `exec.Command` in the command tree, routes them through one switch, and proves with tests that a dry run leaves an empty directory empty, in a sandbox of its own, with the output kept.

The pull request carries the flag, the tests and the lint output, and keeps the golden tests untouched, so a reviewer sees the change to behaviour without a change to what the CLI generates. Several CLIs can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why a persistent flag on the root rather than one per command?

Both `init` and `add` write files, and a future command will too. One persistent flag means `--dry-run` works on every subcommand with one definition, and the `Project` and `Command` types carry the setting to the code that writes.

### Does --dry-run still read my .cobra.yaml?

Yes, the config file still supplies `author` and `license` so the dry run shows what a real run would generate. The flag itself is deliberately not bound to Viper, so a config key cannot switch it on without the flag on the command line.

### Will the golden tests change?

No. The real path renders the same templates into the same files; only the destination of the rendered bytes changes from a file to a buffer and back. `TestGoldenInitCmd` and `TestGoldenAddCmd` compare the same `testdata` files as before.

### Does a dry run show the file contents?

It prints one line per file with the path and whether it would be written or overwritten, plus the `go get` commands. Contents are rendered but not printed; ask for a `--verbose` and the agent adds the rendered text under each path.

### Why route output through cmd.OutOrStdout?

The golden tests silence the commands with `SetOut` and `SetErr` buffers, and `fmt.Printf` ignores those. Writing through the command's writer keeps the tests quiet, lets the new tests assert the output, and is the Cobra convention.

## More Cobra jobs

- [Add GoReleaser to a Cobra CLI](https://getrush.ai/run/add-goreleaser/cobra/)
- [Add govulncheck to a Cobra CLI's CI](https://getrush.ai/run/add-govulncheck-to-ci/cobra/)
- [Add a JSON Output Flag to a Cobra CLI](https://getrush.ai/run/add-json-output-flag/cobra/)

## The same job on other stacks

- [Add a --dry-run Flag to a Click CLI](https://getrush.ai/run/add-dry-run-flag/click/)

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

- [Convert Airflow DAG Loops to Dynamic Task Mapping](https://getrush.ai/run/add-dynamic-task-mapping/airflow/)
- [Turn On DynamoDB Point-in-Time Recovery in a Serverless Framework Service](https://getrush.ai/run/add-dynamodb-point-in-time-recovery/serverless/)

## 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/)
