/
changeswatcher.go
56 lines (49 loc) · 1.11 KB
/
changeswatcher.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
package appwatchertools
import (
"context"
"fmt"
"github.com/fsnotify/fsnotify"
"time"
)
type OnFileChange = func(path []string) error
type Watcher = WatchConfig
func NewWatcher() *Watcher {
return NewWatchConfig()
}
func (w *Watcher) WatchForChanges(ctx context.Context) error {
if w.Dir == "" {
return fmt.Errorf("watcher is missing Dir parameter")
}
if w.Debounce == 0 {
w.Debounce = 200 * time.Millisecond
}
events := make(chan fsnotify.Event, 100)
go func() {
var eventsOut []string
for {
select {
case event := <-events:
// @todo contemplate errors, delete events via Write?
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
eventsOut = append(eventsOut, event.Name)
}
case <-time.After(w.Debounce):
if w.isRebuilding {
continue
}
if eventsOut != nil {
w.isRebuilding = true
if err := w.OnChange(eventsOut); err != nil {
// @todo some better?
panic(err)
}
eventsOut = nil
w.isRebuilding = false
}
case <-ctx.Done():
return
}
}
}()
return WatchDir(w, ctx, events)
}