Skip to content

Commit 4f50f44

Browse files
davidrjennijosharian
authored andcommitted
imports: fix bug, where unused named import is mistaken for unnamed import.
Fixes #8149. Change-Id: Ia3d318f70981b2032a71d3fd32eaffba20cfbcbd Reviewed-on: https://go-review.googlesource.com/13371 Reviewed-by: Josh Bleecher Snyder <josharian@gmail.com>
1 parent b8e61d4 commit 4f50f44

File tree

2 files changed

+33
-15
lines changed

2 files changed

+33
-15
lines changed

imports/fix.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,21 @@ func fixImports(fset *token.FileSet, f *ast.File) (added []string, err error) {
8989
})
9090
ast.Walk(visitor, f)
9191

92+
// Nil out any unused ImportSpecs, to be removed in following passes
93+
unusedImport := map[string]bool{}
94+
for pkg, is := range decls {
95+
if refs[pkg] == nil && pkg != "_" && pkg != "." {
96+
unusedImport[strings.Trim(is.Path.Value, `"`)] = true
97+
}
98+
}
99+
for ipath := range unusedImport {
100+
if ipath == "C" {
101+
// Don't remove cgo stuff.
102+
continue
103+
}
104+
astutil.DeleteImport(fset, f, ipath)
105+
}
106+
92107
// Search for imports matching potential package references.
93108
searches := 0
94109
type result struct {
@@ -126,21 +141,6 @@ func fixImports(fset *token.FileSet, f *ast.File) (added []string, err error) {
126141
}
127142
}
128143

129-
// Nil out any unused ImportSpecs, to be removed in following passes
130-
unusedImport := map[string]bool{}
131-
for pkg, is := range decls {
132-
if refs[pkg] == nil && pkg != "_" && pkg != "." {
133-
unusedImport[strings.Trim(is.Path.Value, `"`)] = true
134-
}
135-
}
136-
for ipath := range unusedImport {
137-
if ipath == "C" {
138-
// Don't remove cgo stuff.
139-
continue
140-
}
141-
astutil.DeleteImport(fset, f, ipath)
142-
}
143-
144144
return added, nil
145145
}
146146

imports/fix_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,24 @@ var (
707707
_ p.P
708708
_ = regexp.Compile
709709
)
710+
`,
711+
},
712+
713+
// Unused named import is mistaken for unnamed import
714+
// golang.org/issue/8149
715+
{
716+
name: "issue 8149",
717+
in: `package main
718+
719+
import foo "fmt"
720+
721+
func main() { fmt.Println() }
722+
`,
723+
out: `package main
724+
725+
import "fmt"
726+
727+
func main() { fmt.Println() }
710728
`,
711729
},
712730
}

0 commit comments

Comments
 (0)