-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
353 lines (335 loc) · 7.85 KB
/
server.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package main
import (
"bufio"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path"
"regexp"
"strings"
"sync"
"9fans.net/go/plan9"
"9fans.net/go/plumb"
)
var (
globalProj = ""
projects map[string]Project
filePathValidator *regexp.Regexp
)
type msg struct {
Action int
Project string
What string
Where string
}
type response struct {
body string // JSON string
}
func listen(c chan int) {
ln, err := net.Listen("tcp", ":"+*port)
if err != nil {
log.Printf("listen error: %v", err)
c <- 1
return
}
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("accept error: %v", err)
c <- 1
return
}
go serve(conn)
log.Printf("********")
}
}
func serveProjects(conn net.Conn) error {
return json.NewEncoder(conn).Encode(projects)
}
func serve(conn net.Conn) {
defer conn.Close()
var m msg
dec := gob.NewDecoder(conn)
err := dec.Decode(&m)
if err != nil {
log.Fatal("decode error:", err)
}
if m.Action == doGetProjects {
if err := serveProjects(conn); err != nil {
log.Print(err)
}
return
}
proj, ok := projects[m.Project]
if !ok {
log.Print("not a project name: %s \n", m.Project)
return
}
var where *[]string
if m.Where != "" {
where = &[]string{m.Where}
} else {
where = &(proj.Locations)
}
exts := proj.Exts
if len(exts) == 0 {
exts = []string{`\.go`}
}
// TODO(mpl): restore whatever case file was?
switch m.Action {
case regex:
findRegex(m.What, *where, exts, proj.Excluded)
case file:
if !filePathValidator.MatchString(m.What) {
patternTofileName(m.What, *where)
} else {
openFile(m.What, *where, false)
}
default:
println(m.Action, m.What)
}
log.Printf("********")
w.Write("body", []byte(m.What+"\n"))
}
func patternTofileName(what string, where []string) {
// assume it's a class/package/etc name and try to find what's the most usual guess depending on the language
// if no project is set, just go through all of them until there's a match
if globalProj == "" {
for _, v := range projects {
for _, s := range v.Exts {
ext := strings.Replace(s, "\\", "", -1)
err := openFile(what+ext, v.Locations, false)
if err == nil {
return
}
}
}
//TODO: probably remove that case later
} else {
v, ok := projects[globalProj]
if ok {
for _, s := range v.Exts {
ext := strings.Replace(s, "\\", "", -1)
openFile(what+ext, where, false)
}
}
}
}
const exitStatusOne = "exit status 1"
// TODO(mpl): things like "map[string]string" fail, probably need to escape the
// brackets.
// TODO(mpl): follow symlinks?
// TODO(mpl): write to acme win once we replace find and grep with native code
func findRegex(reg string, list []string, exts []string, excl []string) {
findProcMu.Lock()
defer findProcMu.Unlock()
var err error
pr, pw := io.Pipe()
defer pr.Close()
go func() {
nargs := 5
args1 := make([]string, 0, nargs+len(list))
args1 = append(args1, findBin)
args1 = append(args1, list...)
exp := ".*(" + strings.Join(exts, "|") + ")$"
args1 = append(args1, "-regextype", "posix-egrep", "-regex", exp)
if excl != nil {
for _, v := range excl {
args1 = append(args1, "-a", "!", "-regex", v)
}
}
cmd := exec.Command(args1[0], args1[1:]...)
cmd.Stdout = pw
if err := cmd.Run(); err != nil {
log.Fatalf("find failed: %v, %s", err, string(err.(*exec.ExitError).Stderr))
}
pw.Close()
}()
sc := bufio.NewScanner(pr)
var lines []string
var mu sync.Mutex
var wg sync.WaitGroup
for sc.Scan() {
killGrepMu.Lock()
if killGrep {
// TODO(mpl): kill last grep? it's only running over 10 files at max, so kindof ok to let it finish.
lines = nil
// Consume all of pr to let find finish gracefully
if _, err := io.Copy(ioutil.Discard, pr); err != nil {
log.Fatal(err)
}
killGrep = false
killGrepMu.Unlock()
break
}
killGrepMu.Unlock()
// println("LINE: ", sc.Text())
lines = append(lines, sc.Text())
if len(lines) > 9 {
args2 := append([]string{grepBin, "-E", "-n", reg}, lines...)
lines = lines[:0]
mu.Lock()
go func() {
defer mu.Unlock()
wg.Add(1)
defer wg.Done()
cmd := exec.Command(args2[0], args2[1:]...)
out, err := cmd.Output()
if err != nil {
// Because exit status 1 is grep simply didn't find anything.
if !strings.Contains(err.Error(), exitStatusOne) {
// TODO(mpl): be less lazy about that *exec.Error assertion
exitErr, ok := err.(*exec.ExitError)
if !ok {
log.Fatalf("grep call failed (and i was too lazy to record Stderr): %v", err)
}
log.Fatalf("grep failed: %v, %s", err, string(exitErr.Stderr))
}
return
}
fmt.Fprintf(os.Stdout, "%s", string(out))
}()
}
}
wg.Wait()
if err := sc.Err(); err != nil {
log.Fatal(err)
}
if len(lines) <= 0 {
return
}
// TODO(mpl): refactor as func
args2 := append([]string{grepBin, "-E", "-n", reg}, lines...)
cmd := exec.Command(args2[0], args2[1:]...)
out, err := cmd.Output()
if err != nil {
// Because exit status 1 is grep simply didn't find anything.
if !strings.Contains(err.Error(), exitStatusOne) {
log.Fatalf("grep failed: %v, %s", err, string(err.(*exec.ExitError).Stderr))
}
return
}
fmt.Fprintf(os.Stdout, "%s", string(out))
}
func findFile(relPath string, list []string) string {
//in case chording (or voluntary input) gave us a full path already
if relPath[0] == '/' {
return relPath
}
for _, includeDir := range list {
fullPath := path.Join(includeDir, relPath)
_, err := os.Lstat(fullPath)
if err == nil {
return fullPath
} else {
//search for other dirs in current dir
currentDir, err := os.Open(includeDir)
if err != nil {
log.Print(err)
//TODO: do we remove a dir when it's bogus? for now, just ignore it
// apparently it's not ENOENT that we hit. investigate.
continue
}
names, err := currentDir.Readdirnames(-1)
if err != nil {
log.Fatal(err)
}
currentDir.Close()
var fi os.FileInfo
for _, name := range names {
fullPath = path.Join(includeDir, name)
fi, err = os.Lstat(fullPath)
if err != nil {
log.Fatal(err)
}
if fi.IsDir() {
// recurse
temp := findFile(relPath, []string{fullPath})
if temp != "" {
return temp
}
}
}
}
}
return ""
}
func findDir(relPath string, list []string) string {
//in case chording (or voluntary input) gave us a full path already
if relPath[0] == '/' {
return relPath
}
for _, includeDir := range list {
fullPath := path.Join(includeDir, relPath)
_, err := os.Lstat(fullPath)
if err == nil {
return fullPath
} else {
//search for other dirs in current dir
currentDir, err := os.Open(includeDir)
if err != nil {
log.Print(err)
//TODO: do we remove a dir when it's bogus? for now, just ignore it
// apparently it's not ENOENT that we hit. investigate.
continue
}
names, err := currentDir.Readdirnames(-1)
if err != nil {
log.Fatal(err)
}
currentDir.Close()
var fi os.FileInfo
newdir := ""
for _, name := range names {
newdir = path.Join(includeDir, name)
fi, err = os.Lstat(newdir)
if err != nil {
log.Fatal(err)
}
if fi.IsDir() {
fullPath = path.Join(newdir, relPath)
fi, err = os.Lstat(fullPath)
if err == nil {
return fullPath
}
// recurse
temp := findDir(relPath, []string{newdir})
if temp != "" {
return temp
}
}
}
}
}
return ""
}
func openFile(relPath string, list []string, isDir bool) error {
fullPath := ""
if isDir {
fullPath = findDir(relPath, list)
} else {
fullPath = findFile(relPath, list)
}
if fullPath == "" {
return os.ErrNotExist
}
port, err := plumb.Open("send", plan9.OWRITE)
if err != nil {
log.Fatal(err)
}
defer port.Close()
msg := &plumb.Message{
Src: "gofinder",
Dst: "edit",
Dir: "/",
Type: "text",
Data: []byte(fullPath),
}
return msg.Send(port)
}