-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathprune.go
100 lines (82 loc) · 2.12 KB
/
prune.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Wrapper around x/tools/imports that only removes imports, never adds new ones.
package imports
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/imports"
"github.com/99designs/gqlgen/internal/code"
)
type visitFn func(node ast.Node)
func (fn visitFn) Visit(node ast.Node) ast.Visitor {
fn(node)
return fn
}
// Prune removes any unused imports
func Prune(filename string, src []byte, packages *code.Packages) ([]byte, error) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.AllErrors)
if err != nil {
return nil, err
}
unused := getUnusedImports(file, packages)
for ipath, name := range unused {
astutil.DeleteNamedImport(fset, file, name, ipath)
}
printConfig := &printer.Config{Mode: printer.TabIndent, Tabwidth: 8}
var buf bytes.Buffer
if err := printConfig.Fprint(&buf, fset, file); err != nil {
return nil, err
}
return imports.Process(filename, buf.Bytes(), &imports.Options{FormatOnly: true, Comments: true, TabIndent: true, TabWidth: 8})
}
func getUnusedImports(file ast.Node, packages *code.Packages) map[string]string {
imported := map[string]*ast.ImportSpec{}
used := map[string]bool{}
ast.Walk(visitFn(func(node ast.Node) {
if node == nil {
return
}
switch v := node.(type) {
case *ast.ImportSpec:
if v.Name != nil {
imported[v.Name.Name] = v
break
}
ipath := strings.Trim(v.Path.Value, `"`)
if ipath == "C" {
break
}
local := packages.NameForPackage(ipath)
imported[local] = v
case *ast.SelectorExpr:
xident, ok := v.X.(*ast.Ident)
if !ok {
break
}
if xident.Obj != nil {
// if the parser can resolve it, it's not a package ref
break
}
used[xident.Name] = true
}
}), file)
for pkg := range used {
delete(imported, pkg)
}
unusedImport := map[string]string{}
for pkg, is := range imported {
if !used[pkg] && pkg != "_" && pkg != "." {
name := ""
if is.Name != nil {
name = is.Name.Name
}
unusedImport[strings.Trim(is.Path.Value, `"`)] = name
}
}
return unusedImport
}