forked from burke/zeus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filemonitor.go
78 lines (64 loc) · 1.49 KB
/
filemonitor.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
package filemonitor
import (
"sync"
"time"
)
const DefaultFileChangeDelay = 300 * time.Millisecond
type FileMonitor interface {
Listen() <-chan []string
Add(string) error
Close() error
}
type fileMonitor struct {
listeners []chan []string
listenerMutex sync.Mutex
}
func (f *fileMonitor) Listen() <-chan []string {
f.listenerMutex.Lock()
defer f.listenerMutex.Unlock()
c := make(chan []string)
f.listeners = append(f.listeners, c)
return c
}
type gatheringMonitor struct {
fileMonitor
changes chan string
fileChangeDelay time.Duration
}
// Create the changes channel and serve debounced changes to listeners.
// The changes channel must be created before this is started.
// Closing the changes channel causes this to close all listener
// channels and return.
func (f *gatheringMonitor) serveListeners() {
never := make(<-chan time.Time)
deadline := never
collected := make(map[string]bool, 1)
for {
select {
case change := <-f.changes:
// Channel closed
if change == "" {
f.listenerMutex.Lock()
defer f.listenerMutex.Unlock()
for _, listener := range f.listeners {
close(listener)
}
return
}
collected[change] = true
if deadline == never {
deadline = time.After(f.fileChangeDelay)
}
case <-deadline:
list := make([]string, 0, len(collected))
for f := range collected {
list = append(list, f)
}
for _, l := range f.listeners {
l <- list
}
deadline = never
collected = make(map[string]bool, 1)
}
}
}