-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord.go
110 lines (101 loc) · 2.2 KB
/
record.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/codegangsta/cli"
"github.com/docker/docker/pkg/term"
"github.com/kr/pty"
)
func recordAction(context *cli.Context) {
if os.Getenv("RECORDING") == "true" {
logger.Fatal("you are already in a recording session")
}
path := context.Args().First()
if path == "" {
logger.Fatal("no path specified for recording")
}
if err := recordTerm(path); err != nil {
logger.Fatal(err)
}
}
type recoding struct {
Timestamp time.Time `json:"timestamp"`
Content []byte `json:"content"`
}
func newRecorder(f io.WriteCloser) io.WriteCloser {
return &recorder{
output: f,
encoder: json.NewEncoder(f),
}
}
type recorder struct {
output io.WriteCloser
encoder *json.Encoder
}
func (r *recorder) Write(p []byte) (int, error) {
c := recoding{
Timestamp: time.Now(),
Content: p,
}
if err := r.encoder.Encode(c); err != nil {
return -1, err
}
return len(p), nil
}
func (r *recorder) Close() error {
return r.output.Close()
}
func recordTerm(path string) error {
if os.Getenv("RECORDING") == "true" {
return fmt.Errorf("cannot start a recording inside a recording, too much inception...")
}
master, slave, err := pty.Open()
if err != nil {
return err
}
state, err := term.SetRawTerminal(os.Stdin.Fd())
if err != nil {
return err
}
defer func() {
master.Close()
term.RestoreTerminal(os.Stdin.Fd(), state)
}()
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return err
}
r := newRecorder(f)
defer r.Close()
s := make(chan os.Signal, 32)
signal.Notify(s)
cmd := exec.Command(os.Getenv("SHELL"))
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
cmd.Env = append(os.Environ(), "RECORDING=true")
cmd.Stdin = slave
cmd.Stdout = slave
cmd.Stderr = slave
setTermSize(master)
go forwardSignals(s, cmd, master)
go io.Copy(master, os.Stdin)
go io.Copy(io.MultiWriter(os.Stdout, r), master)
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
// only return an error if it's not an exit error from
// the user's process
if _, ok := err.(*exec.ExitError); !ok {
return err
}
}
return nil
}