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>
diff --git a/imports/fix.go b/imports/fix.go
index 4c03393..777d28c 100644
--- a/imports/fix.go
+++ b/imports/fix.go
@@ -1043,7 +1043,7 @@
 	// 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 d34fef6..101978c 100644
--- a/imports/fix_test.go
+++ b/imports/fix_test.go
@@ -2066,6 +2066,28 @@
 
 }
 
+// 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