-
Notifications
You must be signed in to change notification settings - Fork 12
/
notify.go
348 lines (290 loc) · 7.91 KB
/
notify.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/**
* Gaze (https://github.com/wtetsu/gaze/)
* Copyright 2020-present wtetsu
* Licensed under MIT
*/
package notify
import (
"errors"
"path/filepath"
"strings"
"github.com/bmatcuk/doublestar"
"github.com/fsnotify/fsnotify"
"github.com/wtetsu/gaze/pkg/fs"
"github.com/wtetsu/gaze/pkg/logger"
"github.com/wtetsu/gaze/pkg/time"
"github.com/wtetsu/gaze/pkg/uniq"
)
// Notify delivers events to a channel when files are virtually updated.
// "create+rename" is regarded as "update".
type Notify struct {
Events chan Event
Errors chan error
watcher *fsnotify.Watcher
isClosed bool
times map[string]int64
pendingPeriod int64
regardRenameAsModPeriod int64
detectCreate bool
candidates []string
}
// Event represents a single file system notification.
type Event struct {
Name string
Time int64
}
// Op describes a set of file operations.
type Op = fsnotify.Op
// Close disposes internal resources.
func (n *Notify) Close() {
if n.isClosed {
return
}
n.watcher.Close()
n.isClosed = true
}
// New creates a Notify
func New(patterns []string, maxWatchDirs int) (*Notify, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.ErrorObject(err)
return nil, err
}
candidates := findCandidatesDirectories(patterns)
watchDirs := findActualDirs(candidates, maxWatchDirs)
if len(watchDirs) > maxWatchDirs {
logger.Error(strings.Join(watchDirs[:maxWatchDirs], "\n") + "\n...")
return nil, errors.New("too many watchDirs")
}
for _, t := range watchDirs {
err = watcher.Add(t)
if err != nil {
if err.Error() == "bad file descriptor" {
logger.Info("%s: %v", t, err)
} else {
logger.Error("%s: %v", t, err)
}
} else {
logger.Info("gazing at: %s", t)
}
}
notify := &Notify{
Events: make(chan Event),
watcher: watcher,
isClosed: false,
times: make(map[string]int64),
pendingPeriod: 100,
regardRenameAsModPeriod: 1000,
detectCreate: true,
candidates: candidates,
}
go notify.wait()
return notify, nil
}
func findActualDirs(patterns []string, maxWatchDirs int) []string {
targets := uniq.New()
for _, pattern := range patterns {
dirs := findDirsByPattern(pattern)
targets.AddAll(dirs)
if targets.Len() > maxWatchDirs {
break
}
}
return targets.List()
}
// ["aaa/bbb/ccc"] -> [".", "aaa", "aaa/bbb", "aaa/bbb/ccc"]
// ["../aaa/bbb/ccc"] -> ["..", "../aaa", "../aaa/bbb", "../aaa/bbb/ccc"]
// ["/aaa/bbb/ccc"] -> ["/", "/aaa", "/aaa/bbb", "/aaa/bbb/ccc"]
func findCandidatesDirectories(patterns []string) []string {
targets := uniq.New()
for _, pattern := range patterns {
paths := parsePathPattern(pattern)
for i := len(paths) - 1; i >= 0; i-- {
targets.Add(paths[i])
}
}
return targets.List()
}
// "aaa/bbb/ccc/*/ddd/eee/*" -> ["aaa/bbb/ccc/*/ddd/eee/*", "aaa/bbb/ccc/*/ddd/eee", "aaa/bbb/ccc/*/ddd", "aaa/bbb/ccc/*", "aaa/bbb/ccc", "aaa/bbb", "aaa", "."]
func parsePathPattern(pathPattern string) []string {
result := []string{}
if len(pathPattern) == 0 {
return result
}
if pathPattern == "/" || pathPattern == "\\" || pathPattern == "." || pathPattern == ".." {
return []string{pathPattern}
}
result = append(result, pathPattern)
isAbs := filepath.IsAbs(pathPattern) || pathPattern[0] == '/'
isParent := strings.HasPrefix(pathPattern, "..")
isWinAbs := pathPattern[0] != '/' && isAbs
isExplicitCurrent := false
isCurrent := !isAbs && !isParent
if isCurrent {
isExplicitCurrent = strings.HasPrefix(pathPattern, ".")
}
winFirstDelimiter := -1
if isWinAbs {
winFirstDelimiter = strings.Index(pathPattern, "\\")
}
for i := len(pathPattern) - 1; i >= 0; i-- {
ch := pathPattern[i]
if ch == '/' || ch == '\\' {
if i > 0 {
p := pathPattern[0:i]
if winFirstDelimiter == i {
p += "\\"
}
result = append(result, p)
} else {
result = append(result, "/")
}
}
}
if len(result) <= 1 {
if !isAbs && !isExplicitCurrent {
result = append(result, ".")
}
} else {
if isCurrent && !isExplicitCurrent {
result = append(result, ".")
}
}
return result
}
func findDirsByPattern(pattern string) []string {
patternDir := filepath.Dir(pattern)
logger.Debug("pattern: %s", pattern)
logger.Debug("patternDir: %s", patternDir)
var targets []string
realDir := findRealDirectory(patternDir)
if len(realDir) > 0 {
targets = append(targets, realDir)
}
_, dirs1 := fs.Find(pattern)
targets = append(targets, dirs1...)
_, dirs2 := fs.Find(patternDir)
targets = append(targets, dirs2...)
return targets
}
func findRealDirectory(path string) string {
entries := strings.Split(filepath.ToSlash(filepath.Clean(path)), "/")
currentPath := ""
for i := 0; i < len(entries); i++ {
if containsWildcard(entries[i]) {
break
}
currentPath += entries[i] + string(filepath.Separator)
}
currentPath = fs.TrimSuffix(currentPath, string(filepath.Separator))
if fs.IsDir(currentPath) {
return currentPath
} else {
return ""
}
}
func containsWildcard(path string) bool {
return strings.ContainsAny(path, "*?[{")
}
func shouldWatch(dirPath string, candidates []string) bool {
dirPathSlash := filepath.ToSlash(dirPath)
if !fs.IsDir(dirPathSlash) {
return false
}
for _, pattern := range candidates {
patternSlash := filepath.ToSlash(pattern)
ok, _ := doublestar.Match(patternSlash, dirPathSlash)
if ok {
return true
}
}
return false
}
func (n *Notify) wait() {
for {
select {
case event, ok := <-n.watcher.Events:
normalizedName := filepath.Clean(event.Name)
logger.Debug("fs.IsDir: %s", fs.IsDir(normalizedName))
if event.Op == fsnotify.Create && shouldWatch(normalizedName, n.candidates) {
logger.Info("gazing at: %s", normalizedName)
n.watchNewDir(normalizedName)
}
if !ok {
continue
}
if !n.shouldExecute(normalizedName, event.Op) {
continue
}
logger.Debug("notified: %s: %s", normalizedName, event.Op)
now := time.Now()
n.times[normalizedName] = now
e := Event{
Name: normalizedName,
Time: now,
}
n.Events <- e
case err, ok := <-n.watcher.Errors:
if !ok {
continue
}
n.Errors <- err
}
}
}
func (n *Notify) watchNewDir(normalizedName string) {
err := n.watcher.Remove(normalizedName)
if err != nil {
if !strings.HasPrefix(err.Error(), "can't remove non-existent") {
logger.Error("watcher.Remove: %s", err)
}
}
err = n.watcher.Add(normalizedName)
if err != nil {
logger.Error("watcher.Add: %s", err)
}
}
func (n *Notify) shouldExecute(filePath string, op Op) bool {
const W = fsnotify.Write
const R = fsnotify.Rename
const C = fsnotify.Create
if op != W && op != R && !(n.detectCreate && op == C) {
logger.Debug("skipped: %s: %s (Op is not applicable)", filePath, op)
return false
}
lastExecutionTime := n.times[filePath]
if !fs.IsFile(filePath) {
logger.Debug("skipped: %s: %s (not a file)", filePath, op)
return false
}
if strings.Contains(filePath, "'") || strings.Contains(filePath, "\"") {
logger.Debug("skipped: %s: %s (unsupported character)", filePath, op)
return false
}
modifiedTime := time.GetFileModifiedTime(filePath)
if op == W || op == C {
elapsed := modifiedTime - lastExecutionTime
logger.Debug("lastExecutionTime(%s): %d, %d", op, lastExecutionTime, elapsed)
if elapsed < n.pendingPeriod*1000000 {
logger.Debug("skipped: %s: %s (too frequent)", filePath, op)
return false
}
}
if op == R {
elapsed := time.Now() - modifiedTime
logger.Debug("lastExecutionTime(%s): %d, %d", op, lastExecutionTime, elapsed)
if elapsed > n.regardRenameAsModPeriod*1000000 {
logger.Debug("skipped: %s: %s (unnatural rename)", filePath, op)
return false
}
}
return true
}
// PendingPeriod sets new pendingPeriod(ms).
func (n *Notify) PendingPeriod(p int64) {
n.pendingPeriod = p
}
// Requeue requeue an event.
func (n *Notify) Requeue(event Event) {
n.Events <- event
}