From 899c78c0c2d21557f184d716a5f1bf738065aab3 Mon Sep 17 00:00:00 2001 From: Fabian Holler Date: Thu, 15 Nov 2018 16:48:14 +0100 Subject: [PATCH] resolve: ignore current environment vars when discovering go source files When a baur repository was inside the GOPATH and contained a Go Application using Go-Modules resolving GoSources failed. It failed because Go-Modules are ignored inside the GOPATH. A fix is to add "GO111MODULE=on" to Build.Input.GolangSources.environment for the specific application. Until now all environment variables of the host were used when resolving go source files. With this commit only a couple strictly required environment variables from the host are inherited. When a custom GOPATH on the host is used in which the baur repository resides, resolving gosource files won't fail for this case anymore. It should also help to reduce other unexpected behaviour that might have happened because of some env vars set on the host. Thanks to @joshsteveth for reporting the issue. --- resolve/gosource/gosource.go | 38 ++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/resolve/gosource/gosource.go b/resolve/gosource/gosource.go index 95fc67665..39ecb97c3 100644 --- a/resolve/gosource/gosource.go +++ b/resolve/gosource/gosource.go @@ -22,7 +22,7 @@ type Resolver struct { // If empty or nil the default Go environment is used. func NewResolver(env []string, goDirs ...string) *Resolver { return &Resolver{ - env: append(os.Environ(), env...), + env: env, goDirs: goDirs, } } @@ -44,11 +44,45 @@ func (r *Resolver) Resolve() ([]string, error) { return allFiles, nil } +// whitelistedEnvVars returns whitelisted environment variables from the host +// that are set during resolving. +func whitelistedEnv() []string { + var env []string + + // PATH might be required to locate the "go list" tool on the host + // system + if path, exist := os.LookupEnv("PATH"); exist { + env = append(env, "PATH="+path) + } + + // The following variables are required for go list to determine the go + // build cache, see: https://github.com/golang/go/blob/release-branch.go1.11/src/cmd/go/internal/cache/default.go#L112. + // When those are not set, resolving fails because "go list -compiled" is called internally which requires a gocache dir + if gocache, exist := os.LookupEnv("GOCACHE"); exist { + env = append(env, "GOCACHE="+gocache) + } + + if xdgCacheHome, exist := os.LookupEnv("XDG_CACHE_HOME"); exist { + env = append(env, "XDG_CACHE_HOME="+xdgCacheHome) + } + + if home, exist := os.LookupEnv("HOME"); exist { + env = append(env, "HOME="+home) + } + + // plan9 home env variable + if home, exist := os.LookupEnv("home"); exist { + env = append(env, "home="+home) + } + + return env +} + func (r *Resolver) resolve(path string) ([]string, error) { cfg := &packages.Config{ Mode: packages.LoadImports, Dir: path, - Env: r.env, + Env: append(whitelistedEnv(), r.env...), } lpkgs, err := packages.Load(cfg, "./...")