-
Notifications
You must be signed in to change notification settings - Fork 0
/
rwatch.go
132 lines (124 loc) · 2.29 KB
/
rwatch.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
package rwatch
import (
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
)
type RecursiveWatcher struct {
root string
watcher *fsnotify.Watcher
Messages chan Message
doneC chan struct{}
subDirs map[string]struct{}
}
func NewRecursiveWatcher(root string) (*RecursiveWatcher, error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
if !filepath.IsAbs(root) {
root, err = filepath.Abs(root)
if err != nil {
return nil, err
}
}
rw := &RecursiveWatcher{
root: root,
watcher: w,
Messages: make(chan Message),
doneC: make(chan struct{}),
subDirs: map[string]struct{}{},
}
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
err = w.Add(path)
if err != nil {
return err
}
rw.subDirs[path] = struct{}{}
}
return nil
})
if err != nil {
return nil, err
}
go rw.run()
return rw, nil
}
func (rw *RecursiveWatcher) Close() {
rw.watcher.Close()
close(rw.Messages)
<-rw.doneC
}
func (rw *RecursiveWatcher) run() {
defer close(rw.doneC)
for {
select {
case e, ok := <-rw.watcher.Events:
if !ok {
return
}
rw.handleMessage(e)
case err, ok := <-rw.watcher.Errors:
if !ok {
return
}
rw.handleError(err, "")
}
}
}
func (rw *RecursiveWatcher) handleError(err error, path string) {
rw.Messages <- Error{
Path: path,
Error: err,
}
}
func (rw *RecursiveWatcher) handleMessage(e fsnotify.Event) {
if e.Op == fsnotify.Remove {
if _, contains := rw.subDirs[e.Name]; contains {
delete(rw.subDirs, e.Name)
rw.Messages <- Deleted{
Path: e.Name,
}
}
return
}
fi, err := os.Stat(e.Name)
if err != nil {
rw.handleError(err, e.Name)
return
}
switch e.Op {
case fsnotify.Create:
rw.Messages <- Created{
Path: e.Name,
File: fi,
}
if fi.IsDir() {
err := rw.watcher.Add(e.Name)
if err != nil {
rw.handleError(err, e.Name)
} else {
rw.subDirs[e.Name] = struct{}{}
}
}
case fsnotify.Write:
rw.Messages <- Changed{
Path: e.Name,
File: fi,
}
case fsnotify.Rename:
rw.Messages <- Renamed{
Path: e.Name,
File: fi,
}
case fsnotify.Chmod:
rw.Messages <- Chmoded{
Path: e.Name,
File: fi,
}
default:
rw.handleError(errors.Errorf("unknown op (%s)", e.Op), "")
}
}