diff --git a/imports/fix.go b/imports/fix.go index 22fde6c1..3ccee0ee 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -89,6 +89,21 @@ func fixImports(fset *token.FileSet, f *ast.File) (added []string, err error) { }) ast.Walk(visitor, f) + // Nil out any unused ImportSpecs, to be removed in following passes + unusedImport := map[string]bool{} + for pkg, is := range decls { + if refs[pkg] == nil && pkg != "_" && pkg != "." { + unusedImport[strings.Trim(is.Path.Value, `"`)] = true + } + } + for ipath := range unusedImport { + if ipath == "C" { + // Don't remove cgo stuff. + continue + } + astutil.DeleteImport(fset, f, ipath) + } + // Search for imports matching potential package references. searches := 0 type result struct { @@ -126,21 +141,6 @@ func fixImports(fset *token.FileSet, f *ast.File) (added []string, err error) { } } - // Nil out any unused ImportSpecs, to be removed in following passes - unusedImport := map[string]bool{} - for pkg, is := range decls { - if refs[pkg] == nil && pkg != "_" && pkg != "." { - unusedImport[strings.Trim(is.Path.Value, `"`)] = true - } - } - for ipath := range unusedImport { - if ipath == "C" { - // Don't remove cgo stuff. - continue - } - astutil.DeleteImport(fset, f, ipath) - } - return added, nil } diff --git a/imports/fix_test.go b/imports/fix_test.go index 6be1d578..f087bc70 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -707,6 +707,24 @@ var ( _ p.P _ = regexp.Compile ) +`, + }, + + // Unused named import is mistaken for unnamed import + // golang.org/issue/8149 + { + name: "issue 8149", + in: `package main + +import foo "fmt" + +func main() { fmt.Println() } +`, + out: `package main + +import "fmt" + +func main() { fmt.Println() } `, }, }