Skip to content

project rulesWorkflowgo

Go CLI Rules

Project rules for Go command line tools: cobra command layout, config precedence, wrapped errors, exit codes and table-driven tests.

npx workspacetemplates add go-cli-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file19 lines · 1.3 KBFile
# Project rules: Go CLI

## Layout
- `cmd/<tool>/main.go` only builds the root command and exits. Commands live in `internal/cli`, one file per subcommand; logic lives in `internal/<domain>` packages that know nothing about cobra.
- Avoid `init()` and package-level mutable state. Build commands with constructors that take their dependencies.

## Config and I/O
- Precedence: flags, then environment variables, then config file, then defaults. Document it in `--help`.
- Write results to `cmd.OutOrStdout()` and diagnostics to `cmd.ErrOrStderr()`, so tests can capture both. Offer `--json`.
- Use `RunE` and return errors; never call `os.Exit` or `log.Fatal` inside a command.

## Errors and exit codes
- Wrap with `fmt.Errorf("load config: %w", err)`; compare with `errors.Is` and `errors.As`. Error strings are lowercase with no trailing punctuation.
- `main` maps errors to codes: `0` success, `1` failure, `2` usage. Set `SilenceUsage` after argument validation.
- Pass `context.Context` first, and cancel it on SIGINT with `signal.NotifyContext`.

## Quality
- Write table-driven tests with `t.Run`, `t.TempDir()` and `t.Parallel()` where safe. Execute commands with `SetArgs` and a buffer.
- Run `gofmt -l .`, `go vet ./...`, `golangci-lint run` and `go test -race ./...` before finishing.

What it does

These rules describe a Go command line tool with commands kept apart from the logic they call. An agent following them produces packages that are small, testable and easy to extend with new subcommands.

They also pin down configuration order, error wrapping and exit behavior, which are the details that make a tool pleasant in scripts.

Example

you › Add a delete subcommand with a --force flag

agent › The agent adds a cobra command in internal/cli that calls a domain function, asks for confirmation unless forced, and covers both paths in a table-driven test.

Questions

Is cobra required?
The layout rules assume cobra. With the standard flag package, keep the same split between commands and logic.
Why avoid log.Fatal?
It exits without running defers and cannot be tested; returning errors lets main decide.
  • Python CLI Rules

    Project rulespython

    Free
  • Rust CLI Rules

    Project rulesrust

    Free
  • Bug Report Triage

    SkillWorkflow

    Free
  • Codebase Onboarding

    SkillWorkflow

    Free