/
remove_unused_imports.go
64 lines (58 loc) · 1.18 KB
/
remove_unused_imports.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package gocodeutil
import (
"go/ast"
"go/token"
"path"
"strings"
"golang.org/x/tools/go/ast/astutil"
)
func RemoveUnusedImports(fset *token.FileSet, file *ast.File) {
unused := make([]*ast.ImportSpec, 0, len(file.Imports))
for _, pkg := range file.Imports {
if pkg.Name != nil && (pkg.Name.Name == "." || pkg.Name.Name == "_") {
continue
}
pkgName := path.Base(strings.Trim(pkg.Path.Value, "\""))
if pkg.Name != nil {
pkgName = pkg.Name.Name
}
if usesImport(file, pkgName) {
continue
}
unused = append(unused, pkg)
}
for _, pkg := range unused {
pkgPath := strings.Trim(pkg.Path.Value, "\"")
if pkg.Name == nil {
astutil.DeleteImport(fset, file, pkgPath)
continue
}
astutil.DeleteNamedImport(fset, file, pkg.Name.Name, pkgPath)
}
}
func usesImport(f *ast.File, pkgName string) bool {
used := false
ast.Inspect(f, func(n ast.Node) bool {
if n == nil {
return true
}
sel, ok := n.(*ast.SelectorExpr)
if !ok {
return true
}
id, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
if id.Obj != nil {
// is not top name
return true
}
if id.Name != pkgName {
return true
}
used = true
return false
})
return used
}