-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathwatcher.go
62 lines (51 loc) · 1.09 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
// +build !darwin
package main
import (
"fmt"
"log"
"github.com/fsnotify/fsnotify"
)
// newWatcher returns a new file watcher.
func newWatcher() (*watcher, error) {
fsw, err := fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("creating FS watcher: %s", err)
}
w := &watcher{
watcher: fsw,
changes: make(chan struct{}, 100),
}
go func() {
for err := range fsw.Errors {
log.Println("fswatch error:", err)
}
}()
go func() {
for event := range fsw.Events {
if event.Op&fsnotify.Write == fsnotify.Write {
w.changes <- struct{}{}
}
}
}()
return w, nil
}
// watcher watches files for changes.
// changes are signaled via the "changes" channel.
// errors are logged.
type watcher struct {
watcher *fsnotify.Watcher
changes chan struct{}
watching []string
}
// Watch watches a file for changes.
func (w *watcher) Watch(file string) {
w.watching = append(w.watching, file)
w.watcher.Add(file)
}
// StopWatchingAll stops watching all files.
func (w *watcher) StopWatchingAll() {
for _, f := range w.watching {
w.watcher.Remove(f)
}
w.watching = nil
}