/
watch.go
65 lines (58 loc) · 1.21 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
package priest
import (
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
"io/ioutil"
"path/filepath"
)
func doWatch(fn func(string, string, fsnotify.Op), scanDirs []string) {
watch(func(event fsnotify.Event) {
if event.Op&fsnotify.Write == fsnotify.Write || event.Op == fsnotify.Remove {
if filepath.Ext(event.Name) == ".go" {
fn(filepath.Dir(event.Name), event.Name, event.Op)
}
}
}, scanDirs)
}
func watch(fn func(event fsnotify.Event), dirs []string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
fn(event)
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Error("error:", err)
}
}
}()
for _, dir := range dirs {
watchRecursively(watcher, dir)
}
<-done
}
func watchRecursively(watcher *fsnotify.Watcher, dir string) {
log.Info("watch ", dir)
err := watcher.Add(dir)
if err != nil {
log.Error(err)
return
}
dirs, _ := ioutil.ReadDir(dir)
for i := range dirs {
if dirs[i].IsDir() {
watchRecursively(watcher, filepath.Join(dir, dirs[i].Name()))
}
}
}