/
seeker.go
110 lines (99 loc) · 2.14 KB
/
seeker.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
101
102
103
104
105
106
107
108
109
110
package main
import (
"fmt"
"go/ast"
"go/token"
"strings"
"github.com/favclip/genbase"
)
type typeSeeker struct {
name string
file *File
ss *structureSource
err error
}
type seekInfo struct {
name string
file *File
}
type ImportSeeker struct {
ss *structureSource
importPkgs []*seekInfo
err error
}
func (t *typeSeeker) seek(node ast.Node) bool {
decl, ok := node.(*ast.GenDecl)
if !ok || decl.Tok != token.TYPE {
return true
}
found := false
for _, spec := range decl.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if ts.Name.String() != t.name {
continue
}
t.ss, t.err = newStructureSource(ts, t.name, t.file)
if t.err != nil {
return true
}
found = true
}
return !found
}
func (i *ImportSeeker) addImportStr(path, ident string) {
if strings.HasPrefix(path, `"`) && strings.HasSuffix(path, `"`) {
path = path[1 : len(path)-1]
}
var ss []string
for _, x := range i.ss.ImportDefs {
ss = append(ss, x.Path)
}
if contains(ss, path) {
return
}
i.ss.ImportDefs = append(i.ss.ImportDefs, &importDef{Ident: ident, Path: path})
}
func contains(ss []string, s string) bool {
for _, a := range ss {
if a == s {
return true
}
}
return false
}
func (i *ImportSeeker) addImports(ss *structureSource) {
for _, f := range ss.FieldSources {
needImport, packageIdent := genbase.IsReferenceToOtherPackage(f.Type)
if !needImport {
continue
}
importSpec := i.FindImportSpecByIdent(ss.file, packageIdent)
if importSpec == nil {
continue
}
i.addImport(importSpec)
}
}
func (i *ImportSeeker) FindImportSpecByIdent(file *File, packageIdent string) *ast.ImportSpec {
for _, imp := range file.file.Imports {
if imp.Name != nil && imp.Name.Name == packageIdent {
return imp
} else if strings.HasSuffix(imp.Path.Value, fmt.Sprintf(`/%s"`, packageIdent)) {
return imp
} else if imp.Path.Value == fmt.Sprintf(`"%s"`, packageIdent) {
return imp
}
}
return nil
}
func (i *ImportSeeker) addImport(importSpec *ast.ImportSpec) {
path := importSpec.Path.Value
ident := ""
if importSpec.Name != nil {
ident = importSpec.Name.Name
}
i.addImportStr(path, ident)
}