/
main.go
84 lines (66 loc) · 1.35 KB
/
main.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
package main
import (
SYS "syscall"
"time"
"github.com/go-fsnotify/fsnotify"
death "github.com/vrecan/death"
)
type state struct {
stat stat
duration time.Duration
}
var emptyState = state{emptyStat, 0}
func whenCreation(
events <-chan fsnotify.Event) <-chan fsnotify.Event {
out := make(chan fsnotify.Event)
write := fsnotify.Write
create := fsnotify.Create
go func() {
for event := range events {
switch {
case event.Op&create == create:
out <- event
case event.Op&write == write:
out <- event
}
}
}()
return out
}
func collect(
fileReader fileReader,
decoder func(
fileReader,
string,
stat) (stat, println),
events <-chan fsnotify.Event,
ticker <-chan time.Time) <-chan stat {
stats := make(chan stat)
go func() {
state := emptyState
for {
select {
case event := <-events:
eventTime := time.Now()
newStat, println :=
decoder(fileReader, event.Name, state.stat)
state.duration += time.Since(eventTime)
state.stat = newStat
runPrintln(println)
case <-ticker:
stats <- calcAvg(state)
state = emptyState
}
}
}()
return stats
}
func main() {
w := logErrors(watchInput("input/"))
go printStats(collect(
runReadfile,
decodeFile,
whenCreation(w.watcher.Events),
time.NewTicker(time.Second).C))
death.NewDeath(SYS.SIGINT, SYS.SIGTERM).WaitForDeath(w)
}