forked from nsf/gocode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
283 lines (250 loc) · 5.94 KB
/
utils.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package gocode
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/charlievieth/gocode/fs"
"github.com/golang/groupcache/lru"
)
type DirEntry struct {
modTime time.Time
names []string
}
type DirCache struct {
cache *lru.Cache
mu sync.Mutex
}
func NewDirCache() *DirCache {
return &DirCache{
cache: lru.New(200),
}
}
func (c *DirCache) readdirnames(path string, fi os.FileInfo) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
if fi == nil {
fi, err = f.Stat()
if err != nil {
return nil, err
}
}
names, err := f.Readdirnames(-1)
f.Close()
if err != nil {
return nil, err
}
c.cache.Add(path, DirEntry{
modTime: fi.ModTime(),
names: names,
})
return names, nil
}
func (c *DirCache) Readdirnames(path string) ([]string, error) {
c.mu.Lock()
defer c.mu.Unlock()
v, found := c.cache.Get(path)
if !found {
return c.readdirnames(path, nil)
}
d, ok := v.(DirEntry)
if !ok {
// This should not happen
if found {
c.cache.Remove(path)
}
return c.readdirnames(path, nil)
}
fi, err := fs.Stat(path)
if err != nil {
if found {
c.cache.Remove(path)
}
return nil, err
}
if !fi.ModTime().Equal(d.modTime) {
names, err := c.readdirnames(path, fi)
if err != nil {
c.cache.Remove(path)
}
return names, err
}
return d.names, nil
}
var dir_cache = NewDirCache()
func has_go_ext(s string) bool {
return len(s) >= len("*.go") && s[len(s)-len(".go"):] == ".go"
}
func readdirnames(name string) ([]string, error) {
return dir_cache.Readdirnames(name)
}
// our own readdir, which skips the files it cannot lstat
func readdir_lstat(name string) ([]os.FileInfo, error) {
names, err := readdirnames(name)
if err != nil {
return nil, err
}
out := make([]os.FileInfo, 0, len(names))
for _, lname := range names {
s, err := fs.Lstat(name + string(filepath.Separator) + lname)
if err == nil {
out = append(out, s)
}
}
return out, nil
}
func readdir_gofiles_lstat(name string) ([]os.FileInfo, error) {
names, err := readdirnames(name)
if err != nil {
return nil, err
}
n := 0
for _, s := range names {
if has_go_ext(s) {
n++
}
}
if n == 0 {
return nil, nil
}
out := make([]os.FileInfo, 0, n)
for _, lname := range names {
if has_go_ext(lname) {
s, err := fs.Lstat(name + string(filepath.Separator) + lname)
if err == nil {
out = append(out, s)
}
}
}
return out, nil
}
// our other readdir function, only opens and reads
func readdir(dirname string) []os.FileInfo {
f, err := os.Open(dirname)
if err != nil {
return nil
}
fi, err := f.Readdir(-1)
f.Close()
if err != nil {
panic(err)
}
return fi
}
// returns truncated 'data' and amount of bytes skipped (for cursor pos adjustment)
func filter_out_shebang(data []byte) ([]byte, int) {
if len(data) > 2 && data[0] == '#' && data[1] == '!' {
newline := bytes.IndexByte(data, '\n')
if newline != -1 && len(data) > newline+1 {
return data[newline+1:], newline + 1
}
}
return data, 0
}
func file_exists(filename string) bool {
return fs.FileExists(filename)
}
func is_dir(path string) bool {
return fs.IsDir(path)
}
func has_prefix(s, prefix string, ignorecase bool) bool {
return len(s) >= len(prefix) &&
(s[0:len(prefix)] == prefix ||
(ignorecase && strings.EqualFold(s[0:len(prefix)], prefix)))
}
// vendorlessImportPath returns the devendorized version of the provided import path.
// e.g. "foo/bar/vendor/a/b" => "a/b"
func vendorlessImportPath(ipath string, currentPackagePath string) (string, bool) {
if strings.Contains(ipath, "vendor/") {
split := strings.Split(ipath, "vendor/")
// no vendor in path
if len(split) == 1 {
return ipath, true
}
// this import path does not belong to the current package
if currentPackagePath != "" && !strings.Contains(currentPackagePath, split[0]) {
return "", false
}
// Devendorize for use in import statement.
if i := strings.LastIndex(ipath, "/vendor/"); i >= 0 {
return ipath[i+len("/vendor/"):], true
}
if strings.HasPrefix(ipath, "vendor/") {
return ipath[len("vendor/"):], true
}
}
return ipath, true
}
//-------------------------------------------------------------------------
// print_backtrace
//
// a nicer backtrace printer than the default one
//-------------------------------------------------------------------------
var g_backtrace_mutex sync.Mutex
func print_backtrace(err interface{}) {
g_backtrace_mutex.Lock()
defer g_backtrace_mutex.Unlock()
fmt.Printf("panic: %v\n", err)
i := 2
for {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
f := runtime.FuncForPC(pc)
fmt.Printf("%d(%s): %s:%d\n", i-1, f.Name(), file, line)
i++
}
fmt.Println("")
}
//-------------------------------------------------------------------------
// File reader goroutine
//
// It's a bad idea to block multiple goroutines on file I/O. Creates many
// threads which fight for HDD. Therefore only single goroutine should read HDD
// at the same time.
//-------------------------------------------------------------------------
type file_reader_type struct {
gate chan struct{}
}
var file_reader = &file_reader_type{
gate: make(chan struct{}, 100),
}
func (r *file_reader_type) read_file(filename string) ([]byte, error) {
r.gate <- struct{}{}
b, err := ioutil.ReadFile(filename)
<-r.gate
return b, err
}
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// NB: use this for reading .a files since I compile on save they
// are often the same size, but the updated at timestamp changes.
func (r *file_reader_type) read_file_buffer(filename string, fi os.FileInfo) (*bytes.Buffer, error) {
r.gate <- struct{}{}
defer func() { <-r.gate }()
f, err := os.Open(filename)
if err != nil {
return nil, err
}
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
buf.Grow(int(fi.Size()) + bytes.MinRead)
_, err = buf.ReadFrom(f)
f.Close()
if err != nil {
bufferPool.Put(buf)
return nil, err
}
return buf, nil
}