-
Notifications
You must be signed in to change notification settings - Fork 5
/
package.go
75 lines (61 loc) · 1.62 KB
/
package.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
package astutil
import (
"go/ast"
"go/parser"
"go/token"
"os"
"strings"
"sync"
"github.com/pkg/errors"
)
var (
// 开了缓存,ops 可以提高三个数量级
OptPackageCache = true
)
// ReadPackage is simple wrapper for parserDir
// use pkgName with last segment in pkgPath
func ReadPackage(pkgPath string) (pkg *ast.Package, err error) {
short := ``
for i := len(pkgPath) - 1; i >= 0; i-- {
if pkgPath[i] == '/' {
short = pkgPath[:i]
break
}
}
return ReadPackageWithName(pkgPath, short, `.`, func(info os.FileInfo) bool {
return true
})
}
var pkgCache sync.Map
// ReadPackageWithName read package with specified package name
// fileScope used for cache key
func ReadPackageWithName(pkgPath string, pkgName string, fileScope string, filter func(os.FileInfo) bool) (pkg *ast.Package, err error) {
if !OptPackageCache {
return readPackageWithNameNoCache(pkgPath, pkgName, filter)
}
cacheKey := pkgPath + `|` + pkgName + `|` + fileScope
value, ok := pkgCache.Load(cacheKey)
if ok {
pkg = value.(*ast.Package)
return
}
pkg, err = readPackageWithNameNoCache(pkgPath, pkgName, filter)
pkgCache.Store(cacheKey, pkg)
return
}
func readPackageWithNameNoCache(pkgPath string, pkgName string, filter func(os.FileInfo) bool) (pkg *ast.Package, err error) {
pkgs, err := parser.ParseDir(token.NewFileSet(), pkgPath, filter, parser.ParseComments)
if err != nil {
err = errors.WithStack(err)
return
}
pkg, ok := pkgs[pkgName]
if !ok {
keys := []string{}
for name := range pkgs {
keys = append(keys, name)
}
err = errors.Errorf("no package %s in [%s]", pkgName, strings.Join(keys, `,`))
}
return
}