-
Notifications
You must be signed in to change notification settings - Fork 90
/
watch.go
88 lines (71 loc) · 1.37 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
package main
import (
"fmt"
"strings"
"time"
"github.com/fsnotify/fsnotify"
)
func watch(c config) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
const dir = "./"
if err := watcher.Add(dir); err != nil {
return err
}
interval := 1 * time.Second
tick := time.Tick(interval)
done := make(chan struct{}, 1)
// a buffer for events
var events []fsnotify.Event
var loopErr error
go func() {
Loop:
for {
select {
case event := <-watcher.Events:
if !strings.HasSuffix(event.Name, ".go") {
continue
}
if is(event, fsnotify.Create) || is(event, fsnotify.Write) {
events = append(events, event)
}
case loopErr = <-watcher.Errors:
break Loop
case <-tick:
if len(events) == 0 {
continue
}
// stop watching while gen'ing files
loopErr = watcher.Remove(dir)
if loopErr != nil {
break Loop
}
// gen the files
loopErr = run(c)
if loopErr != nil {
fmt.Fprintln(c.out, loopErr)
}
// clear the buffer
events = make([]fsnotify.Event, 0)
// resume watching
loopErr = watcher.Add(dir)
if loopErr != nil {
break Loop
}
}
}
done <- struct{}{}
}()
<-done
close(done)
if loopErr != nil {
return loopErr
}
return nil
}
func is(event fsnotify.Event, op fsnotify.Op) bool {
return event.Op&op == op
}