diff --git a/src/cmd/go/generate.go b/src/cmd/go/generate.go index 749e28c24d3..3c6065e89aa 100644 --- a/src/cmd/go/generate.go +++ b/src/cmd/go/generate.go @@ -14,7 +14,6 @@ import ( "os/exec" "path/filepath" "regexp" - "runtime" "strconv" "strings" ) @@ -276,8 +275,8 @@ func isGoGenerate(buf []byte) bool { // single go:generate command. func (g *Generator) setEnv() { g.env = []string{ - "GOARCH=" + runtime.GOARCH, - "GOOS=" + runtime.GOOS, + "GOARCH=" + buildContext.GOARCH, + "GOOS=" + buildContext.GOOS, "GOFILE=" + g.file, "GOLINE=" + strconv.Itoa(g.lineNum), "GOPACKAGE=" + g.pkg, diff --git a/src/cmd/go/go_test.go b/src/cmd/go/go_test.go index a6c70d97b6f..0529d7fb311 100644 --- a/src/cmd/go/go_test.go +++ b/src/cmd/go/go_test.go @@ -2920,3 +2920,27 @@ func TestAlwaysLinkSysoFiles(t *testing.T) { tg.run("list", "-f", "{{.SysoFiles}}", "syso") tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0") } + +// Issue 16120. +func TestGenerateUsesBuildContext(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("this test won't run under Windows") + } + + tg := testgo(t) + defer tg.cleanup() + tg.parallel() + tg.tempDir("src/gen") + tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n") + tg.setenv("GOPATH", tg.path(".")) + + tg.setenv("GOOS", "linux") + tg.setenv("GOARCH", "amd64") + tg.run("generate", "gen") + tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination") + + tg.setenv("GOOS", "darwin") + tg.setenv("GOARCH", "386") + tg.run("generate", "gen") + tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination") +}