Skip to content
Latchkey

go mod tidy: Sync go.mod and go.sum in CI

go mod tidy makes go.mod match the source: it adds requirements for imported packages, drops unused ones, and updates go.sum accordingly.

A common CI gate runs go mod tidy then fails if git diff is non-empty, proving dependencies are declared exactly. Watch the -compat flag on version bumps.

What it does

go mod tidy scans every package the module imports (including tests), adds any missing module requirements to go.mod, removes requirements no package uses, and refreshes go.sum. -go sets the go directive version and -compat controls which older Go version go.sum must stay compatible with.

Common usage

Terminal
go mod tidy
go mod tidy -go=1.22
go mod tidy && git diff --exit-code go.mod go.sum   # CI gate
go mod tidy -compat=1.21

Flags

FlagWhat it does
-go <version>Update the go directive to this version
-compat <version>Keep go.sum compatible with this Go version
-vPrint removed modules to stderr
-eContinue despite errors loading packages
-xPrint the commands tidy runs

In CI

Run tidy and then git diff --exit-code go.mod go.sum so an untidy module fails the build. tidy needs network to fetch checksums; cache the module cache (~/go/pkg/mod) and consider GOFLAGS=-mod=readonly in build/test steps so they error instead of editing go.mod. Run tidy in its own job where editing is expected.

Common errors in CI

"go: updates to go.mod needed, disabled by -mod=readonly" means a build step needs tidy; run it in a separate step without -mod=readonly. "missing go.sum entry for module ...; to add it: go mod download ..." means go.sum is incomplete. "go: errors parsing go.mod" flags a malformed module file. The git-diff gate failing means tidy changed files you must commit.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →