-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
63 lines (54 loc) · 1.13 KB
/
watcher.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
package watcher
import (
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
func addRecursiveWatch(watcher *fsnotify.Watcher, rootPath string) error {
err := watcher.Add(rootPath)
if err != nil {
return err
}
return filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err == nil && info.Mode().IsDir() {
err = watcher.Add(path)
}
return err
})
}
func startWatching(watcher *fsnotify.Watcher, stop <-chan bool, observeEvent func(interface{})) {
go func() {
for {
select {
case <-stop:
return
case event, ok := <-watcher.Events:
if !ok {
return
}
observeEvent(event)
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
}
func Watch(stop <-chan bool, done chan<- bool, observeEvent func(interface{})) {
watcher, err := fsnotify.NewWatcher()
var workerDir string
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
startWatching(watcher, stop, observeEvent)
workerDir, _ = os.Getwd()
err = addRecursiveWatch(watcher, workerDir)
if err != nil {
log.Fatal(err)
}
done <- true
}