Skip to content

Commit

Permalink
cmd/go/internal/load: override Package.Root in module mode
Browse files Browse the repository at this point in the history
The Context.ImportDir method in the go/build package sets Package.Root
to $GOPATH, if a package is inside a GOPATH workspace.  The
loadPackageData function keeps this value even when modules are enabled.

Override Package.Root when modules are enabled, instead of just set its
value when Context.ImportDir was unable to set it.

Add a regression test.

Fixes #46119

Change-Id: I900a33fe13a445cb771e2952d0d830f1b4a5921f
Reviewed-on: https://go-review.googlesource.com/c/go/+/319209
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Trust: Bryan C. Mills <bcmills@google.com>
Trust: Jay Conrod <jayconrod@google.com>
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
  • Loading branch information
perillo authored and Bryan C. Mills committed May 14, 2021
1 parent a938e52 commit 0eb38f2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/cmd/go/internal/load/pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,9 @@ func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoo
buildMode = build.ImportComment
}
data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
if data.p.Root == "" && cfg.ModulesEnabled {
if cfg.ModulesEnabled {
// Override data.p.Root, since ImportDir sets it to $GOPATH, if
// the module is inside $GOPATH/src.
if info := modload.PackageModuleInfo(ctx, path); info != nil {
data.p.Root = info.Dir
}
Expand Down
23 changes: 23 additions & 0 deletions src/cmd/go/testdata/script/list_gomod_in_gopath.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Issue 46119

# When a module is inside a GOPATH workspace, Package.Root should be set to
# Module.Dir instead of $GOPATH/src.

env GOPATH=$WORK/tmp
cd $WORK/tmp/src/test

go list -f {{.Root}}
stdout ^$PWD$

# Were we really inside a GOPATH workspace?
env GO111MODULE=off
go list -f {{.Root}}
stdout ^$WORK/tmp$

-- $WORK/tmp/src/test/go.mod --
module test

-- $WORK/tmp/src/test/main.go --
package main

func main() {}

0 comments on commit 0eb38f2

Please sign in to comment.