-
Notifications
You must be signed in to change notification settings - Fork 1
/
watcher.go
66 lines (57 loc) · 1.22 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
package main
import (
"io/fs"
"log"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
// Watches dir recursively, ignoring directories that match patterns in excludes
// which are checked with filepath.Match. Events are batched and sent in groups
// at most every 100ms.
func watch(dir string, excludes []string) chan []fsnotify.Event {
w, err := fsnotify.NewWatcher()
ch := make(chan []fsnotify.Event)
if err != nil {
log.Fatal(err)
}
go func() {
defer w.Close()
ticker := time.Tick(100 * time.Millisecond)
queue := []fsnotify.Event{}
for {
for _, dir := range w.WatchList() {
w.Remove(dir)
}
filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
for _, pat := range excludes {
if match, _ := filepath.Match(pat, path); match {
return filepath.SkipDir
}
}
w.Add(path)
}
return nil
})
polling:
for {
select {
case err := <-w.Errors:
log.Fatal(err)
case e := <-w.Events:
if e.Op != fsnotify.Chmod {
queue = append(queue, e)
}
case <-ticker:
if len(queue) > 0 {
ch <- queue
queue = []fsnotify.Event{}
break polling
}
}
}
}
}()
return ch
}