-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfilewatch.go
118 lines (98 loc) · 2.2 KB
/
filewatch.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
package filewatch
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"github.com/fsnotify/fsnotify"
)
type Watch interface {
Add(path string, callback func()) error
Run(done <-chan struct{}) error
IsRunning() bool
}
func New() Watch {
return &watch{
callbacks: make(map[string]func()),
}
}
type watch struct {
lock sync.Mutex
callbacks map[string]func()
running atomic.Bool
}
var _ Watch = &watch{}
func (w *watch) Add(path string, callback func()) error {
w.lock.Lock()
defer w.lock.Unlock()
if w.running.Load() {
return fmt.Errorf("cannot add to a running watch")
}
w.callbacks[path] = callback
return nil
}
func (w *watch) Run(done <-chan struct{}) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("could not create fsnotify.Watcher: %w", err)
}
// watcher.Close() never returns an error
defer func() { _ = watcher.Close() }()
func() {
// Before setting running to true, we need to acquire the lock,
// because Add() method may be running concurrently.
w.lock.Lock()
defer w.lock.Unlock()
w.running.Store(true)
}()
// Setting running to false is ok without a lock.
defer w.running.Store(false)
err = w.addCallbacks(watcher)
if err != nil {
return fmt.Errorf("could not add callbacks: %w", err)
}
return w.processEvents(watcher, done)
}
func (w *watch) IsRunning() bool {
return w.running.Load()
}
func (w *watch) addCallbacks(watcher *fsnotify.Watcher) error {
for path := range w.callbacks {
err := watcher.Add(path)
if err != nil {
return fmt.Errorf("failed watch %s: %w", path, err)
}
}
return nil
}
func (w *watch) processEvents(watcher *fsnotify.Watcher, done <-chan struct{}) error {
for {
select {
case <-done:
return nil
case event, ok := <-watcher.Events:
if !ok {
return nil
}
w.handleEvent(event)
case err, ok := <-watcher.Errors:
if !ok {
return nil
}
if err != nil {
return err
}
}
}
}
func (w *watch) handleEvent(event fsnotify.Event) {
const modificationEvents = fsnotify.Create | fsnotify.Write | fsnotify.Remove
if event.Op&modificationEvents == 0 {
return
}
for path, callback := range w.callbacks {
if strings.HasPrefix(event.Name, path) {
callback()
}
}
}