Go Generate with Go Run

Using go:generate to run tools over your Go application is super useful, but how can you know you've got the tool installed? Simply having something like:

//go:generate mockery --name=Provider --case=snake --with-expecter

would only work if you've already got mockery installed.

If the tool is a Go application in a public repository, not a problem. Simply run go install and it's now on your dev machine:

$ go install github.com/vektra/mockery/v2@latest
$ go generate ./...
$ go build

But what about your CI/CD pipeline? Sure you could add explicit steps to install the tool first, but we could do better by using go run instead:

//go:generate go run github.com/vektra/mockery/v2/ --name=Provider --case=snake --with-expecter

This saves you from worrying about whether the tools installed. If it is, great. If not, Go will install it for you.

Even better, this also works on your dev machine.

Last updated