-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
82 lines (66 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package watch
import (
"path/filepath"
"sync"
"github.com/amitybell/srcvox/errs"
"github.com/amitybell/srcvox/logs"
"github.com/fsnotify/fsnotify"
)
type Event struct {
fsnotify.Event
}
var (
Logs = logs.AppLogger()
watch = struct {
sync.Mutex
fsw *fsnotify.Watcher
seen map[string]bool
notify []func(ev Event)
}{
seen: map[string]bool{},
}
)
func Path(fn string) error {
fn = filepath.Clean(fn)
watch.Lock()
defer watch.Unlock()
if watch.seen[fn] {
return nil
}
watch.seen[fn] = true
if watch.fsw == nil {
fsw, err := fsnotify.NewWatcher()
if err != nil {
return err
}
watch.fsw = fsw
go watchNotifier(fsw)
}
return watch.fsw.Add(fn)
}
func watchNotify(ev Event, f func(Event)) {
defer func() {
var err error
errs.Recover(&err)
if err != nil {
Logs.Println("Watch.Notify PANIC:", err)
}
}()
f(ev)
}
func watchNotifier(fsw *fsnotify.Watcher) {
for e := range fsw.Events {
ev := Event{Event: e}
watch.Lock()
notify := watch.notify
watch.Unlock()
for _, f := range notify {
go watchNotify(ev, f)
}
}
}
func Notify(f func(ev Event)) {
watch.Lock()
defer watch.Unlock()
watch.notify = append(watch.notify[:len(watch.notify):len(watch.notify)], f)
}