Welcome to mirror list, hosted at ThFree Co, Russian Federation.

batcher.go « watcher - github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a22ad8b4154631fe152bf1783644bbbd90cf8e31 (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
package watcher

import (
	"github.com/howeyc/fsnotify"
	"time"
)

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()
}