-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwatcher.go
More file actions
189 lines (167 loc) · 4.37 KB
/
watcher.go
File metadata and controls
189 lines (167 loc) · 4.37 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
package fswatch
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/logger"
"github.com/fsnotify/fsnotify"
)
const DefaultWaitTimeout = 100 * time.Millisecond
// Watcher is a simple fsnotify wrapper to watch updates correctly.
type Watcher struct {
watchDirect bool
watchTarget []string
watchPath []string
callback func(path string)
waitTimeout time.Duration
logger logger.Logger
watcher *fsnotify.Watcher
stateAccess sync.Mutex
timerMap map[string]pendingCallback
closed bool
}
type pendingCallback struct {
generation uint64
timer *time.Timer
}
type Options struct {
// Path is the list of files or directories to watch
// It is the caller's responsibility to ensure that paths are absolute.
Path []string
// Direct is the flag to watch the file directly if file will never be removed
Direct bool
// Callback is the function to call when a file is updated
Callback func(path string)
// WaitTimeout is the time to wait write events before calling the callback
// DefaultWaitTimeout is used by default
WaitTimeout time.Duration
// Logger is the logger to log errors
// optional
Logger logger.Logger
}
func NewWatcher(options Options) (*Watcher, error) {
if len(options.Path) == 0 || options.Callback == nil {
return nil, os.ErrInvalid
}
waitTimeout := options.WaitTimeout
if waitTimeout == 0 {
waitTimeout = DefaultWaitTimeout
}
var watchTarget []string
if options.Direct {
watchTarget = options.Path
} else {
watchTarget = common.Uniq(common.Map(options.Path, filepath.Dir))
// TODO: update sing to use common.Remove when it's stable
watchTarget = common.Filter(watchTarget, func(it string) bool {
return !common.Any(watchTarget, func(path string) bool {
return len(path) > len(it) && strings.HasPrefix(path, it)
})
})
}
return &Watcher{
watchDirect: options.Direct,
watchTarget: watchTarget,
watchPath: options.Path,
callback: options.Callback,
waitTimeout: waitTimeout,
logger: options.Logger,
timerMap: make(map[string]pendingCallback),
}, nil
}
func (w *Watcher) Start() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return E.Cause(err, "fswatch: create fsnotify watcher")
}
for _, target := range w.watchTarget {
err = watcher.Add(target)
if err != nil {
return E.Cause(err, "fswatch: watch ", target)
}
}
w.watcher = watcher
go w.loopUpdate()
return nil
}
func (w *Watcher) Close() error {
w.stateAccess.Lock()
if w.closed {
watcher := w.watcher
w.stateAccess.Unlock()
return common.Close(common.PtrOrNil(watcher))
}
w.closed = true
timers := make([]*time.Timer, 0, len(w.timerMap))
for path, pending := range w.timerMap {
timers = append(timers, pending.timer)
delete(w.timerMap, path)
}
watcher := w.watcher
w.stateAccess.Unlock()
for _, timer := range timers {
timer.Stop()
}
return common.Close(common.PtrOrNil(watcher))
}
func (w *Watcher) loopUpdate() {
for {
select {
case event, loaded := <-w.watcher.Events:
if !loaded {
return
}
if common.Contains(w.watchTarget, event.Name) && (event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove)) {
if w.logger != nil {
w.logger.Error("fswatch: watcher removed: ", event.Name)
}
} else if common.Contains(w.watchPath, event.Name) && (event.Has(fsnotify.Create) || event.Has(fsnotify.Write)) {
w.scheduleCallback(event.Name)
}
case err, loaded := <-w.watcher.Errors:
if !loaded {
return
}
if w.logger != nil {
w.logger.Error("fswatch: ", err)
}
}
}
}
func (w *Watcher) scheduleCallback(path string) {
w.stateAccess.Lock()
if w.closed {
w.stateAccess.Unlock()
return
}
pending := w.timerMap[path]
generation := pending.generation + 1
if pending.timer != nil {
pending.timer.Stop()
}
w.timerMap[path] = pendingCallback{
generation: generation,
timer: time.AfterFunc(w.waitTimeout, func() { w.fireCallback(path, generation) }),
}
w.stateAccess.Unlock()
}
func (w *Watcher) fireCallback(path string, generation uint64) {
w.stateAccess.Lock()
if w.closed {
w.stateAccess.Unlock()
return
}
pending, loaded := w.timerMap[path]
if !loaded || pending.generation != generation {
w.stateAccess.Unlock()
return
}
delete(w.timerMap, path)
callback := w.callback
w.stateAccess.Unlock()
callback(path)
}