From 0fdf0c73855bae8482c5d3907a9e06f33ff70a10 Mon Sep 17 00:00:00 2001 From: kazyshr Date: Sun, 31 Mar 2019 21:03:24 +0900 Subject: [PATCH] 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 TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- imports/fix.go | 2 +- imports/fix_test.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/imports/fix.go b/imports/fix.go index 4c033930..777d28cc 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -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), diff --git a/imports/fix_test.go b/imports/fix_test.go index d34fef66..101978c1 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -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