/
imports.go
51 lines (41 loc) · 867 Bytes
/
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
package parser
import (
"fmt"
"go/ast"
"strings"
)
type Imports map[string]string
func NewImports() Imports {
return make(Imports)
}
func (m Imports) ParseFile(file *ast.File) {
for _, spec := range file.Imports {
m.ParseImport(spec)
}
}
func (m Imports) ParseImport(spec *ast.ImportSpec) {
path := strings.ReplaceAll(spec.Path.Value, "\"", "")
var name string
if spec.Name != nil {
name = spec.Name.Name
} else {
name = parsePackageName(path)
}
if name == "automap" {
return
}
m[path] = name
}
func (m Imports) ToList() []string {
res := make([]string, 0, len(m))
for path, name := range m {
isUnnamed := (path == name) ||
strings.HasSuffix(path, fmt.Sprintf("/%s", name))
if isUnnamed {
res = append(res, fmt.Sprintf(`"%s"`, path))
} else {
res = append(res, fmt.Sprintf(`%s "%s"`, name, path))
}
}
return res
}