imports: fix circular imports

goimports will add an import for the package of target source file accidentally,
so check if package path is different from target source file when finding import candidates.

Fixes golang/go#30663

Change-Id: I77c29bc74bef6c888e63ccb501b013a5fbc30b5c
Reviewed-on: https://go-review.googlesource.com/c/tools/+/170238
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
kazyshr 2019-03-31 21:03:24 +09:00 committed by Brad Fitzpatrick
parent a81264a823
commit 0fdf0c7385
2 changed files with 23 additions and 1 deletions

View File

@ -1043,7 +1043,7 @@ func findImport(ctx context.Context, env *fixEnv, dirScan []*pkg, pkgName string
// Find candidate packages, looking only at their directory names first.
var candidates []pkgDistance
for _, pkg := range dirScan {
if pkgIsCandidate(filename, pkgName, pkg) {
if pkg.dir != pkgDir && pkgIsCandidate(filename, pkgName, pkg) {
candidates = append(candidates, pkgDistance{
pkg: pkg,
distance: distance(pkgDir, pkg.dir),

View File

@ -2066,6 +2066,28 @@ var _ = fmt.Printf
}
// Tests that an input file's own package is ignored.
func TestIgnoreOwnPackage(t *testing.T) {
const input = `package pkg
const _ = pkg.X
`
const want = `package pkg
const _ = pkg.X
`
testConfig{
module: packagestest.Module{
Name: "foo.com",
Files: fm{
"pkg/a.go": "package pkg\nconst X = 1",
"pkg/b.go": input,
},
},
}.processTest(t, "foo.com", "pkg/b.go", nil, nil, want)
}
func TestPkgIsCandidate(t *testing.T) {
tests := []struct {
name string