imports: ignore globals in different packages

Some people put multiple packages' files in the same directory, most
commonly commands and code generators. Global variables from one package
should be ignored in other packages.

Change-Id: I9a5d27778570183dfe391dd3273dfa8277a29bf2
Reviewed-on: https://go-review.googlesource.com/c/153419
Run-TryBot: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Heschi Kreinick 2018-12-10 13:43:31 -05:00
parent 85346a3911
commit 4c53570e04
2 changed files with 32 additions and 1 deletions

View File

@ -282,7 +282,11 @@ func (p *pass) load() bool {
// that we might want to mimic.
globals := map[string]bool{}
for _, otherFile := range p.otherFiles {
addGlobals(otherFile, globals)
// Don't load globals from files that are in the same directory
// but a different package. Using them to suggest imports is OK.
if p.f.Name.Name == otherFile.Name.Name {
addGlobals(otherFile, globals)
}
p.candidates = append(p.candidates, collectImports(otherFile)...)
}

View File

@ -1882,6 +1882,33 @@ var time Time
}.processTest(t, "foo.com", "pkg/uses.go", nil, nil, usesGlobal)
}
// Some people put multiple packages' files in the same directory. Globals
// declared in other packages should be ignored.
func TestGlobalImports_DifferentPackage(t *testing.T) {
const declaresGlobal = `package main
var fmt int
`
const input = `package pkg
var _ = fmt.Printf
`
const want = `package pkg
import "fmt"
var _ = fmt.Printf
`
testConfig{
module: packagestest.Module{
Name: "foo.com",
Files: fm{
"pkg/main.go": declaresGlobal,
"pkg/uses.go": input,
},
},
}.processTest(t, "foo.com", "pkg/uses.go", nil, nil, want)
}
// Tests that sibling files - other files in the same package - can provide an
// import that may not be the default one otherwise.
func TestSiblingImports(t *testing.T) {