forked from slene/margo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkgpaths.go
126 lines (102 loc) · 1.96 KB
/
pkgpaths.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"go/parser"
"go/token"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
buildIgnore = regexp.MustCompile(`^\W*[+]build.*?\bignore\b`)
)
func ignoreNm(name string) bool {
if name == "" || name[0] == '.' || name[0] == '_' {
return true
}
name = strings.ToLower(name)
return strings.HasSuffix(name, "_test.go")
}
func ls(fn string) ([]string, bool) {
nm := filepath.Base(fn)
if ignoreNm(nm) {
return nil, false
}
d, err := os.Open(fn)
if err != nil {
return nil, false
}
defer d.Close()
names, err := d.Readdirnames(-1)
return names, (err == nil || len(names) > 0)
}
func walk(root string, ch chan string, dir string) {
names, ok := ls(dir)
if !ok {
return
}
for _, nm := range names {
if ignoreNm(nm) {
continue
}
fn := filepath.Join(dir, nm)
isFx, isGo := fx(nm)
if isGo {
ch <- fn
} else if !isFx {
walk(root, ch, fn)
}
}
}
func pkgPaths(srcDir string, exclude []string) map[string]string {
paths := map[string]string{}
done := make(chan struct{})
ch := make(chan string, 100)
fset := token.NewFileSet()
seen := map[string]void{}
excluded := map[string]void{}
for _, s := range exclude {
excluded[s] = void{}
}
proc := func(fn string) {
dir := filepath.Dir(fn)
p, err := filepath.Rel(srcDir, dir)
if err != nil || strings.HasPrefix(p, ".") {
return
}
p = filepath.ToSlash(p)
if _, ok := paths[p]; ok {
return
}
if _, ok := seen[p]; ok {
return
}
af, _ := parser.ParseFile(fset, fn, nil, parser.ImportsOnly|parser.ParseComments)
if af == nil || af.Name == nil {
return
}
name := af.Name.String()
for _, cg := range af.Comments {
for _, c := range cg.List {
if buildIgnore.MatchString(c.Text) {
return
}
}
}
if _, skip := excluded[name]; skip {
seen[p] = void{}
return
}
paths[p] = name
}
go func() {
defer close(done)
for fn := range ch {
proc(fn)
}
}()
walk(srcDir, ch, srcDir)
close(ch)
<-done
return paths
}