1
0
mirror of https://github.com/golang/go synced 2024-09-30 22:48:32 -06:00

x/tools/gopls: add fallback to default GOPATH if missing

The "Organize imports" code action uses internal/imports that needs a
valid GOPATH set. Since Go 1.8 setting GOPATH manually is not required,
and if it isn't set gopls will sometimes fail to properly import
packages.

This CL sets GOPATH to the default if the env var GOPATH isn't set.

Fixes golang/go#33918.

Change-Id: Ib63a26a801e15af730197999de4d1d4901694a30
Reviewed-on: https://go-review.googlesource.com/c/tools/+/191600
Run-TryBot: Ian Cottrell <iancottrell@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
This commit is contained in:
Pontus Leitzler 2019-08-28 20:02:38 +00:00 committed by Paul Jolly
parent 340205e581
commit f340ed3ae2

View File

@ -12,6 +12,7 @@ import (
"go/token"
"go/types"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
@ -147,7 +148,10 @@ func (v *view) RunProcessEnvFunc(ctx context.Context, fn func(*imports.Options)
v.mu.Lock()
defer v.mu.Unlock()
if v.processEnv == nil {
v.processEnv = v.buildProcessEnv(ctx)
var err error
if v.processEnv, err = v.buildProcessEnv(ctx); err != nil {
return err
}
}
// Before running the user provided function, clear caches in the resolver.
@ -176,7 +180,7 @@ func (v *view) RunProcessEnvFunc(ctx context.Context, fn func(*imports.Options)
return nil
}
func (v *view) buildProcessEnv(ctx context.Context) *imports.ProcessEnv {
func (v *view) buildProcessEnv(ctx context.Context) (*imports.ProcessEnv, error) {
cfg := v.Config(ctx)
env := &imports.ProcessEnv{
WorkingDir: cfg.Dir,
@ -204,7 +208,17 @@ func (v *view) buildProcessEnv(ctx context.Context) *imports.ProcessEnv {
env.GOSUMDB = split[1]
}
}
return env
if env.GOPATH == "" {
cmd := exec.CommandContext(ctx, "go", "env", "GOPATH")
cmd.Env = cfg.Env
if out, err := cmd.CombinedOutput(); err != nil {
return nil, err
} else {
env.GOPATH = strings.TrimSpace(string(out))
}
}
return env, nil
}
func (v *view) modFilesChanged() bool {