-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
333 lines (312 loc) · 7.64 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
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
package watcher
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/bep/debounce"
"github.com/fsnotify/fsnotify"
"github.com/livebud/watcher/internal/gitignore"
)
// Stop informs the watcher to stop.
//
//lint:ignore ST1012 stop is not an error, it's part of the control flow.
var Stop = errors.New("stop watching")
// Arbitrarily picked after some manual testing. OSX is pretty fast, but Ubuntu
// requires a longer delay for writes. Duplicate checks below allow us to keep
// this snappy.
var debounceDelay = 20 * time.Millisecond
// Op is the type of file event that occurred
type Op string
const (
OpCreate Op = "create"
OpUpdate Op = "update"
OpDelete Op = "delete"
)
// Event is used to track file events
type Event struct {
Op Op
Path string
}
func (e Event) String() string {
return string(e.Op) + ":" + e.Path
}
func newEventSet() *eventSet {
return &eventSet{
has: map[string]bool{},
events: []Event{},
}
}
// eventset is used to collect events that have changed and flush them all at once
// when the watch function is triggered.
type eventSet struct {
mu sync.RWMutex
has map[string]bool
events []Event
}
// Add a event to the set
func (p *eventSet) Add(event Event) {
p.mu.Lock()
defer p.mu.Unlock()
if p.has[event.String()] {
return
}
p.has[event.String()] = true
p.events = append(p.events, event)
}
// Flush the stored events and clear the event set.
func (p *eventSet) Flush() (events []Event) {
p.mu.Lock()
defer p.mu.Unlock()
events = make([]Event, 0, len(p.events))
// Sometimes you can end up with two events for the same file like create and
// update on Mac. Remove any updates, when we have a create or delete event.
seen := map[string]bool{}
for _, event := range p.events {
if seen[event.Path] {
continue
}
seen[event.Path] = true
events = append(events, event)
}
// Sort amongst the same operation to make the tests deterministic.
sort.Slice(events, func(i, j int) bool {
if events[i].Op == events[j].Op {
return events[i].Path < events[j].Path
}
return false
})
// Clear the set
p.has = map[string]bool{}
p.events = []Event{}
return events
}
// Watch a directory of files
func Watch(ctx context.Context, dir string, fn func(events []Event) error) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// Don't watch files in .gitignore
gitIgnore := gitignore.From(dir)
// Trigger is debounced to group events together
errorCh := make(chan error)
eventSet := newEventSet()
debounce := debounce.New(debounceDelay)
trigger := func(event Event) {
relPath, err := filepath.Rel(dir, event.Path)
if err != nil {
errorCh <- err
return
}
event.Path = relPath
eventSet.Add(event)
debounce(func() {
if err := fn(eventSet.Flush()); err != nil {
errorCh <- err
return
}
})
}
// Avoid duplicate events by checking the stamp of the file. This allows us
// to bring down the debounce delay to trigger events faster.
// TODO: bound this map
duplicates := map[string]struct{}{}
isDuplicate := func(path string, stat fs.FileInfo) bool {
stamp, err := computeStamp(path, stat)
if err != nil {
return false
}
// Duplicate check
if _, ok := duplicates[stamp]; ok {
return true
}
duplicates[stamp] = struct{}{}
return false
}
// For some reason renames are often emitted instead of
// Remove. Check it and correct.
rename := func(path string) error {
_, err := os.Stat(path)
if nil == err {
return nil
}
// If it's a different error, ignore
if !errors.Is(err, fs.ErrNotExist) {
return nil
}
// Remove the path and emit an update
watcher.Remove(path)
// Trigger an update
trigger(Event{OpDelete, path})
return nil
}
// Remove the file or directory from the watcher.
// We intentionally ignore errors for this case.
remove := func(path string) error {
watcher.Remove(path)
// Trigger an update
trigger(Event{OpDelete, path})
return nil
}
// Watching a file or directory as long as it's not inside .gitignore.
// Ignore most errors since missing a file isn't the end of the world.
// If a new directory is created, add and trigger all the files within
// that directory.
var create func(path string) error
create = func(path string) error {
// Stat the file
stat, err := os.Stat(path)
if err != nil {
return nil
}
relPath, err := filepath.Rel(dir, path)
if err != nil {
return err
}
if gitIgnore(relPath) {
return nil
}
if isDuplicate(path, stat) {
return nil
}
err = watcher.Add(path)
if err != nil {
return err
}
// If it's a directory, walk the dir and trigger creates
// because those create events won't happen on their own
if stat.IsDir() {
trigger(Event{OpCreate, path})
des, err := os.ReadDir(path)
if err != nil {
return err
}
for _, de := range des {
if err := create(filepath.Join(path, de.Name())); err != nil {
return err
}
}
return nil
}
// Otherwise, trigger the create
trigger(Event{OpCreate, path})
return nil
}
// A file or directory has been updated. Notify our matchers.
write := func(path string) error {
relPath, err := filepath.Rel(dir, path)
if err != nil {
return err
}
if gitIgnore(relPath) {
return nil
}
// Stat the file
stat, err := os.Stat(path)
if err != nil {
return nil
}
if isDuplicate(path, stat) {
return nil
}
// Trigger an update
trigger(Event{OpUpdate, path})
return nil
}
// Walk the files, adding files that aren't ignored
if err := filepath.WalkDir(dir, func(path string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(dir, path)
if err != nil {
return err
}
// Support .gitignore
if gitIgnore(relPath) {
// Skip directories
if de.IsDir() {
return filepath.SkipDir
}
// Ignore files
return nil
}
// Add the path to the watcher
if err := watcher.Add(path); err != nil {
return err
}
return nil
}); err != nil {
return err
}
// Watch for file events!
// Note: The FAQ currently says it needs to be in a separate Go routine
// https://github.com/fsnotify/fsnotify#faq, so we'll do that.
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
for {
select {
case <-ctx.Done():
return nil
case err := <-errorCh:
return err
case err := <-watcher.Errors:
return err
case evt := <-watcher.Events:
// Sometimes the event name can be empty on Linux during deletes. Ignore
// those events.
if evt.Name == "" {
continue
}
// Switch over the operations
switch op := evt.Op; {
// Handle rename events
case op&fsnotify.Rename != 0:
if err := rename(evt.Name); err != nil {
return err
}
// Handle remove events
case op&fsnotify.Remove != 0:
if err := remove(evt.Name); err != nil {
return err
}
// Handle create events
case op&fsnotify.Create != 0:
if err := create(evt.Name); err != nil {
return err
}
// Handle write events
case op&fsnotify.Write != 0:
if err := write(evt.Name); err != nil {
return err
}
}
}
}
})
// Wait for the watcher to complete
if err := eg.Wait(); err != nil {
if !errors.Is(err, Stop) {
return err
}
return nil
}
return nil
}
// computeStamp uses path, size, mode and modtime to try and ensure this is a
// unique event.
func computeStamp(path string, stat fs.FileInfo) (stamp string, err error) {
mtime := stat.ModTime().Unix()
mode := stat.Mode()
size := stat.Size()
stamp = path + ":" + strconv.Itoa(int(size)) + ":" + mode.String() + ":" + strconv.Itoa(int(mtime))
return stamp, nil
}