-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecorder.go
80 lines (64 loc) · 1.53 KB
/
recorder.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
package main
import "log"
type ControlMessage int
const (
Unknown ControlMessage = 0
StartRecording ControlMessage = 1
StopRecording ControlMessage = 2
)
type Recorder struct {
control chan ControlMessage
sync chan []byte
stdout <-chan byte
recording bool
current []byte
sizeLimit int
}
func NewRecorder(stdout <-chan byte, sizeLimit int) *Recorder {
return &Recorder{
control: make(chan ControlMessage),
sync: make(chan []byte),
stdout: stdout,
recording: false,
current: make([]byte, 0),
sizeLimit: sizeLimit,
}
}
func (r *Recorder) Start() {
r.control <- StartRecording
<-r.sync
}
func (r *Recorder) Stop() []byte {
r.control <- StopRecording
return <-r.sync
}
func (r *Recorder) Run() {
for {
select {
case ch := <-r.stdout:
if r.recording {
if len(r.current) < r.sizeLimit {
r.current = append(r.current, ch)
}
}
case cmd := <-r.control:
switch cmd {
case StartRecording:
log.Println("starting recording")
r.recording = true
r.sync <- nil // let the shell know it can continue
case StopRecording:
r.recording = false
// make sure r.last has the correct size for copying
// this is fine, always, as they have the same underlying capacity
last := make([]byte, len(r.current))
// save last command's output before cleaning the current buffer
copy(last, r.current)
// clean the buffer for the new recording
r.current = r.current[:0]
log.Println("stopping recording, got", len(last), "bytes")
r.sync <- last
}
}
}
}