go generate: Run Code Generators in CI
go generate scans for //go:generate directives in your source and runs the commands they specify, typically to regenerate mocks, protobufs, or stringer code.
go generate does not run during build; you invoke it explicitly. In CI a common gate runs it and fails if git diff is non-empty, proving generated code is committed and current.
What it does
go generate looks for lines like //go:generate stringer -type=Pill in package files and executes the named command in that package directory. It runs them in source order; it does not understand dependencies between generators. -run filters which directives run by regex.
Common usage
go generate ./...
go generate -x ./... # echo each command
go generate -run mockgen ./... # only matching directives
go generate ./... && git diff --exit-code # drift gateFlags
| Flag | What it does |
|---|---|
| ./... | Process directives in all packages |
| -run <regex> | Only run directives whose command matches |
| -x | Print each generate command as it runs |
| -n | Print commands without executing them (dry run) |
| -v | Print the names of packages and files scanned |
In CI
The standard gate is go generate ./... && git diff --exit-code: if generation changes anything, someone forgot to commit it. Install the generator tools first (often via go install tool@version) and cache the module/build caches. Pin generator versions so output is stable across runs.
Common errors in CI
"go generate: ... : executable file not found in $PATH" means the generator (stringer, mockgen, protoc-gen-go) is not installed; go install it first. "running "protoc": exec: ...: no such file" is the same for non-Go tools. A failing git diff --exit-code after generate means the committed generated files are stale. "directive missing command" flags a malformed //go:generate line.