-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsevent_monitor.go
85 lines (69 loc) · 1.84 KB
/
fsevent_monitor.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
// +build darwin
package piaas
import (
"github.com/fsnotify/fsevents"
log "github.com/sirupsen/logrus"
"path/filepath"
"time"
)
type FSEventMonitor struct {
startDir string
// This channel publish collected changes.
// The changes will be published to CollectObservers.
collectsCh chan []string
// The caller of RecursiveMonitor should use this to subscribe to collected changes.
collectObservers []chan<- []string
eventStream *fsevents.EventStream
}
func (fsm *FSEventMonitor) Start(debounceTime uint64) {
dev, err := fsevents.DeviceForPath(fsm.startDir)
if err != nil {
log.Fatal(err)
}
es := &fsevents.EventStream{
Paths: []string{fsm.startDir},
Latency: time.Millisecond * time.Duration(debounceTime),
Device: dev,
Flags: fsevents.FileEvents | fsevents.NoDefer,
}
fsm.eventStream = es
go handleCollectedFSEvent(fsm)
go handleFSEvent(fsm)
es.Start()
}
func (fsm *FSEventMonitor) Subscribe(subscriber chan<- []string) {
fsm.collectObservers = append(fsm.collectObservers, subscriber)
log.Debugf("Added collect observer: %d.", len(fsm.collectObservers))
}
func (fsm *FSEventMonitor) Stop() {
if fsm.eventStream != nil {
fsm.eventStream.Stop()
}
}
func handleFSEvent(fsm *FSEventMonitor) {
for events := range fsm.eventStream.Events {
collected := make([]string, len(events))
for i := range events {
collected[i] = "/" + events[i].Path
}
fsm.collectsCh <- collected
}
}
func handleCollectedFSEvent(fsm *FSEventMonitor) {
for collected := range fsm.collectsCh {
for _, obs := range fsm.collectObservers {
obs <- collected
}
}
}
func NewFSEventMonitor(path string) FSEventMonitor {
evaluated, err := filepath.EvalSymlinks(path)
if err != nil {
log.Errorf("Error evaluating sym links: %s", err)
evaluated = path
}
return FSEventMonitor{
startDir: evaluated,
collectsCh: make(chan []string),
}
}