Skip to content

Commit 0fdf0c7

Browse files
kazyshrbradfitz
authored andcommitted
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 <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent a81264a commit 0fdf0c7

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

imports/fix.go

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

imports/fix_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -2066,6 +2066,28 @@ var _ = fmt.Printf
20662066

20672067
}
20682068

2069+
// Tests that an input file's own package is ignored.
2070+
func TestIgnoreOwnPackage(t *testing.T) {
2071+
const input = `package pkg
2072+
2073+
const _ = pkg.X
2074+
`
2075+
const want = `package pkg
2076+
2077+
const _ = pkg.X
2078+
`
2079+
2080+
testConfig{
2081+
module: packagestest.Module{
2082+
Name: "foo.com",
2083+
Files: fm{
2084+
"pkg/a.go": "package pkg\nconst X = 1",
2085+
"pkg/b.go": input,
2086+
},
2087+
},
2088+
}.processTest(t, "foo.com", "pkg/b.go", nil, nil, want)
2089+
}
2090+
20692091
func TestPkgIsCandidate(t *testing.T) {
20702092
tests := []struct {
20712093
name string

0 commit comments

Comments
 (0)