diff --git a/imports/fix.go b/imports/fix.go index d009cd50..a8ac4ac1 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -200,7 +200,12 @@ func (p *pass) findMissingImport(pkg string, syms map[string]bool) *importInfo { if !ok { continue } - if candidate.name != pkg && pkgInfo.name != pkg { + // If the candidate import has a name, it must match pkg. + if candidate.name != "" && candidate.name != pkg { + continue + } + // Otherwise, the real name of the package must match. + if candidate.name == "" && pkgInfo.name != pkg { continue } diff --git a/imports/fix_test.go b/imports/fix_test.go index ec22c60b..f83239f3 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -1966,6 +1966,34 @@ func LogSomethingElse() { }.processTest(t, "foo.com", "p/needs_import.go", nil, nil, want) } +// Tests #29180: a sibling import of the right package with the wrong name is used. +func TestSiblingImport_Misnamed(t *testing.T) { + const sibling = `package main +import renamed "fmt" +var _ = renamed.Printf +` + 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": sibling, + "pkg/uses.go": input, + }, + }, + }.processTest(t, "foo.com", "pkg/uses.go", nil, nil, want) + +} + func TestPkgIsCandidate(t *testing.T) { tests := []struct { name string