forked from qrtz/livedev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
140 lines (120 loc) · 2.43 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
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
package watcher
import (
"errors"
"log"
"path/filepath"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
)
// Event wraps fsnotify.Event
type Event struct {
fsnotify.Event
}
// Watcher wraps fsnotify.Watcher.
type Watcher struct {
watcher *fsnotify.Watcher
mu sync.RWMutex
watches map[string][]chan<- Event
stop chan struct{}
}
// New creates a new Watcher and begins watching events
func New() (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
w := &Watcher{
watcher: watcher,
watches: make(map[string][]chan<- Event),
stop: make(chan struct{}, 1),
}
go w.run()
return w, nil
}
func (w *Watcher) run() {
for {
select {
case <-w.stop:
return
case event := <-w.watcher.Events:
if event.Op&fsnotify.Chmod != fsnotify.Chmod {
w.notify(Event{event})
}
case err := <-w.watcher.Errors:
log.Println("Watcher error:", err)
}
}
}
func (w *Watcher) notify(e Event) {
w.mu.RLock()
defer w.mu.RUnlock()
p := filepath.Clean(e.Name)
for key, channels := range w.watches {
if strings.HasPrefix(p, key) {
for _, ch := range channels {
go func(c chan<- Event) {
defer func() {
// Catch potential send on closed channel
recover()
}()
select {
case c <- e:
default:
log.Println("Unable to Notify: ", e.Name)
}
}(ch)
}
}
}
}
// Close stops all watches and closes the underlying watcher.
func (w *Watcher) Close() error {
select {
case w.stop <- struct{}{}:
return w.watcher.Close()
default:
return errors.New("Already stopped")
}
}
// Add registers a channel for events on the given path
func (w *Watcher) Add(path string, ch chan<- Event) error {
w.mu.Lock()
defer w.mu.Unlock()
path = filepath.Clean(path)
chs, exists := w.watches[path]
if exists {
for _, c := range chs {
if c == ch {
return nil
}
}
}
err := w.watcher.Add(path)
if err == nil {
w.watches[path] = append(chs, ch)
}
return err
}
// Remove unregisters a channel for events on the given path
func (w *Watcher) Remove(path string, ch chan<- Event) error {
w.mu.Lock()
defer w.mu.Unlock()
path = filepath.Clean(path)
chs, exists := w.watches[path]
if exists {
for i, c := range chs {
if c == ch {
err := w.watcher.Remove(path)
if err == nil {
w.watches[path] = append(chs[0:i], chs[i+1:]...)
}
return err
}
}
if len(chs) == 0 {
delete(w.watches, path)
}
}
return nil
}