-
Notifications
You must be signed in to change notification settings - Fork 0
/
importer.go
65 lines (58 loc) · 1.19 KB
/
importer.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
package helper
import (
"sort"
"strings"
)
type Importer struct {
data []importPathAndAlias
cache map[string]struct{}
}
type importPathAndAlias struct {
path string
alias string
}
func NewImporter() *Importer {
return &Importer{cache: make(map[string]struct{})}
}
func (i *Importer) Import(importPath string) *Importer {
if _, has := i.cache[importPath]; has {
return i
}
i.data = append(i.data,
importPathAndAlias{path: importPath},
)
i.cache[importPath] = struct{}{}
return i
}
func (i *Importer) ImportWithAlias(importPath string, alias string) *Importer {
if _, has := i.cache[importPath]; has {
return i
}
i.data = append(i.data,
importPathAndAlias{
path: importPath,
alias: alias,
},
)
i.cache[importPath] = struct{}{}
return i
}
func (i *Importer) String() string {
sort.Slice(i.data, func(a, b int) bool {
return i.data[a].path < i.data[b].path
})
var buf strings.Builder
buf.WriteString("import (\n")
for _, im := range i.data {
if im.alias != "" {
buf.WriteRune('\t')
buf.WriteString(im.alias)
buf.WriteRune(' ')
}
buf.WriteString("\t\"")
buf.WriteString(im.path)
buf.WriteString("\"\n")
}
buf.WriteString(")\n")
return buf.String()
}