aboutsummaryrefslogtreecommitdiffhomepage
path: root/watcher/batcher.go
blob: 479603f1e1d9a852d237acd23bbd721d9fb3da04 (plain)
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
package watcher

import (
	"time"

	"gopkg.in/fsnotify.v0"
)

type Batcher struct {
	*fsnotify.Watcher
	interval time.Duration
	done     chan struct{}

	Event chan []*fsnotify.FileEvent // Events are returned on this channel
}

func New(interval time.Duration) (*Batcher, error) {
	watcher, err := fsnotify.NewWatcher()

	batcher := &Batcher{}
	batcher.Watcher = watcher
	batcher.interval = interval
	batcher.done = make(chan struct{}, 1)
	batcher.Event = make(chan []*fsnotify.FileEvent, 1)

	if err == nil {
		go batcher.run()
	}

	return batcher, err
}

func (b *Batcher) run() {
	tick := time.Tick(b.interval)
	evs := make([]*fsnotify.FileEvent, 0)
OuterLoop:
	for {
		select {
		case ev := <-b.Watcher.Event:
			evs = append(evs, ev)
		case <-tick:
			if len(evs) == 0 {
				continue
			}
			b.Event <- evs
			evs = make([]*fsnotify.FileEvent, 0)
		case <-b.done:
			break OuterLoop
		}
	}
	close(b.done)
}

func (b *Batcher) Close() {
	b.done <- struct{}{}
	b.Watcher.Close()
}