Uh oh!
There was an error while loading. Please reload this page.
forked from radovskyb/watcher
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwatcher.go
More file actions
Latest commit
703 lines (605 loc) · 15.1 KB
/
Copy pathwatcher.go
File metadata and controls
703 lines (605 loc) · 15.1 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
package watcher
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
)
var (
// ErrDurationTooShort occurs when calling the watcher's Start
// method with a duration that's less than 1 nanosecond.
ErrDurationTooShort=errors.New("error: duration is less than 1ns")
// ErrWatcherRunning occurs when trying to call the watcher's
// Start method and the polling cycle is still already running
// from previously calling Start and not yet calling Close.
ErrWatcherRunning=errors.New("error: watcher is already running")
// ErrWatchedFileDeleted is an error that occurs when a file or folder that was
// being watched has been deleted.
ErrWatchedFileDeleted=errors.New("error: watched file or folder deleted")
// ErrSkip is less of an error, but more of a way for path hooks to skip a file or
// directory.
ErrSkip=errors.New("error: skipping file")
)
// An Op is a type that is used to describe what type
// of event has occurred during the watching process.
typeOpuint32
// Ops
const (
CreateOp=iota
Write
Remove
Rename
Chmod
Move
)
varops=map[Op]string{
Create: "CREATE",
Write: "WRITE",
Remove: "REMOVE",
Rename: "RENAME",
Chmod: "CHMOD",
Move: "MOVE",
}
// String prints the string version of the Op consts
func (eOp) String() string {
ifop, found:=ops[e]; found {
returnop
}
return"???"
}
// An Event describes an event that is received when files or directory
// changes occur. It includes the os.FileInfo of the changed file or
// directory and the type of event that's occurred and the full path of the file.
typeEventstruct {
Op
Pathstring
os.FileInfo
}
// String returns a string depending on what type of event occurred and the
// file name associated with the event.
func (eEvent) String() string {
ife.FileInfo==nil {
return"???"
}
pathType:="FILE"
ife.IsDir() {
pathType="DIRECTORY"
}
returnfmt.Sprintf("%s %q %s [%s]", pathType, e.Name(), e.Op, e.Path)
}
// FilterFileHookFunc is a function that is called to filter files during listings.
// If a file is ok to be listed, nil is returned otherwise ErrSkip is returned.
typeFilterFileHookFuncfunc(info os.FileInfo, fullPathstring) error
// RegexFilterHook is a function that accepts or rejects a file
// for listing based on whether it's filename or full path matches
// a regular expression.
funcRegexFilterHook(r*regexp.Regexp, useFullPathbool) FilterFileHookFunc {
returnfunc(info os.FileInfo, fullPathstring) error {
str:=info.Name()
ifuseFullPath {
str=fullPath
}
// Match
ifr.MatchString(str) {
returnnil
}
// No match.
returnErrSkip
}
}
// Watcher describes a process that watches files for changes.
typeWatcherstruct {
EventchanEvent
Errorchanerror
Closedchanstruct{}
closechanstruct{}
wg*sync.WaitGroup
// mu protects the following.
mu*sync.Mutex
ffh []FilterFileHookFunc
runningbool
namesmap[string]bool// bool for recursive or not.
filesmap[string]os.FileInfo// map of files.
ignoredmap[string]struct{} // ignored files or directories.
opsmap[Op]struct{} // Op filtering.
ignoreHiddenbool// ignore hidden files or not.
maxEventsint// max sent events per cycle
}
// New creates a new Watcher.
funcNew() *Watcher {
// Set up the WaitGroup for w.Wait().
varwg sync.WaitGroup
wg.Add(1)
return&Watcher{
Event: make(chanEvent),
Error: make(chanerror),
Closed: make(chanstruct{}),
close: make(chanstruct{}),
mu: new(sync.Mutex),
wg: &wg,
files: make(map[string]os.FileInfo),
ignored: make(map[string]struct{}),
names: make(map[string]bool),
}
}
// SetMaxEvents controls the maximum amount of events that are sent on
// the Event channel per watching cycle. If max events is less than 1, there is
// no limit, which is the default.
func (w*Watcher) SetMaxEvents(deltaint) {
w.mu.Lock()
w.maxEvents=delta
w.mu.Unlock()
}
// AddFilterHook
func (w*Watcher) AddFilterHook(fFilterFileHookFunc) {
w.mu.Lock()
w.ffh=append(w.ffh, f)
w.mu.Unlock()
}
// IgnoreHiddenFiles sets the watcher to ignore any file or directory
// that starts with a dot.
func (w*Watcher) IgnoreHiddenFiles(ignorebool) {
w.mu.Lock()
w.ignoreHidden=ignore
w.mu.Unlock()
}
// FilterOps filters which event op types should be returned
// when an event occurs.
func (w*Watcher) FilterOps(ops...Op) {
w.mu.Lock()
w.ops=make(map[Op]struct{})
for_, op:=rangeops {
w.ops[op] =struct{}{}
}
w.mu.Unlock()
}
// Add adds either a single file or directory to the file list.
func (w*Watcher) Add(namestring) (errerror) {
w.mu.Lock()
deferw.mu.Unlock()
name, err=filepath.Abs(name)
iferr!=nil {
returnerr
}
// If name is on the ignored list or if hidden files are
// ignored and name is a hidden file or directory, simply return.
_, ignored:=w.ignored[name]
isHidden, err:=isHiddenFile(name)
iferr!=nil {
returnerr
}
ifignored|| (w.ignoreHidden&&isHidden) {
returnnil
}
// Add the directory's contents to the files list.
fileList, err:=w.list(name)
iferr!=nil {
returnerr
}
fork, v:=rangefileList {
w.files[k] =v
}
// Add the name to the names list.
w.names[name] =false
returnnil
}
func (w*Watcher) list(namestring) (map[string]os.FileInfo, error) {
fileList:=make(map[string]os.FileInfo)
// Make sure name exists.
stat, err:=os.Stat(name)
iferr!=nil {
returnnil, err
}
fileList[name] =stat
// If it's not a directory, just return.
if!stat.IsDir() {
returnfileList, nil
}
// It's a directory.
fInfoList, err:=ioutil.ReadDir(name)
iferr!=nil {
returnnil, err
}
// Add all of the files in the directory to the file list as long
// as they aren't on the ignored list or are hidden files if ignoreHidden
// is set to true.
outer:
for_, fInfo:=rangefInfoList {
path:=filepath.Join(name, fInfo.Name())
_, ignored:=w.ignored[path]
isHidden, err:=isHiddenFile(path)
iferr!=nil {
returnnil, err
}
ifignored|| (w.ignoreHidden&&isHidden) {
continue
}
for_, f:=rangew.ffh {
err:=f(fInfo, path)
iferr==ErrSkip {
continue outer
}
iferr!=nil {
returnnil, err
}
}
fileList[path] =fInfo
}
returnfileList, nil
}
// AddRecursive adds either a single file or directory recursively to the file list.
func (w*Watcher) AddRecursive(namestring) (errerror) {
w.mu.Lock()
deferw.mu.Unlock()
name, err=filepath.Abs(name)
iferr!=nil {
returnerr
}
fileList, err:=w.listRecursive(name)
iferr!=nil {
returnerr
}
fork, v:=rangefileList {
w.files[k] =v
}
// Add the name to the names list.
w.names[name] =true
returnnil
}
func (w*Watcher) listRecursive(namestring) (map[string]os.FileInfo, error) {
fileList:=make(map[string]os.FileInfo)
returnfileList, filepath.Walk(name, func(pathstring, info os.FileInfo, errerror) error {
iferr!=nil {
returnerr
}
for_, f:=rangew.ffh {
err:=f(info, path)
iferr==ErrSkip {
returnnil
}
iferr!=nil {
returnerr
}
}
// If path is ignored and it's a directory, skip the directory. If it's
// ignored and it's a single file, skip the file.
_, ignored:=w.ignored[path]
isHidden, err:=isHiddenFile(path)
iferr!=nil {
returnerr
}
ifignored|| (w.ignoreHidden&&isHidden) {
ifinfo.IsDir() {
returnfilepath.SkipDir
}
returnnil
}
// Add the path and it's info to the file list.
fileList[path] =info
returnnil
})
}
// Remove removes either a single file or directory from the file's list.
func (w*Watcher) Remove(namestring) (errerror) {
w.mu.Lock()
deferw.mu.Unlock()
name, err=filepath.Abs(name)
iferr!=nil {
returnerr
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found:=w.files[name]
if!found {
returnnil// Doesn't exist, just return.
}
if!info.IsDir() {
delete(w.files, name)
returnnil
}
// Delete the actual directory from w.files
delete(w.files, name)
// If it's a directory, delete all of it's contents from w.files.
forpath:=rangew.files {
iffilepath.Dir(path) ==name {
delete(w.files, path)
}
}
returnnil
}
// RemoveRecursive removes either a single file or a directory recursively from
// the file's list.
func (w*Watcher) RemoveRecursive(namestring) (errerror) {
w.mu.Lock()
deferw.mu.Unlock()
name, err=filepath.Abs(name)
iferr!=nil {
returnerr
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found:=w.files[name]
if!found {
returnnil// Doesn't exist, just return.
}
if!info.IsDir() {
delete(w.files, name)
returnnil
}
// If it's a directory, delete all of it's contents recursively
// from w.files.
forpath:=rangew.files {
ifstrings.HasPrefix(path, name) {
delete(w.files, path)
}
}
returnnil
}
// Ignore adds paths that should be ignored.
//
// For files that are already added, Ignore removes them.
func (w*Watcher) Ignore(paths...string) (errerror) {
for_, path:=rangepaths {
path, err=filepath.Abs(path)
iferr!=nil {
returnerr
}
// Remove any of the paths that were already added.
iferr:=w.RemoveRecursive(path); err!=nil {
returnerr
}
w.mu.Lock()
w.ignored[path] =struct{}{}
w.mu.Unlock()
}
returnnil
}
// WatchedFiles returns a map of files added to a Watcher.
func (w*Watcher) WatchedFiles() map[string]os.FileInfo {
w.mu.Lock()
deferw.mu.Unlock()
files:=make(map[string]os.FileInfo)
fork, v:=rangew.files {
files[k] =v
}
returnfiles
}
// fileInfo is an implementation of os.FileInfo that can be used
// as a mocked os.FileInfo when triggering an event when the specified
// os.FileInfo is nil.
typefileInfostruct {
namestring
sizeint64
mode os.FileMode
modTime time.Time
sysinterface{}
dirbool
}
func (fs*fileInfo) IsDir() bool {
returnfs.dir
}
func (fs*fileInfo) ModTime() time.Time {
returnfs.modTime
}
func (fs*fileInfo) Mode() os.FileMode {
returnfs.mode
}
func (fs*fileInfo) Name() string {
returnfs.name
}
func (fs*fileInfo) Size() int64 {
returnfs.size
}
func (fs*fileInfo) Sys() interface{} {
returnfs.sys
}
// TriggerEvent is a method that can be used to trigger an event, separate to
// the file watching process.
func (w*Watcher) TriggerEvent(eventTypeOp, file os.FileInfo) {
w.Wait()
iffile==nil {
file=&fileInfo{name: "triggered event", modTime: time.Now()}
}
w.Event<-Event{Op: eventType, Path: "-", FileInfo: file}
}
func (w*Watcher) retrieveFileList() map[string]os.FileInfo {
w.mu.Lock()
deferw.mu.Unlock()
fileList:=make(map[string]os.FileInfo)
varlistmap[string]os.FileInfo
varerrerror
forname, recursive:=rangew.names {
ifrecursive {
list, err=w.listRecursive(name)
iferr!=nil {
ifos.IsNotExist(err) {
w.Error<-ErrWatchedFileDeleted
} else {
w.Error<-err
}
}
} else {
list, err=w.list(name)
iferr!=nil {
ifos.IsNotExist(err) {
w.Error<-ErrWatchedFileDeleted
} else {
w.Error<-err
}
}
}
// Add the file's to the file list.
fork, v:=rangelist {
fileList[k] =v
}
}
returnfileList
}
// Start begins the polling cycle which repeats every specified
// duration until Close is called.
func (w*Watcher) Start(d time.Duration) error {
// Return an error if d is less than 1 nanosecond.
ifd<time.Nanosecond {
returnErrDurationTooShort
}
// Make sure the Watcher is not already running.
w.mu.Lock()
ifw.running {
w.mu.Unlock()
returnErrWatcherRunning
}
w.running=true
w.mu.Unlock()
// Unblock w.Wait().
w.wg.Done()
for {
// done lets the inner polling cycle loop know when the
// current cycle's method has finished executing.
done:=make(chanstruct{})
// Any events that are found are first piped to evt before
// being sent to the main Event channel.
evt:=make(chanEvent)
// Retrieve the file list for all watched file's and dirs.
fileList:=w.retrieveFileList()
// cancel can be used to cancel the current event polling function.
cancel:=make(chanstruct{})
// Look for events.
gofunc() {
w.pollEvents(fileList, evt, cancel)
done<-struct{}{}
}()
// numEvents holds the number of events for the current cycle.
numEvents:=0
inner:
for {
select {
case<-w.close:
close(cancel)
close(w.Closed)
returnnil
caseevent:=<-evt:
iflen(w.ops) >0 { // Filter Ops.
_, found:=w.ops[event.Op]
if!found {
continue
}
}
numEvents++
ifw.maxEvents>0&&numEvents>w.maxEvents {
close(cancel)
break inner
}
w.Event<-event
case<-done: // Current cycle is finished.
break inner
}
}
// Update the file's list.
w.mu.Lock()
w.files=fileList
w.mu.Unlock()
// Sleep and then continue to the next loop iteration.
time.Sleep(d)
}
}
func (w*Watcher) pollEvents(filesmap[string]os.FileInfo, evtchanEvent,
cancelchanstruct{}) {
w.mu.Lock()
deferw.mu.Unlock()
// Store create and remove events for use to check for rename events.
creates:=make(map[string]os.FileInfo)
removes:=make(map[string]os.FileInfo)
// Check for removed files.
forpath, info:=rangew.files {
if_, found:=files[path]; !found {
removes[path] =info
}
}
// Check for created files, writes and chmods.
forpath, info:=rangefiles {
oldInfo, found:=w.files[path]
if!found {
// A file was created.
creates[path] =info
continue
}
ifoldInfo.ModTime() !=info.ModTime() {
select {
case<-cancel:
return
caseevt<-Event{Write, path, info}:
}
}
ifoldInfo.Mode() !=info.Mode() {
select {
case<-cancel:
return
caseevt<-Event{Chmod, path, info}:
}
}
}
// Check for renames and moves.
forpath1, info1:=rangeremoves {
forpath2, info2:=rangecreates {
ifsameFile(info1, info2) {
e:=Event{
Op: Move,
Path: fmt.Sprintf("%s -> %s", path1, path2),
FileInfo: info1,
}
// If they are from the same directory, it's a rename
// instead of a move event.
iffilepath.Dir(path1) ==filepath.Dir(path2) {
e.Op=Rename
}
delete(removes, path1)
delete(creates, path2)
select {
case<-cancel:
return
caseevt<-e:
}
}
}
}
// Send all the remaining create and remove events.
forpath, info:=rangecreates {
select {
case<-cancel:
return
caseevt<-Event{Create, path, info}:
}
}
forpath, info:=rangeremoves {
select {
case<-cancel:
return
caseevt<-Event{Remove, path, info}:
}
}
}
// Wait blocks until the watcher is started.
func (w*Watcher) Wait() {
w.wg.Wait()
}
// Close stops a Watcher and unlocks its mutex, then sends a close signal.
func (w*Watcher) Close() {
w.mu.Lock()
if!w.running {
w.mu.Unlock()
return
}
w.running=false
w.files=make(map[string]os.FileInfo)
w.names=make(map[string]bool)
w.mu.Unlock()
// Send a close signal to the Start method.
w.close<-struct{}{}
}