diff --git a/imports/fix.go b/imports/fix.go index 6e969d03..eacc557e 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -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)...) } diff --git a/imports/fix_test.go b/imports/fix_test.go index 20bc219f..73d92dcb 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -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) {