Skip to content

Commit f2d9ab2

Browse files
author
Bryan C. Mills
committed
cmd/go: set GOROOT explicitly for 'go generate' subprocesses
Code generators may reasonably expect to find the GOROOT for which the code is being generated. If the generator invokes 'go run' (which ought to be reasonable to do) and the user has set 'GOFLAGS=trimpath' (which also ought to be reasonable), then either 'go generate' or 'go run' needs to set GOROOT explicitly. I would argue that it is more appropriate for 'go generate' to set GOROOT than for 'go run' to do so, since a user may reasonably invoke 'go run' to reproduce a user-reported bug in a standalone Go program, but should not invoke 'go generate' except to regenerate code for a Go package. Updates golang#51461. Change-Id: Iceba233b4eebd57c40cf5dcd4af9031d210dc9d8 Reviewed-on: https://go-review.googlesource.com/c/go/+/399157 Run-TryBot: Bryan Mills <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Russ Cox <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent e299381 commit f2d9ab2

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

src/cmd/go/alldocs.go

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/cmd/go/internal/generate/generate.go

+4
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,9 @@ Go generate sets several variables when it runs the generator:
8484
The line number of the directive in the source file.
8585
$GOPACKAGE
8686
The name of the package of the file containing the directive.
87+
$GOROOT
88+
The GOROOT directory for the 'go' command that invoked the
89+
generator, containing the Go toolchain and standard library.
8790
$DOLLAR
8891
A dollar sign.
8992
@@ -326,6 +329,7 @@ func isGoGenerate(buf []byte) bool {
326329
// single go:generate command.
327330
func (g *Generator) setEnv() {
328331
g.env = []string{
332+
"GOROOT=" + cfg.GOROOT,
329333
"GOARCH=" + cfg.BuildContext.GOARCH,
330334
"GOOS=" + cfg.BuildContext.GOOS,
331335
"GOFILE=" + g.file,

src/cmd/go/testdata/script/build_trimpath_goroot.txt

+7
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,20 @@ stderr 'cannot find package "runtime" in any of:\n\t\(\$GOROOT not set\)\n\t'$WO
6262
stdout '^GOROOT $'
6363
stdout 'cannot find package "runtime" in any of:\n\t\(\$GOROOT not set\)\n\t'$WORK${/}gopath${/}src${/}runtime' \(from \$GOPATH\)$'
6464

65+
env GOFLAGS=-trimpath
66+
go generate .
67+
stdout '^GOROOT '$TESTGO_GOROOT'$'
68+
stdout '^runtime '$TESTGO_GOROOT${/}src${/}runtime'$'
69+
6570
-- go.mod --
6671
module example
6772

6873
go 1.19
6974
-- main.go --
7075
package main
7176

77+
//go:generate go run .
78+
7279
import (
7380
"fmt"
7481
"go/build"

0 commit comments

Comments
 (0)