This repository has been archived by the owner on May 29, 2018. It is now read-only.
/
pkgs.go
68 lines (58 loc) · 1.84 KB
/
pkgs.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
// Package pkgs finds all packages in all of the GOPATH trees. It is
// library functionality equivalent to `go list all` (see `go help
// packages` for more info).
//
// Much of the code was adapted from the cmd/go matchPackages func.
package pkgs
import (
"go/build"
"os"
"path/filepath"
"strings"
)
type FindMode uint
const (
IncludeStdlib FindMode = 1 << iota
)
// FindAll returns a list of all packages in all of the GOPATH trees
// in the given build context. If prefix is non-empty, only packages
// whose import paths begin with prefix are returned.
func FindAll(prefix string, buildContext build.Context, mode FindMode) (pkgs []*build.Package, err error) {
have := map[string]bool{
"builtin": true, // ignore pseudo-package that exists only for documentation
}
if !buildContext.CgoEnabled {
have["runtime/cgo"] = true // ignore during walk
}
// TODO(sqs): find cmd packages as well
var gorootSrcPkg = filepath.Join(buildContext.GOROOT, "src/pkg")
for _, src := range buildContext.SrcDirs() {
if src == gorootSrcPkg && mode&IncludeStdlib == 0 {
continue // skip stdlib
}
src = filepath.Clean(src) + string(filepath.Separator)
start := filepath.Join(src, prefix)
filepath.Walk(start, func(path string, fi os.FileInfo, err error) error {
if err != nil || !fi.IsDir() || path == src {
return nil
}
// Avoid .foo, _foo, and testdata directory trees.
_, elem := filepath.Split(path)
if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
return filepath.SkipDir
}
name := filepath.ToSlash(path[len(start):])
if have[name] {
return nil
}
have[name] = true
pkg, err := buildContext.ImportDir(path, 0)
if err != nil && strings.Contains(err.Error(), "no Go source files") {
return nil
}
pkgs = append(pkgs, pkg)
return nil
})
}
return pkgs, nil
}