go generate: Usage, Options & Common CI Errors
Run the code generators embedded in your source.
go generate scans for //go:generate directives and runs the commands they specify. It is never run automatically by build or test - you invoke it explicitly and commit the generated files.
What it does
Finds //go:generate lines in the named packages and executes each command (e.g. stringer, mockgen, protoc). It does no dependency analysis and never re-runs on its own; you decide when to run it.
Common usage
go generate ./... # run all generators
go generate -run stringer ./... # only directives matching a regex
go generate -x ./... # print the commands as they runCommon CI error: generated code is stale
A build uses out-of-date generated files because someone changed the source but did not re-run go generate. Gate it in CI: run go generate ./... then git diff --exit-code, which fails when the committed generated output no longer matches. The generator binaries (stringer, mockgen) must be installed on the runner first.
Options
| Flag | Effect |
|---|---|
| -run <regex> | Run matching directives only |
| -x | Print executed commands |
| -n | Dry run, print without executing |