-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathm_pkgdirs.go
91 lines (79 loc) · 1.71 KB
/
m_pkgdirs.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
package main
import (
"os"
"path"
"path/filepath"
"strings"
"sync"
)
var (
pkgDirsLck = sync.RWMutex{}
pkgDirsCache = map[string]bool{}
)
type mPkgDirs struct {
Env map[string]string
}
func (m *mPkgDirs) Call() (interface{}, string) {
return pkgDirs(m.Env), ""
}
func init() {
registry.Register("pkg_dirs", func(_ *Broker) Caller {
return &mPkgDirs{
Env: map[string]string{},
}
})
}
func pkgDirs(env map[string]string) map[string]map[string]string {
res := map[string]map[string]string{}
for _, root := range rootDirs(env) {
res[root] = map[string]string{}
walkRootDir(root, res[root], root)
}
return res
}
func walkRootDir(root string, m map[string]string, basePath string) {
dir, err := os.Open(root)
if err != nil {
return
}
defer dir.Close()
importPath, err := filepath.Rel(basePath, root)
if err != nil {
importPath = root
}
importPath = path.Clean(filepath.ToSlash(importPath))
idealName := path.Base(importPath) + ".go"
names, err := dir.Readdirnames(-1)
for _, name := range names {
if name[0] == '.' || name[0] == '_' {
continue
}
fn := filepath.Join(root, name)
if strings.HasSuffix(name, ".go") {
isIdeal := false
oldFn, ok := m[importPath]
if ok {
isIdeal = strings.HasSuffix(oldFn, idealName)
}
if !ok || name == idealName || (!isIdeal && name == "main.go") {
m[importPath] = fn
}
} else {
pkgDirsLck.RLock()
isDir, ok := pkgDirsCache[fn]
pkgDirsLck.RUnlock()
if ok {
if isDir {
walkRootDir(fn, m, basePath)
}
} else if fi, err := os.Stat(fn); err == nil {
pkgDirsLck.Lock()
pkgDirsCache[fn] = fi.IsDir()
pkgDirsLck.Unlock()
if fi.IsDir() {
walkRootDir(fn, m, basePath)
}
}
}
}
}