🎅

いまさら go generate 入門

に公開

Go は go fmt、go test、go build など、開発に必要なツールが標準で揃っているのも魅力の1つだと思います。普段からGoで開発されている方はご存知だと思いますが、標準コマンドの中に go generate というものがあります。

例えば、テスト用のモックを生成するために以下のようなコメントを書いたり、あるいはGraphQL のスキーマを生成するために以下のようなコメントを書いて go generate を実行するといったことをしているかもしれません。

//go:generate go tool mockgen -source=$GOFILE -destination=./service_mock.go

//go:generate go tool gqlgen generate

この使い方からして、「go generate は生成ツールを呼び出すためのショートカットなんだな」と思っていました。しかし、内部としては何をしているのかは把握していなかったので調べてみました。

TL;DR

  • go generate は、Goファイル内の //go:generate ... ディレクティブを走査して、書かれたコマンドを実行する
  • 実体はコマンド実行フックなので、技術的にはコード生成以外にも使える
  • 依存解析などは目的としておらず、タスクランナー用途には向きづらい。そもそもの背景がタスクランナーへの依存をなくすもの

go generate の解説

なにはともあれヘルプを見てみましょう。

go help generate
usage: go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

Generate runs commands described by directives within existing
files. Those commands can run any process but the intent is to
create or update Go source files.

Go generate is never run automatically by go build, go test,
and so on. It must be run explicitly.

Go generate scans the file for directives, which are lines of
the form,

	//go:generate command argument...

(note: no leading spaces and no space in "//go") where command
is the generator to be run, corresponding to an executable file
that can be run locally. It must either be in the shell path
(gofmt), a fully qualified path (/usr/you/bin/mytool), or a
command alias, described below.

Note that go generate does not parse the file, so lines that look
like directives in comments or multiline strings will be treated
as directives.

The arguments to the directive are space-separated tokens or
double-quoted strings passed to the generator as individual
arguments when it is run.

Quoted strings use Go syntax and are evaluated before execution; a
quoted string appears as a single argument to the generator.

To convey to humans and machine tools that code is generated,
generated source should have a line that matches the following
regular expression (in Go syntax):

	^// Code generated .* DO NOT EDIT\.$

This line must appear before the first non-comment, non-blank
text in the file.

Go generate sets several variables when it runs the generator:

	$GOARCH
		The execution architecture (arm, amd64, etc.)
	$GOOS
		The execution operating system (linux, windows, etc.)
	$GOFILE
		The base name of the file.
	$GOLINE
		The line number of the directive in the source file.
	$GOPACKAGE
		The name of the package of the file containing the directive.
	$GOROOT
		The GOROOT directory for the 'go' command that invoked the
		generator, containing the Go toolchain and standard library.
	$DOLLAR
		A dollar sign.
	$PATH
		The $PATH of the parent process, with $GOROOT/bin
		placed at the beginning. This causes generators
		that execute 'go' commands to use the same 'go'
		as the parent 'go generate' command.

Other than variable substitution and quoted-string evaluation, no
special processing such as "globbing" is performed on the command
line.

As a last step before running the command, any invocations of any
environment variables with alphanumeric names, such as $GOFILE or
$HOME, are expanded throughout the command line. The syntax for
variable expansion is $NAME on all operating systems. Due to the
order of evaluation, variables are expanded even inside quoted
strings. If the variable NAME is not set, $NAME expands to the
empty string.

A directive of the form,

	//go:generate -command xxx args...

specifies, for the remainder of this source file only, that the
string xxx represents the command identified by the arguments. This
can be used to create aliases or to handle multiword generators.
For example,

	//go:generate -command foo go tool foo

specifies that the command "foo" represents the generator
"go tool foo".

Generate processes packages in the order given on the command line,
one at a time. If the command line lists .go files from a single directory,
they are treated as a single package. Within a package, generate processes the
source files in a package in file name order, one at a time. Within
a source file, generate runs generators in the order they appear
in the file, one at a time. The go generate tool also sets the build
tag "generate" so that files may be examined by go generate but ignored
during build.

For packages with invalid code, generate processes only source files with a
valid package clause.

If any generator returns an error exit status, "go generate" skips
all further processing for that package.

The generator is run in the package's source directory.

Go generate accepts two specific flags:

	-run=""
		if non-empty, specifies a regular expression to select
		directives whose full original source text (excluding
		any trailing spaces and final newline) matches the
		expression.

	-skip=""
		if non-empty, specifies a regular expression to suppress
		directives whose full original source text (excluding
		any trailing spaces and final newline) matches the
		expression. If a directive matches both the -run and
		the -skip arguments, it is skipped.

It also accepts the standard build flags including -v, -n, and -x.
The -v flag prints the names of packages and files as they are
processed.
The -n flag prints commands that would be executed.
The -x flag prints commands as they are executed.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

上からさらっと大事そうなところや知らなかったことをピックアップしてみます。

Generate runs commands described by directives within existing files.
Those commands can run any process but the intent is to create or update Go source files.

名前の通りでコード生成に使うことを意図としていますが、どんなプロセスでも実行できるようです(!?)。


Go generate scans the file for directives, which are lines of
the form,

	//go:generate command argument...

(note: no leading spaces and no space in "//go") where command
is the generator to be run,

これは go directive の書き方ですね。 //go の前後にスペースは入れないです。


Note that go generate does not parse the file, so lines that look
like directives in comments or multiline strings will be treated
as directives.

構文解析はせず、行頭に //go:generate がある場合はコメントや複数行文字列でも認識されるようです。ただしヘルプにもある通り、ディレクティブは 先頭に空白なしで //go:generate から始まる必要があります。
例えば以下のようなコードは実行されます。

package main

/*
このコメントブロック内に書いても実行される:
//go:generate go tool gqlgen generate
*/

var doc = `
ドキュメント内に書いても実行される:
//go:generate go tool gqlgen generate
`

func main() {}

コメント内に書く場合は気をつけたほうが良さそうです(そんな場面があるかはわかりませんが)。


Go generate sets several variables when it runs the generator:

実行時に環境変数がセットされます。モック生成で$GOFILEや$GOPACKAGEはそこそこ使う印象でした。


To convey to humans and machine tools that code is generated,
generated source should have a line that matches the following
regular expression (in Go syntax):

	^// Code generated .* DO NOT EDIT\.$

コードが生成されたものであることを伝えるために、生成されたソースには ^// Code generated .* DO NOT EDIT\.$ に一致する行を含めましょうとのこと。確かにコード生成されたファイルでよく見かけますが、go generate で推奨しているものだと改めて知りました。


A directive of the form,

	//go:generate -command xxx args...

specifies, for the remainder of this source file only, that the
string xxx represents the command identified by the arguments. This
can be used to create aliases or to handle multiword generators.
For example,

	//go:generate -command foo go tool foo

specifies that the command "foo" represents the generator
"go tool foo".

//go:generate -command xxx args... の形式のディレクティブを書くと、そのファイル内では xxx が args... で指定されたコマンドに置き換えられます。引数や設定値が多い場合に便利そうです。


It also accepts the standard build flags including -v, -n, and -x.
The -v flag prints the names of packages and files as they are
processed.
The -n flag prints commands that would be executed.
The -x flag prints commands as they are executed.

実行時には -v, -n, -x のフラグが使えます。

  • -v はパッケージとファイルの名前を表示
  • -n は実行せずにコマンドを表示(dry run)
  • -x は実行しながらコマンドを表示

dry runできるのは知りませんでした。


任意のコマンドを実行できる

help から go generate の一通りの使い方を確認しましたが、その中でも任意のコマンドを実行できると述べていることが印象に残りました。

Those commands can run any process but the intent is to create or update Go source files.

試してみましょう。

// main.go
package main

//go:generate echo "Hello from go generate!"
//go:generate cat main.go
func main() {}
$ go generate ./...
Hello from go generate!
package main

//go:generate echo "Hello from go generate!"
//go:generate cat main.go
func main() {}

go generate を実行すると go tool でもない、ただの echo や cat が実行されています。ソースコードを確認すると、os/exec を使って go generate で渡されるコマンドを直接実行していることがわかります。

https://github.com/golang/go/blob/ea603eea37f1030cfeecbe03ec7660fbc0da7819/src/cmd/go/internal/generate/generate.go#L498-L510

つまり go generate の本質はGoファイル内に埋め込まれた、任意のコマンドを実行するフックであると考えられます。

タスクランナーとして使えるのか?

任意のコマンドが実行できるなら、タスクランナーとして使えるのでは?と思いました。

例えば、

//go:generate docker compose up -d
//go:generate go run main.go

と書いておいて、go generate を実行すると docker compose up -d や go run main.go が実行されて開発環境を立ち上げるといったことは、技術的には可能です。

しかし、少なくとも自分はそのような使い方を見たことがありません。任意のコマンドが実行できるのに公式でもそのような使い方が紹介されていないのはなぜでしょうか。

go generate の背景

上で見たとおり go generate は任意のコマンドを実行できるフックですが、なぜ go コマンド配下に入れたのでしょうか。

Go には昔から、protobufやstringer のようなコード生成ツールがありました。これらは Go の外側の都合(外部ファイルやメタデータ)を Go の内側(Goソース)に持ち込むために必要で、外部ビルドツールで実行するのが一般的でした(Generating code - The Go Blog)。

ブログでは、「ソースコードを生成する外部ツール」をビルドに組み込むこと自体は、外部ビルドツールを使えば簡単だと述べています。一方で Go では「go ツールが必要なビルド情報を Goソースから得る」ため、当時は go ツール単体でその外部ツールを実行する仕組みがなかった、と説明されています。

そこで go generate です。やることはシンプルで、「このパッケージを成立させるために、まず何を実行すべきか」を Goソースにコメントで残し、go コマンドで実行できるようにする。公式ブログでも、yacc を例に「生成コマンドをソースに埋め込んで、必要なときに明示的に実行する」という絵がそのまま描かれています。

例えば gopher.go を生成するには何を実行すればいいか?というのは、その情報をビルドツールではなく、Go のソースコード自体に埋め込みます。

//go:generate goyacc -o gopher.go -p parser gopher.y

なぜ go build で自動実行しないのか?

ヘルプにも明記されている通り、go generate は go build や go test で自動実行されません。

Go generate is never run automatically by go build, go test,
and so on. It must be run explicitly.

デザインドキュメントにも “Non-goal” として、go generate を make 的な一般ビルドシステムにはしない、依存解析もしない、と書かれています(go-generate.md)。

つまり go generate の立ち位置は

  • Goal: 生成に必要な手順の記録と実行の入口を Go の中に寄せる
  • Non-Goal: 汎用的なビルドシステムのようなこと(依存解析など)はやらない

この割り切りとシンプルさから、go build の挙動を汚さずに導入できたし、生成ツールの多様性も吸収できているのかなと思います。シンプルさがGoらしさを感じさせます。
逆に言うと、この割り切りがそのままタスクランナーとして使いづらい理由になると思いました(そもそもタスクランナーへの依存をしないことを目的として作られたので逆説的ですが...)

結論、タスクランナーの代替として使うには向いていないと思いました。依存解析などの機能が不足しており、それはそもそもの設計の前提が違うからです。

また、余談ですがgo generate は exec.Command でシェルを経由せずにコマンドを実行するため、そのまま書いてもシェルの機能(glob展開など)は基本的に使えません[1]。ヘルプにもある通り、変数展開と quoted-string の評価以外に特別な処理は行われないので、例えば *.go のようなワイルドカードはそのまま引数として渡されます。必要なら sh -c を噛ませることになり、シンプルにタスクランナーとしてみても不向きかなと思いました。

まとめ

go generate のドキュメントをもとに、基本的な使い方やタスクランナーとの違いを考え、生まれた背景を確認しました。「名前は generate だけど、本質はコマンド実行。ただし、意図は Goソースの生成・更新」という、背景を持ったツールだと学びました。

もし誤りや補足があれば、ご指摘いただけると嬉しいです。

参考リンク

脚注
  1. https://pkg.go.dev/os/exec#pkg-overview ↩︎

Discussion