-
Notifications
You must be signed in to change notification settings - Fork 248
/
helper.go
69 lines (62 loc) · 1.32 KB
/
helper.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
package astutils
import (
"github.com/pkg/errors"
"go/ast"
"go/parser"
"go/token"
"golang.org/x/tools/go/packages"
"path/filepath"
"strings"
)
func IsSlice(t string) bool {
return strings.Contains(t, "[") || strings.HasPrefix(t, "...")
}
func IsVarargs(t string) bool {
return strings.HasPrefix(t, "...")
}
func ToSlice(t string) string {
return "[]" + strings.TrimPrefix(t, "...")
}
// ElementType get element type string from slice
func ElementType(t string) string {
if IsVarargs(t) {
return strings.TrimPrefix(t, "...")
}
return t[strings.Index(t, "]")+1:]
}
func CollectStructsInFolder(dir string, sc *StructCollector) {
dir, _ = filepath.Abs(dir)
var files []string
err := filepath.Walk(dir, Visit(&files))
if err != nil {
panic(err)
}
for _, file := range files {
if filepath.Ext(file) != ".go" {
continue
}
root, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ParseComments)
if err != nil {
panic(err)
}
ast.Walk(sc, root)
}
}
func GetPkgPath(filePath string) string {
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedName,
Dir: filePath,
})
if err != nil {
panic(err)
}
if len(pkgs) == 0 {
panic(errors.New("no package found"))
}
if len(pkgs[0].Errors) > 0 {
for _, err = range pkgs[0].Errors {
panic(err)
}
}
return pkgs[0].PkgPath
}