Tool dependencies in go.mod
suggest changeMost projects use programs written in Go that aren't part of the program itself: code generators like stringer, sqlc and protoc-gen-go, linters, mock generators. Everyone on the team and the CI server should run the same version of each tool.
Since Go 1.24, go.mod can record these tools with a tool directive, and go tool <name> runs them. This article covers:
- adding a tool with
go get -tooland what it writes togo.mod - running tools with
go tool,go generateandgo install tool - upgrading, listing and removing tools
- migrating from the old
tools.gofile with blank imports - real examples with
stringer,sqlcandprotoc-gen-go - keeping tool dependencies out of your module's dependencies with a separate
tools.mod - how
go runandgo toolcache the executables they build
All commands were run with Go 1.27.
Adding a tool
Start with a module and add stringer, which generates String() methods for integer constants:
$ go mod init example.com/shapes
$ go get -tool golang.org/x/tools/cmd/stringer
go: downloading golang.org/x/tools v0.52.0
go: downloading golang.org/x/sync v0.24.0
go: downloading golang.org/x/mod v0.42.0
go: added golang.org/x/mod v0.42.0
go: added golang.org/x/sync v0.24.0
go: added golang.org/x/tools v0.52.0
go get -tool does two things: it adds a tool line naming the package, and it adds the module that contains it (plus that module's dependencies) as requirements:
module example.com/shapes
go 1.27.0
tool golang.org/x/tools/cmd/stringer
require (
golang.org/x/mod v0.42.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/tools v0.52.0 // indirect
)
Notes:
- The
toolline names a package path (golang.org/x/tools/cmd/stringer), not a module path. The version comes from therequireblock, so the version of the tool is pinned and checked againstgo.sumlike any other dependency. - The requirements are marked
// indirectbecause no package in your module imports them. go mod tidykeeps tool requirements. Before Go 1.24 it would have removed them, which is why thetools.gotrick (described below) existed.- Commit
go.modandgo.sum. Anyone who clones the repository gets the same tool version.
With more than one tool, the directives are grouped in a block like require:
tool (
golang.org/x/tools/cmd/stringer
google.golang.org/protobuf/cmd/protoc-gen-go
)
You can also edit the directive without downloading anything with go mod edit -tool=path and go mod edit -droptool=path, then run go mod tidy to add or remove the matching requirements.
Running a tool with go tool
go tool <name> builds the tool at the version from go.mod and runs it. <name> is the last element of the package path, and arguments after it are passed to the tool:
$ go tool stringer -h
Usage of stringer:
stringer [flags] -type T [directory]
stringer [flags] -type T files... # Must be a single package
For more information, see:
https://pkg.go.dev/golang.org/x/tools/cmd/stringer
If two tools have the same last element (e.g. two different .../cmd/gen), use the full package path: go tool golang.org/x/tools/cmd/stringer -h.
go tool without arguments lists the tools that ship with Go followed by the tools declared in go.mod:
$ go tool
asm
cgo
compile
cover
fix
link
preprofile
vet
stringer (golang.org/x/tools/cmd/stringer)
An unknown name is an error:
$ go tool nosuch
go: no such tool "nosuch"
go tool uses the module of the current directory, so it works from any subdirectory of the module, and different projects on the same machine can use different versions of the same tool without conflicts. Nothing is installed in GOBIN or PATH.
The tool doesn't have to come from another module. A main package inside your own module works too, which is handy for project-specific generators like the one in Code generation with go/ast:
// cmd/hello/main.go in module example.com/local
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("hello from a module-local tool, args:", os.Args[1:])
}
$ go get -tool ./cmd/hello
$ go tool hello a b
hello from a module-local tool, args: [a b]
The go.mod gets tool example.com/local/cmd/hello and no new requirements. Compared to go run ./cmd/hello this gives the generator a short name that works from any directory in the module.
Using tools with go generate
go tool is most useful in //go:generate lines. The version of the generator is now part of the module, so go generate produces the same output on every machine:
package main
import "fmt"
//go:generate go tool stringer -type=Shape
type Shape int
const (
Circle Shape = iota
Square
Triangle
)
func main() {
for _, s := range []Shape{Circle, Square, Triangle, 7} {
fmt.Println(s)
}
}
$ go generate -x ./...
go tool stringer -type=Shape
$ go run .
Circle
Square
Triangle
Shape(7)
go generate created shape_string.go:
// Code generated by "stringer -type=Shape"; DO NOT EDIT.
package main
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Circle-0]
_ = x[Square-1]
...
Compare this with the older styles of //go:generate lines:
| Line | Problem |
|---|---|
//go:generate stringer -type=Shape |
needs stringer in PATH, at whatever version each developer happened to install |
//go:generate go run golang.org/x/tools/cmd/stringer -type=Shape |
version comes from go.mod only if something keeps the requirement there (tools.go) |
//go:generate go run golang.org/x/tools/cmd/stringer@v0.52.0 -type=Shape |
pinned, but the version is repeated in every file and ignores go.mod |
//go:generate go tool stringer -type=Shape |
pinned in go.mod, short, nothing to install |
See Enums for how String() methods for enums are used.
sqlc
sqlc generates type-safe Go code from SQL queries. Add it as a tool:
$ go mod init example.com/db
$ go get -tool github.com/sqlc-dev/sqlc/cmd/sqlc
$ go tool sqlc version
v1.31.1
Configure it with sqlc.yaml:
version: "2"
sql:
- engine: "sqlite"
schema: "schema.sql"
queries: "query.sql"
gen:
go:
package: "db"
out: "db"
with schema.sql:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
and query.sql:
-- name: GetUser :one
SELECT id, name FROM users WHERE id = ?;
Put the //go:generate line in any Go file in the module root, e.g. gen.go:
package main
//go:generate go tool sqlc generate
$ go generate -x
go tool sqlc generate
$ ls db
db.go models.go query.sql.go
db/query.sql.go now has func (q *Queries) GetUser(ctx context.Context, id int64) (User, error).
sqlc is a big program: go get -tool added 44 modules to go.mod. That's the main cost of tool dependencies; see "Keeping tools out of your dependencies" below.
protoc-gen-go
protoc-gen-go is a plugin: you don't run it yourself, protoc runs it. By default protoc looks for an executable named protoc-gen-go in PATH, which defeats the point of pinning it. Instead, pass the path with --plugin. go tool -n builds the tool if needed and prints the path of the executable instead of running it:
$ go get -tool google.golang.org/protobuf/cmd/protoc-gen-go
$ go tool -n protoc-gen-go
C:\Users\me\AppData\Local\go-build\ba\bad22ca09006e34b18a5643f295c926b79338674704b4d176dde8d29e1e4ac22-d\protoc-gen-go.exe
$ go tool protoc-gen-go --version
protoc-gen-go.exe v1.36.12
A //go:generate line that uses it (it needs a Unix-like shell for $(...); on Windows sh from Git for Windows works):
package pb
//go:generate sh -c "protoc --plugin=protoc-gen-go=$(go tool -n protoc-gen-go) --go_out=. --go_opt=paths=source_relative user.proto"
syntax = "proto3";
package pb;
option go_package = "example.com/old/pb";
message User {
int64 id = 1;
string name = 2;
}
$ go generate ./...
$ head -5 pb/user.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc v7.36.2
// source: user.proto
There's a nice side effect: the generated code imports google.golang.org/protobuf, and protoc-gen-go lives in the same module. Both come from one require line, so the generator and the runtime library can't drift apart. After go mod tidy the requirement becomes direct:
require google.golang.org/protobuf v1.36.12
protoc itself is a C++ program and can't be a Go tool dependency. See Using protobuf with Go for more about protobuf.
Installing tools with go install tool
Some programs need tools as real executables: editors, Makefiles, protoc plugins, pre-commit hooks. The tool package pattern matches all tools of the module, and go install tool installs all of them into GOBIN (or $GOPATH/bin) at the versions from go.mod:
$ go install tool
$ ls $(go env GOBIN)
stringer.exe
To keep the binaries inside the project instead of a shared directory, set GOBIN for this one command:
$ GOBIN=$PWD/bin go install tool
$ export PATH=$PWD/bin:$PATH
The installed binary records the version it was built from:
$ go version -m bin/stringer.exe
bin/stringer.exe: go1.27.0
path golang.org/x/tools/cmd/stringer
mod golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
dep golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
dep golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
This is different from go install golang.org/x/tools/gopls@latest (see go get), which ignores the current module. Use that for personal tools like gopls that have nothing to do with a particular project.
Listing, upgrading and removing tools
go list tool prints the package paths of all tools:
$ go list tool
golang.org/x/tools/cmd/stringer
google.golang.org/protobuf/cmd/protoc-gen-go
A specific tool is upgraded or downgraded with go get -tool and a version:
$ go get -tool golang.org/x/tools/cmd/stringer@v0.40.0
go: downgraded golang.org/x/mod v0.42.0 => v0.32.0
go: downgraded golang.org/x/tools v0.52.0 => v0.40.0
go get tool upgrades every tool to its latest version, and go get -u tool also upgrades their dependencies:
$ go get tool
go: upgraded golang.org/x/mod v0.32.0 => v0.42.0
go: upgraded golang.org/x/tools v0.40.0 => v0.52.0
To remove a tool, use the version none:
$ go get -tool golang.org/x/tools/cmd/stringer@none
This removes the tool line. The requirement on golang.org/x/tools stays if something else needs it, otherwise go mod tidy removes it. Remember to delete //go:generate lines that use the tool:
$ go generate ./...
go: no such tool "stringer"
shape.go:5: running "go": exit status 2
go get -tool accepts any package path, even one that isn't a main package, and complains later:
$ go get -tool golang.org/x/tools/go/packages
$ go install tool
package golang.org/x/tools/go/packages is not a main package
Fix it with go mod edit -droptool golang.org/x/tools/go/packages.
Migrating from tools.go
Before Go 1.24, the common way to pin tools was a tools.go file with blank imports, excluded from builds by a build tag:
//go:build tools
package tools
import (
_ "golang.org/x/tools/cmd/stringer"
_ "google.golang.org/protobuf/cmd/protoc-gen-go"
)
The imports made go mod tidy keep the requirements, and the tools build tag made sure the file was never compiled (importing a main package is otherwise an error). Tools were run with go run golang.org/x/tools/cmd/stringer. With tools.go, go mod tidy treats the tool modules as direct dependencies:
require (
golang.org/x/tools v0.52.0
google.golang.org/protobuf v1.36.12
)
To migrate:
-
Add a
tooldirective for each blank import. Several-toolflags can be passed to one command:$ go mod edit -tool golang.org/x/tools/cmd/stringer -tool google.golang.org/protobuf/cmd/protoc-gen-gogo get -tool pathworks too, but it also upgrades the tool to the latest version unless you add@version. -
Delete
tools.go. -
Run
go mod tidy. The requirements stay, now marked// indirect. -
Replace
go run golang.org/x/tools/cmd/stringerwithgo tool stringerin//go:generatelines, Makefiles and CI scripts.
$ go mod tidy
$ go list tool
golang.org/x/tools/cmd/stringer
google.golang.org/protobuf/cmd/protoc-gen-go
The old way still works, so there's no rush, but go tool is shorter, and the tool block documents what the requirements are for.
Keeping tools out of your dependencies
Tool requirements live in the same module graph as your code's requirements. Go uses one version of each module for the whole graph (minimal version selection), so adding a tool can upgrade libraries your program uses.
Here a program uses golang.org/x/mod v0.20.0:
package main
import (
"fmt"
"golang.org/x/mod/semver"
)
func main() {
fmt.Println(semver.Compare("v1.2.0", "v1.10.0"))
}
Adding stringer silently upgrades it, because the newest golang.org/x/tools requires a newer golang.org/x/mod:
$ go get golang.org/x/mod@v0.20.0
go: added golang.org/x/mod v0.20.0
$ go get -tool golang.org/x/tools/cmd/stringer
go: upgraded golang.org/x/mod v0.20.0 => v0.42.0
go: added golang.org/x/sync v0.24.0
go: upgraded golang.org/x/tools v0.13.0 => v0.52.0
For small tools that's usually fine. For big tools (sqlc with 44 modules, linters with hundreds) it means your program gets upgrades it didn't ask for, and if your module is a library, the tool's requirements become part of the module graph of every program that uses it, where they can raise the versions of shared dependencies.
The fix is a separate module file just for tools. Most go commands accept -modfile:
$ go mod init -modfile=tools.mod example.com/app
$ go get -modfile=tools.mod -tool golang.org/x/tools/cmd/stringer
go: added golang.org/x/mod v0.42.0
go: added golang.org/x/sync v0.24.0
go: added golang.org/x/tools v0.52.0
This creates tools.mod and tools.sum next to go.mod, while go.mod keeps only what the program needs:
module example.com/app
go 1.27.0
require golang.org/x/mod v0.20.0
Pass the same flag to run, list or install the tools:
$ go tool -modfile=tools.mod stringer -h
Usage of stringer:
...
$ go list -modfile=tools.mod tool
golang.org/x/tools/cmd/stringer
$ go list tool
go: warning: "tool" matched no packages
and in //go:generate lines: //go:generate go tool -modfile=../tools.mod stringer -type=Shape. Note that the path is relative to the directory of the file with the //go:generate line, because that's where go generate runs the command.
Use the separate file for heavy tools and keep go.mod for small ones like stringer, or put everything in tools.mod if the module is a library.
Executables are cached
Before Go 1.24, go run re-linked the executable every time, which made each go run some/tool noticeably slower than running an installed binary. Since Go 1.24, executables built by go run and go tool are stored in the build cache, so the second run is nearly as fast as running an installed binary.
Timing go tool stringer -h with an empty build cache:
$ time go tool stringer -h # compiles stringer and its dependencies
real 0m17.198s
$ time go tool stringer -h # cached executable
real 0m1.193s
$ time go tool stringer -h
real 0m0.333s
go tool -n (and go run -n for a package) show where the cached executable is:
$ go tool -n stringer
C:\Users\me\AppData\Local\go-build\fd\fd8fe10ee33e50f25398ab3742b70482d8a0717eb250709f73533687a9f21286-d\stringer.exe
The cache key depends on the package, the versions of all its dependencies and the build settings, so two projects that pin the same version of stringer share one cached executable, and upgrading the tool in go.mod builds a new one. Cached executables are removed by go clean -cache and, like other build cache entries, are trimmed automatically when they haven't been used for a while. See GOPATH, GOROOT, GOBIN and go env for GOCACHE and the other directories the go command uses.
In CI this means there's no separate "install tools" step: go generate ./... or go tool ... builds what's needed, and if you cache GOCACHE and GOMODCACHE between runs (as actions/setup-go does), tools aren't rebuilt at all. See Test Go code with GitHub Actions.
Summary
| Task | Command |
|---|---|
| add a tool | go get -tool golang.org/x/tools/cmd/stringer |
| add a tool at a version | go get -tool golang.org/x/tools/cmd/stringer@v0.52.0 |
| run a tool | go tool stringer args... |
| print the tool's executable path | go tool -n stringer |
| list tools | go list tool |
install all tools into GOBIN |
go install tool |
| upgrade all tools | go get tool (go get -u tool to also upgrade their dependencies) |
| remove a tool | go get -tool golang.org/x/tools/cmd/stringer@none |
| edit without downloading | go mod edit -tool=path, go mod edit -droptool=path |
| keep tools in a separate file | add -modfile=tools.mod to the commands above |
Things to remember:
- the
tooldirective needs Go 1.24 or later (see Go versions and toolchains) - a tool is a package path, its version comes from the
requireblock - tool requirements share version selection with your code; use
-modfile=tools.modfor heavy tools go tool <name>uses the last path element; use the full path when names collide- use
go install pkg@versionfor personal tools that don't belong to a project