-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
464 lines (348 loc) · 9.56 KB
/
watch.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//watch handles reloading of a command by watching a directory and if supplied a set of given extensions for change
package main
import (
"bytes"
"flag"
"fmt"
"go/build"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/howeyc/fsnotify"
)
var multispaces = regexp.MustCompile(`\s+`)
func goDeps(targetdir string) (bool, error) {
cmdline := []string{"go", "get"}
cmdline = append(cmdline, targetdir)
//setup the executor and use a shard buffer
cmd := exec.Command("go", cmdline[1:]...)
buf := bytes.NewBuffer([]byte{})
cmd.Stdout = buf
cmd.Stderr = buf
err := cmd.Run()
if buf.Len() > 0 {
return false, fmt.Errorf("go get failed: %s: %s", buf.String(), err.Error())
}
return true, nil
}
//goRun runs the runs a command
func goRun(cmd string) string {
var cmdline []string
com := strings.Split(cmd, " ")
if len(com) < 0 {
return ""
}
if len(com) == 1 {
cmdline = append(cmdline, com...)
} else {
cmdline = append(cmdline, com[0])
cmdline = append(cmdline, com[1:]...)
}
//setup the executor and use a shard buffer
cmdo := exec.Command(cmdline[0], cmdline[1:]...)
buf := bytes.NewBuffer([]byte{})
cmdo.Stdout = buf
cmdo.Stderr = buf
_ = cmdo.Run()
return buf.String()
}
//gobuild runs the build process and returns true/false and an error
func gobuild(dir, name string) (bool, error) {
cmdline := []string{"go", "build"}
if runtime.GOOS == "windows" {
name = fmt.Sprintf("%s.exe", name)
}
target := filepath.Join(dir, name)
cmdline = append(cmdline, "-o", target)
//setup the executor and use a shard buffer
cmd := exec.Command("go", cmdline[1:]...)
buf := bytes.NewBuffer([]byte{})
cmd.Stdout = buf
cmd.Stderr = buf
err := cmd.Run()
if buf.Len() > 0 {
return false, fmt.Errorf("go build failed: %s: %s", buf.String(), err.Error())
}
return true, nil
}
// runBin runs the generated bin file with the arguments expected
func runBin(bindir, bin string, args []string) chan bool {
var relunch = make(chan bool)
go func() {
binfile := fmt.Sprintf("%s/%s", bindir, bin)
// cmdline := append([]string{bin}, args...)
var proc *os.Process
for dosig := range relunch {
if proc != nil {
if err := proc.Signal(os.Interrupt); err != nil {
log.Printf("Error in sending signal %s", err)
proc.Kill()
}
proc.Wait()
}
if !dosig {
continue
}
cmd := exec.Command(binfile, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Printf("Error starting process: %s", err)
}
proc = cmd.Process
}
}()
return relunch
}
func buildPkgWatcher(pkpath string, assets map[string]bool) (*fsnotify.Watcher, error) {
ws, err := fsnotify.NewWatcher()
add2Watcher(ws, pkpath, assets)
return ws, err
}
func buildWatcher(pkpath string) (*fsnotify.Watcher, error) {
ws, err := fsnotify.NewWatcher()
ws.Watch(pkpath)
return ws, err
}
func hasIn(paths []string, dt string) bool {
for _, so := range paths {
if strings.Contains(so, dt) || so == dt {
return true
}
}
return false
}
func watchDir(ws *fsnotify.Watcher, dir string, assets map[string]bool, skip []string) {
mo, err := os.Stat(dir)
if err != nil {
return
}
if !mo.IsDir() {
return
}
filepath.Walk(filepath.ToSlash(dir), func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".git") {
return nil
}
if info == nil {
return nil
}
if hasIn(skip, path) {
return nil
}
// log.Printf("adding: %s", path)
// if !info.IsDir() {
// return nil
// }
if assets[path] {
return nil
}
ws.Watch(path)
assets[path] = true
return nil
})
}
func add2Watcher(ws *fsnotify.Watcher, pkgpath string, assets map[string]bool) {
pkg, err := build.Import(pkgpath, "", 0)
if err != nil {
log.Printf("Import path watch error %s", err.Error())
return
}
if pkg.Goroot {
return
}
ws.Watch(pkg.Dir)
assets[pkgpath] = true
for _, imp := range pkg.Imports {
if !assets[imp] {
add2Watcher(ws, imp, assets)
}
}
}
func watch(command, importable, bin, exts string, dobuild, watchbuild, withdir bool, args []string) error {
log.Printf("Command: %s %s %s %t", command, importable, bin, dobuild)
extcls := multispaces.ReplaceAllString(exts, " ")
extens := multispaces.Split(extcls, -1)
if len(extens) == 1 && extens[0] == "" {
extens = extens[:0]
}
var buildName string
var ubin string
var buildHandler = func() error {
var pkgs *build.Package
var err error
pkgs, err = build.Import(importable, "", 0)
if err != nil {
return err
}
_, buildName = path.Split(pkgs.ImportPath)
// _, buildName := path.Split("./")
wd, _ := os.Getwd()
if bin != "" {
ubin = filepath.ToSlash(filepath.Join(wd, bin))
} else {
ubin = pkgs.BinDir
}
// lets install
_, err = goDeps("./")
if err != nil {
log.Printf("go.install.err: %s", err.Error())
// return err
}
log.Printf("Building Pkg %s \nBin: %s \nUsing name: %s", pkgs.ImportPath, ubin, buildName)
done, err := gobuild(ubin, buildName)
if err != nil {
return err
}
_ = done
return nil
}
var buildWatch = func() (*fsnotify.Watcher, error) {
var err error
var watch *fsnotify.Watcher
added := make(map[string]bool)
if watchbuild {
log.Printf("Watch import Path enabled")
watch, err = buildPkgWatcher(importable, added)
} else {
if !added["./"] {
watch, err = buildWatcher("./")
}
}
//lets watch the current directory also if allowed
if withdir && err == nil {
wod, ex := os.Getwd()
if ex == nil && wod != "" {
watchDir(watch, wod, added, []string{ubin})
}
}
return watch, err
}
var err error
var watch *fsnotify.Watcher
var binRun bool
var binChan chan bool
//lets build if we are allowed
if dobuild {
if err = buildHandler(); err != nil {
return err
}
binChan = runBin(ubin, buildName, args)
binRun = true
binChan <- true
}
log.Printf("Building dir watchers.....")
watch, err = buildWatch()
if err != nil {
log.Printf("Unable to build err %s", err.Error())
return err
}
for {
//should we watch
we, _ := <-watch.Event
exo := filepath.Ext(we.Name)
//if its a .git directory skip it
if strings.Contains(filepath.ToSlash(we.Name), ".git") {
continue
}
//if its our bin directory skip it
if filepath.ToSlash(we.Name) == filepath.ToSlash(ubin) {
continue
}
log.Printf("Watch: %s -> %s with extensions: %s", exo, we.Name, extens)
if len(extens) > 0 {
var found bool
for _, mo := range extens {
if exo == mo {
found = true
break
}
}
if !found {
continue
}
}
log.Printf("Watcher notified change: %s", we.Name)
watch.Close()
go func(evs chan *fsnotify.FileEvent) {
for _ = range evs {
}
}(watch.Event)
log.Printf("Re-initiating watch scans .....")
if command != "" {
log.Printf("Running cmd '%s' with result: '%s'", command, goRun(command))
}
if dobuild {
if err = buildHandler(); err != nil {
return err
}
if binRun {
binChan <- true
}
}
watch, err = buildWatch()
if err != nil {
return err
}
go func(errors chan error) {
for _ = range errors {
}
}(watch.Error)
}
}
func usage() {
fmt.Printf(`
About: provides a simple but combined go dir builder and file watcher
Version: %s
Usage: watch [--import] <import path> [--cmd] <cmd_to_rerun>
[--ext] <extensions> [--bin] <bin path to store> --dir --nobin
Parameter Explantions:
--ext: a space seperated string of extensions to watch
--cmd : Command to run instead on every change
--withdir: This sets the current directories and subdirectories to be watched
--bindir: The build directory for storing the build file
--importdir: Command to run instead on every change")
--nobin: sets the watcher to watch for changes in the package import path and in the current directory without building a binary file for running
Examples:
- Build project directory on any change:
watch --import github.com/influx6/todo
- Watch project directory import (and the current directory) path only without building for changes then run a command:
watch --import github.com/influx6/todo --dir --cmd "gopherjs build" --nobin
- Build project directory and subdirectories files on any change:
watch --import github.com/influx6/todo --dir
- Run command on any change within current directory
watch --cmd "echo 'dude'"
- Build project directory on any change,run command and only watch files in extensions:
watch --import github.com/influx6/todo --cmd "echo 'dude'" --ext ".go .tmpl .js"
`, version)
}
var version = "0.0.2"
func main() {
exts := flag.String("ext", "", "a space seperated string of extensions to watch")
cmd := flag.String("cmd", "", "Command to run instead on every change")
withdir := flag.Bool("dir", false, "This sets the current directories and subdirectories to be watched")
bindir := flag.String("bin", "./bin", "The build directory for storing the build file")
importdir := flag.String("import", "", "Command to run instead on every change")
nobin := flag.Bool("nobin", false, "This sets the watcher to watch for files in the package giving in the import option and in the current directory without building a binary file for running")
flag.Parse()
flag.Usage = usage
if *cmd == "" && *importdir == "" {
// flag.PrintDefaults()
usage()
return
}
build := (*importdir != "" && !(*nobin))
watchbuild := (*importdir != "")
if watchbuild {
log.Printf("Import build path: %s", *importdir)
}
err := watch(*cmd, *importdir, *bindir, *exts, build, watchbuild, *withdir, flag.Args())
if err != nil {
log.Printf("Errored: %s", err.Error())
}
}