From 5f4a60f04f23ac48e0665f257413ae3eacf339be Mon Sep 17 00:00:00 2001 From: Heschi Kreinick Date: Wed, 12 Dec 2018 13:11:39 -0500 Subject: [PATCH] imports: fix renamed sibling imports more This is the fix I should have made in CL 153440. What I get for being in a rush. Fixes golang/go#29180 Change-Id: I7ee3e26173b86c70574b9710f84094e46db27a37 Reviewed-on: https://go-review.googlesource.com/c/153859 Run-TryBot: Heschi Kreinick TryBot-Result: Gobot Gobot Reviewed-by: Ian Cottrell --- imports/fix.go | 7 ++++++- imports/fix_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) 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