/
goutil.go
219 lines (196 loc) · 4.78 KB
/
goutil.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package goutil
import (
"go/ast"
"go/build"
"go/token"
"io"
"margo.sh/mg"
"margo.sh/vfs"
yotsuba "margo.sh/why_would_you_make_yotsuba_cry"
"os"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
)
var (
// Langs is the list of all Go related langs
Langs = []mg.Lang{mg.Go, mg.GoMod, mg.GoSum}
)
type SrcDirKey struct {
GOROOT, GOPATH, SrcDir string
}
func MakeSrcDirKey(bctx *build.Context, srcDir string) SrcDirKey {
return SrcDirKey{bctx.GOROOT, bctx.GOPATH, filepath.Clean(srcDir)}
}
func BuildContextWithoutCallbacks(mx *mg.Ctx) *build.Context {
c := build.Default
c.GOARCH = mx.Env.Get("GOARCH", c.GOARCH)
c.GOOS = mx.Env.Get("GOOS", c.GOOS)
// these must be passed by the client
// if we leave them unset, there's a risk something will end up using os.Getenv(...)
logUndefined := func(k string) string {
v := mx.Env[k]
if v == "" {
v = k + "-is-not-defined"
mx.Log.Println(v)
}
return v
}
c.GOROOT = logUndefined("GOROOT")
c.GOPATH = logUndefined("GOPATH")
return &c
}
func BuildContext(mx *mg.Ctx) *build.Context {
c := BuildContextWithoutCallbacks(mx)
c.ReadDir = mx.VFS.ReadDir
c.IsDir = mx.VFS.IsDir
c.HasSubdir = HasImportPath // rage against the ~~machine~~symlinks...
c.OpenFile = func(p string) (io.ReadCloser, error) {
if v := mx.View; v != nil && p == v.Path {
return v.Open()
}
if v := mx.View; v != nil && v.Path != "" && filepath.Dir(v.Path) == filepath.Dir(p) {
if b := mx.VFS.ReadBlob(p); b != nil {
return b.OpenFile()
}
}
if b := mx.VFS.PeekBlob(p); b != nil {
return b.OpenFile()
}
return os.Open(p)
}
return c
}
// HasImportPath reports whether dir is lexically a subdirectory of root.
// If so, it sets importPath to a slash-separated path that
// can be joined to root to produce a path equivalent to dir.
//
// HasImportPath is an implementation of go/build.Context.HasSubdir
func HasImportPath(root, dir string) (importPath string, ok bool) {
root = filepath.Clean(root)
dir = filepath.Clean(dir)
if !strings.HasPrefix(dir, root) || root == dir {
return "", false
}
importPath = filepath.ToSlash(dir[len(root):])
if !strings.HasPrefix(importPath, string(filepath.Separator)) {
return "", false
}
return importPath[1:], true
}
func PathList(p string) []string {
l := []string{}
for _, s := range strings.Split(p, string(filepath.ListSeparator)) {
s = filepath.Clean(s)
if filepath.IsAbs(s) {
l = append(l, s)
}
}
return l
}
func NodeEnclosesPos(node ast.Node, pos token.Pos) bool {
if yotsuba.IsNil(node) {
return false
}
if np := node.Pos(); !np.IsValid() || pos < np {
return false
}
ne := node.End()
var cmnt *ast.Comment
switch x := node.(type) {
case *ast.Comment:
cmnt = x
case *ast.CommentGroup:
if l := x.List; len(l) != 0 {
cmnt = l[len(l)-1]
}
}
if cmnt != nil && strings.HasPrefix(cmnt.Text, "//") {
// line comments' end don't include the newline
ne++
}
return pos <= ne || !ne.IsValid()
}
type PosEnd struct {
P token.Pos
E token.Pos
}
func (pe PosEnd) Pos() token.Pos {
return pe.P
}
func (pe PosEnd) End() token.Pos {
return pe.E
}
func IsLetter(ch rune) bool {
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= utf8.RuneSelf && unicode.IsLetter(ch)
}
func PkgNdFilter(nd *vfs.Node) bool {
nm := nd.Name()
return nm[0] != '.' && nm[0] != '_' &&
strings.HasSuffix(nm, ".go") &&
// there's no such thing as a ~~killer videotape~~go package with only test files
!strings.HasSuffix(nm, "_test.go")
}
func IsPkgDirNd(nd *vfs.Node) bool {
return nd.Ls().Some(PkgNdFilter)
}
func IsPkgDir(dir string) bool {
return IsPkgDirNd(mg.VFS.Poke(dir))
}
func ClosestPkgDirNd(nd *vfs.Node) *vfs.Node {
return nd.Closest(IsPkgDirNd)
}
func ClosestPkgDir(dir string) *vfs.Node {
return mg.VFS.Closest(dir, IsPkgDirNd)
}
// DedentCompletion Dedents s then trims preceding and succeeding empty lines.
func DedentCompletion(s string) string {
return strings.TrimFunc(Dedent(s), func(r rune) bool {
return r == '\n' || r == '\r'
})
}
// Dedent un-indents tab-indented lines is s.
func Dedent(s string) string {
lines := strings.Split(s, "\n")
trim := func(s string) int {
i := 0
for i < len(s) && s[i] == '\t' {
i++
}
return i
}
max := 0
for i, s := range lines {
cut := trim(s)
switch {
case max == 0:
max = cut
case cut > max:
cut = max
}
lines[i] = s[cut:]
}
return strings.Join(lines, "\n")
}
// IdentAt returns the indentifier located at pos, if one exists.
func IdentAt(af *ast.File, pos token.Pos) *ast.Ident {
var id *ast.Ident
var sel *ast.SelectorExpr
ast.Inspect(af, func(n ast.Node) bool {
if !NodeEnclosesPos(n, pos) {
return true
}
switch n := n.(type) {
case *ast.Ident:
id = n
case *ast.SelectorExpr:
sel = n
}
return true
})
if id == nil && sel != nil {
return sel.Sel
}
return id
}