forked from go-godo/godo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
304 lines (273 loc) · 6.7 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package fswatch
import (
"os"
"path/filepath"
"strings"
"time"
"github.com/mgutz/str"
)
// Watcher represents a file system watcher. It should be initialised
// with NewWatcher or NewAutoWatcher, and started with Watcher.Start().
type Watcher struct {
paths map[string]*watchItem
cnotify chan *Notification
cadd chan *watchItem
autoWatch bool
// ignoreFn is used to ignore paths
IgnorePathFn func(path string) bool
}
// newWatcher is the internal function for properly setting up a new watcher.
func newWatcher(dirNotify bool, initpaths ...string) (w *Watcher) {
w = new(Watcher)
w.autoWatch = dirNotify
w.paths = make(map[string]*watchItem, 0)
w.IgnorePathFn = ignorePathDefault
var paths []string
for _, path := range initpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if dirNotify {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
return
}
// NewWatcher initialises a new Watcher with an initial set of paths. It
// does not start listening, and this Watcher will not automatically add
// files created under any directories it is watching.
func NewWatcher(paths ...string) *Watcher {
return newWatcher(false, paths...)
}
// NewAutoWatcher initialises a new Watcher with an initial set of paths.
// It behaves the same as NewWatcher, except it will automatically add
// files created in directories it is watching, including adding any
// subdirectories.
func NewAutoWatcher(paths ...string) *Watcher {
return newWatcher(true, paths...)
}
// Start begins watching the files, sending notifications when files change.
// It returns a channel that notifications are sent on.
func (w *Watcher) Start() <-chan *Notification {
if w.cnotify != nil {
return w.cnotify
}
if w.autoWatch {
w.cadd = make(chan *watchItem, NotificationBufLen)
go w.watchItemListener()
}
w.cnotify = make(chan *Notification, NotificationBufLen)
go w.watch(w.cnotify)
return w.cnotify
}
// Stop listening for changes to the files.
func (w *Watcher) Stop() {
if w.cnotify != nil {
close(w.cnotify)
}
if w.cadd != nil {
close(w.cadd)
}
}
// Active returns true if the Watcher is actively looking for changes.
func (w *Watcher) Active() bool {
return w.paths != nil && len(w.paths) > 0
}
// Add method takes a variable number of string arguments and adds those
// files to the watch list, returning the number of files added.
func (w *Watcher) Add(inpaths ...string) {
var paths []string
for _, path := range inpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if w.autoWatch && w.cnotify != nil {
for _, path := range paths {
wi := watchPath(path)
w.addPaths(wi)
}
} else if w.autoWatch {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
}
// goroutine that cycles through the list of paths and checks for updates.
func (w *Watcher) watch(sndch chan<- *Notification) {
defer func() {
recover()
}()
for {
//fmt.Printf("updating watch info %s\n", time.Now())
<-time.After(WatchDelay)
for _, wi := range w.paths {
//fmt.Printf("cheecking %#v\n", wi.Path)
if wi.Update() && w.shouldNotify(wi) {
sndch <- wi.Notification()
}
if wi.LastEvent == NOEXIST && w.autoWatch {
delete(w.paths, wi.Path)
}
if len(w.paths) == 0 {
w.Stop()
}
// if filepath.Base(wi.Path) == "sub1.txt" {
// fmt.Printf("%s\n", wi.Path)
// }
}
}
}
func (w *Watcher) shouldNotify(wi *watchItem) bool {
if w.autoWatch && wi.StatInfo.IsDir() &&
!(wi.LastEvent == DELETED || wi.LastEvent == NOEXIST) {
go w.addPaths(wi)
return false
}
return true
}
func (w *Watcher) addPaths(wi *watchItem) {
walker := getWalker(w, wi.Path, w.cadd)
go filepath.Walk(wi.Path, walker)
}
func (w *Watcher) watchItemListener() {
defer func() {
recover()
}()
for {
wi := <-w.cadd
if wi == nil {
continue
} else if _, watching := w.paths[wi.Path]; watching {
continue
}
w.paths[wi.Path] = wi
}
}
func getWalker(w *Watcher, root string, addch chan<- *watchItem) func(string, os.FileInfo, error) error {
walker := func(path string, info os.FileInfo, err error) error {
if w.IgnorePathFn(path) {
if info.IsDir() {
//fmt.Println("SKIPPING dir", path)
return filepath.SkipDir
}
return nil
}
if err != nil {
return err
}
if path == root {
return nil
}
wi := watchPath(path)
if wi == nil {
return nil
} else if _, watching := w.paths[wi.Path]; !watching {
wi.LastEvent = CREATED
w.cnotify <- wi.Notification()
addch <- wi
if !wi.StatInfo.IsDir() {
return nil
}
w.addPaths(wi)
}
return nil
}
return walker
}
// DefaultIsIgnorePath checks whether a path is ignored. Currently defaults
// to hidden files on *nix systems, ie they start with a ".".
func ignorePathDefault(path string) bool {
if strings.HasPrefix(path, ".") || strings.Contains(path, "/.") {
return true
}
// ignore node
if strings.HasPrefix(path, "node_modules") || strings.Contains(path, "/node_modules") {
return true
}
// vim creates random numeric files
base := filepath.Base(path)
if str.IsNumeric(base) {
return true
}
return false
}
func (w *Watcher) syncAddPaths(paths ...string) {
for _, path := range paths {
if w.IgnorePathFn(path) {
//fmt.Println("SKIPPING path", path)
continue
}
wi := watchPath(path)
if wi == nil {
continue
} else if wi.LastEvent == NOEXIST {
continue
} else if _, watching := w.paths[wi.Path]; watching {
continue
}
w.paths[wi.Path] = wi
if wi.StatInfo.IsDir() {
w.syncAddDir(wi)
}
}
}
func (w *Watcher) syncAddDir(wi *watchItem) {
walker := func(path string, info os.FileInfo, err error) error {
if w.IgnorePathFn(path) {
if info.IsDir() {
//fmt.Println("SKIPPING dir", path)
return filepath.SkipDir
}
return nil
}
if err != nil {
return err
}
if path == wi.Path {
return nil
}
newWI := watchPath(path)
if newWI != nil {
w.paths[path] = newWI
if !newWI.StatInfo.IsDir() {
return nil
}
if _, watching := w.paths[newWI.Path]; !watching {
w.syncAddDir(newWI)
}
}
return nil
}
filepath.Walk(wi.Path, walker)
}
// Watching returns a list of the files being watched.
func (w *Watcher) Watching() (paths []string) {
paths = make([]string, 0)
for path := range w.paths {
paths = append(paths, path)
}
return
}
// State returns a slice of Notifications representing the files being watched
// and their last event.
func (w *Watcher) State() (state []Notification) {
state = make([]Notification, 0)
if w.paths == nil {
return
}
for _, wi := range w.paths {
state = append(state, *wi.Notification())
}
return
}