/
watch.go
96 lines (81 loc) · 1.69 KB
/
watch.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
package watch
import (
"path/filepath"
"sync/atomic"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-gonzo/fs/glob"
"github.com/omeid/gonzo/context"
"github.com/omeid/kargar"
)
func throttle(limit time.Duration) func(func()) bool {
var last int64
lims := limit.Seconds()
return func(cb func()) bool {
now := time.Now().Unix()
l := atomic.LoadInt64(&last)
if l+int64(lims) < now {
cb()
atomic.StoreInt64(&last, now)
return true
}
return false
}
}
// Watcher ...
func Watcher(ctx context.Context, cb func(string), globs ...string) error {
files, err := glob.Glob(globs...)
if err != nil {
return err
}
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
for matchpair := range files {
w.Add(filepath.Dir(matchpair.Name))
w.Add(matchpair.Name)
}
throttled := throttle(50 * time.Millisecond)
go func() {
for {
select {
case event := <-w.Events:
ctx.Debugf("gonzo:watch:Event %v on %v", event, event.Name)
//if event.Op&fsnotify.Write == fsnotify.Write {
//event.Op&fsnotify.Create == fsnotify.Create ||
throttled(func() {
cb(event.Name)
})
//}
case err := <-w.Errors:
if err != nil {
ctx.Error(err)
}
case <-ctx.Done():
w.Close()
return
}
}
}()
return nil
}
// WatcherSet is like watcher...
func WatcherSet(cb func(context.Context, ...string) error, watches map[string][]string) kargar.Action {
return func(ctx context.Context) error {
//function wrapper to copy set and files.
for set, files := range watches {
var s = set
err := Watcher(
ctx,
func(string) { cb(ctx, s) },
files...,
)
if err != nil {
return err
}
}
<-ctx.Done()
return nil
}
}