-
Notifications
You must be signed in to change notification settings - Fork 1
/
corpus.go
85 lines (76 loc) · 1.9 KB
/
corpus.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
package goref
import (
"fmt"
"go/build"
"os"
"path/filepath"
"strings"
)
// A Corpus represents a prefix from which Go packages may be loaded.
// Default corpora are $GOROOT/src and each of $GOPATH/src
type Corpus string
// NewCorpus creates a new Corpus.
func NewCorpus(basepath string) (Corpus, error) {
if !filepath.IsAbs(basepath) {
return Corpus(""), fmt.Errorf("Corpus %s has a relative basepath", basepath)
}
return Corpus(basepath), nil
}
// Contains returns whether the provided filepath exists under this
// Corpus.
func (c Corpus) Contains(fpath string) bool {
if string(c) == "" {
return false
}
rel, err := filepath.Rel(string(c), fpath)
if err != nil {
return false
}
return !strings.HasPrefix(rel, "../") && rel != ".."
}
// ContainsRel returns whether the provided relpath exists under this
// Corpus.
func (c Corpus) ContainsRel(rel string) bool {
fpath := c.Abs(rel)
fi, err := os.Stat(fpath)
if err != nil {
return false
}
return (fi.Mode() & os.ModeType) == 0
}
// Abs returns the absolute path of a file within a Corpus.
func (c Corpus) Abs(rel string) string {
if string(c) == "" {
return ""
}
return filepath.Join(string(c), rel)
}
// Pkg returns the package containing this file.
func (c Corpus) Pkg(rel string) string {
if string(c) == "" || rel == "" {
return ""
}
return filepath.Dir(string(rel))
}
// Rel returns the relative path of a file within a Corpus.
// If the string does not belong to the corpus, it returns fpath.
func (c Corpus) Rel(fpath string) string {
if !c.Contains(fpath) {
return fpath
}
rel, err := filepath.Rel(string(c), fpath)
if err != nil {
return fpath
}
return rel
}
// DefaultCorpora returns the set of default corpora based on GOROOT
// and GOPATH.
func DefaultCorpora() []Corpus {
srcdirs := build.Default.SrcDirs()
corpora := make([]Corpus, len(srcdirs))
for n, s := range srcdirs {
corpora[n] = Corpus(s)
}
return corpora
}