/
watcher.go
186 lines (151 loc) · 4.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
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
package watcher
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/bep/debounce"
"github.com/fsnotify/fsnotify"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"encr.dev/pkg/eerror"
)
type Watcher struct {
mutex sync.Mutex
log *zerolog.Logger
appRoot string
watcher *fsnotify.Watcher
directories map[string]struct{}
stop chan struct{}
EventsReady chan struct{}
events *Events
notifyListener func()
}
func New(appID string) (*Watcher, error) {
fswatcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, eerror.Wrap(err, "watcher", "unable to create watcher", map[string]interface{}{"app": appID})
}
logger := log.With().Str("component", "watcher").Str("app", appID).Logger()
logger.Debug().Msg("File system watcher created")
w := &Watcher{
watcher: fswatcher,
log: &logger,
directories: make(map[string]struct{}),
stop: make(chan struct{}),
events: nil,
EventsReady: make(chan struct{}),
}
// We debounce this to give the system time to process mass file updates
d := debounce.New(50 * time.Millisecond)
w.notifyListener = func() {
d(func() {
w.EventsReady <- struct{}{}
})
}
go w.listenForChangeEvents()
return w, nil
}
func (w *Watcher) RecursivelyWatch(folder string) error {
return filepath.WalkDir(folder, func(path string, info os.DirEntry, err error) error {
if err != nil {
return eerror.Wrap(err, "watcher", "unable to walk directory", map[string]any{"path": path})
}
if info.IsDir() {
folder := filepath.Clean(path)
if IgnoreFolder(folder) {
return filepath.SkipDir
}
// Track the fact we're watching this directory
w.mutex.Lock()
if _, found := w.directories[folder]; found {
w.mutex.Unlock()
return filepath.SkipDir
}
w.directories[folder] = struct{}{}
w.mutex.Unlock() // unlock here to prevent reentrant locks during recursion
// Now start watching this folder
if err := w.watcher.Add(folder); err != nil {
return eerror.Wrap(err, "watcher", "unable to add folder to watch", map[string]any{"folder": folder})
}
}
return nil
})
}
func (w *Watcher) listenForChangeEvents() {
for {
select {
case <-w.stop:
_ = w.watcher.Close()
return
case event := <-w.watcher.Events:
switch {
case event.Op&fsnotify.Create == fsnotify.Create:
w.handleCreateEvent(event.Name)
case event.Op&fsnotify.Write == fsnotify.Write:
w.handleWriteEvent(event.Name)
case event.Op&fsnotify.Remove == fsnotify.Remove:
w.handleDeleteEvent(event.Name)
}
case err := <-w.watcher.Errors:
w.log.Err(err).Msg("Watcher error")
}
}
}
func (w *Watcher) handleCreateEvent(path string) {
if info, err := os.Stat(path); err != nil {
w.log.Err(err).Str("path", path).Msg("unable to stat file")
} else if info.IsDir() {
if err := w.RecursivelyWatch(path); err != nil {
w.log.Err(err).Str("path", path).Msg("unable to start watching new directory")
}
} else {
w.recordEventInBatch(path, CREATED, info)
}
}
func (w *Watcher) handleDeleteEvent(path string) {
path = filepath.Clean(path)
// If it's a directory we're watching, stop watching it
w.mutex.Lock()
for watchedFolder := range w.directories {
if strings.HasPrefix(watchedFolder, path) || watchedFolder == path {
if err := w.watcher.Remove(watchedFolder); err != nil {
w.log.Err(err).Str("path", watchedFolder).Msg("unable to stop watching deleted directory")
}
delete(w.directories, watchedFolder)
}
}
w.mutex.Unlock()
w.recordEventInBatch(path, DELETED, nil)
}
func (w *Watcher) handleWriteEvent(path string) {
if info, err := os.Stat(path); err != nil {
w.log.Err(err).Str("path", path).Msg("unable to stat file")
} else if !info.IsDir() {
w.recordEventInBatch(path, MODIFIED, info)
}
}
func (w *Watcher) recordEventInBatch(path string, event EventType, info os.FileInfo) {
w.mutex.Lock()
defer w.mutex.Unlock()
if w.events == nil {
w.events = newEventBatch()
w.notifyListener()
}
w.events.addEvent(path, event, info)
}
func (w *Watcher) GetEventsBatch() *Events {
w.mutex.Lock()
defer w.mutex.Unlock()
events := w.events
w.events = nil
return events
}
func (w *Watcher) Close() error {
close(w.stop)
return nil
}
func (w *Watcher) Done() <-chan struct{} {
return w.stop
}