-
Notifications
You must be signed in to change notification settings - Fork 5
/
filewatcher.go
115 lines (96 loc) · 1.89 KB
/
filewatcher.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
package gonotify
import (
"context"
"path/filepath"
"sync"
)
// FileWatcher waits for events generated by filesystem for a specific list of file paths, including
// IN_CREATE for not yet existing files and IN_DELETE for removed.
type FileWatcher struct {
C chan FileEvent
done chan struct{}
}
// NewFileWatcher creates FileWatcher with provided inotify mask and list of files to wait events for.
func NewFileWatcher(ctx context.Context, mask uint32, files ...string) (*FileWatcher, error) {
f := &FileWatcher{
C: make(chan FileEvent),
done: make(chan struct{}),
}
inotify, err := NewInotify(ctx)
if err != nil {
return nil, err
}
expectedPaths := make(map[string]bool)
for _, file := range files {
_, err := inotify.AddWatch(filepath.Dir(file), mask)
if err != nil {
return nil, err
}
expectedPaths[file] = true
}
events := make(chan FileEvent)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
close(events)
return
default:
}
raw, err := inotify.Read()
if err != nil {
close(events)
return
}
for _, event := range raw {
select {
case <-ctx.Done():
return
case events <- FileEvent{
InotifyEvent: event,
}: //noop
}
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
defer close(f.C)
for {
select {
case <-ctx.Done():
return
case event, ok := <-events:
if !ok {
select {
case <-ctx.Done():
case f.C <- FileEvent{Eof: true}:
}
return
}
if !expectedPaths[event.Name] {
continue
}
select {
case <-ctx.Done():
return
case f.C <- event:
}
}
}
}()
go func() {
<-inotify.Done()
wg.Wait()
close(f.done)
}()
return f, nil
}
// Done returns a channel that is closed when the FileWatcher is done.
func (f *FileWatcher) Done() <-chan struct{} {
return f.done
}