-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
78 lines (65 loc) · 1.24 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
package globnotify
import (
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
zglob "github.com/mattn/go-zglob"
"github.com/pilu/treenotify"
)
type Watcher interface {
Watch() (chan fsnotify.Event, error)
Close()
}
type watcher struct {
tw treenotify.Watcher
glob string
events chan fsnotify.Event
stop chan struct{}
}
func New(glob string) (Watcher, error) {
tw, err := treenotify.New()
if err != nil {
return nil, err
}
absGlob, err := filepath.Abs(glob)
if err != nil {
return nil, err
}
return &watcher{
tw: tw,
glob: absGlob,
events: make(chan fsnotify.Event),
stop: make(chan struct{}),
}, nil
}
func root(glob string) string {
parts := strings.Split(glob, "*")
return parts[0]
}
func (w *watcher) Watch() (chan fsnotify.Event, error) {
root := root(w.glob)
events, err := w.tw.Watch(root)
if err != nil {
return nil, err
}
go w.watch(events)
return w.events, nil
}
func (w *watcher) watch(events chan fsnotify.Event) {
working := true
for working {
select {
case <-w.stop:
working = false
case event := <-events:
match, _ := zglob.Match(w.glob, event.Name)
if match {
w.events <- event
}
}
}
}
func (w *watcher) Close() {
w.stop <- struct{}{}
w.tw.Close()
}