forked from sourcegraph/go-langserver
/
buildutil.go
106 lines (89 loc) · 2.37 KB
/
buildutil.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
package tools
import (
"go/build"
"path"
"sort"
"sync"
"golang.org/x/tools/go/buildutil"
"github.com/sourcegraph/go-langserver/langserver/util"
)
// ListPkgsUnderDir is buildutil.ExpandPattern(ctxt, []string{dir +
// "/..."}). The implementation is modified from the upstream
// buildutil.ExpandPattern so we can be much faster. buildutil.ExpandPattern
// looks at all directories under GOPATH if there is a `...` pattern. This
// instead only explores the directories under dir. In future
// buildutil.ExpandPattern may be more performant (there are TODOs for it).
func ListPkgsUnderDir(ctxt *build.Context, dir string) []string {
ch := make(chan string)
var wg sync.WaitGroup
for _, root := range ctxt.SrcDirs() {
root := root
wg.Add(1)
go func() {
allPackages(ctxt, root, dir, ch)
wg.Done()
}()
}
go func() {
wg.Wait()
close(ch)
}()
var pkgs []string
for p := range ch {
pkgs = append(pkgs, p)
}
sort.Strings(pkgs)
return pkgs
}
// We use a process-wide counting semaphore to limit
// the number of parallel calls to ReadDir.
var ioLimit = make(chan bool, 20)
// allPackages is from tools/go/buildutil. We don't use the exported method
// since it doesn't allow searching from a directory. We need from a specific
// directory for performance on large GOPATHs.
func allPackages(ctxt *build.Context, root, start string, ch chan<- string) {
root = path.Clean(root)
start = path.Clean(start)
if util.PathHasPrefix(root, start) {
// If we are a child of start, we can just start at the
// root. A concrete example of this happening is when
// root=/goroot/src and start=/goroot
start = root
}
if !util.PathHasPrefix(start, root) {
return
}
var wg sync.WaitGroup
var walkDir func(dir string)
walkDir = func(dir string) {
// Avoid .foo, _foo, and testdata directory trees.
base := path.Base(dir)
if base == "" || base[0] == '.' || base[0] == '_' || base == "testdata" {
return
}
pkg := util.PathTrimPrefix(dir, root)
// Prune search if we encounter any of these import paths.
switch pkg {
case "builtin":
return
}
if pkg != "" {
ch <- pkg
}
ioLimit <- true
files, _ := buildutil.ReadDir(ctxt, dir)
<-ioLimit
for _, fi := range files {
fi := fi
if fi.IsDir() {
wg.Add(1)
go func() {
walkDir(buildutil.JoinPath(ctxt, dir, fi.Name()))
wg.Done()
}()
}
}
}
walkDir(start)
wg.Wait()
}