-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript_writer.go
More file actions
121 lines (100 loc) · 2.35 KB
/
script_writer.go
File metadata and controls
121 lines (100 loc) · 2.35 KB
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
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"fmt"
"os"
"text/template"
"time"
"unicode/utf8"
)
type scriptWriter struct {
outFileName string
outputFile *os.File
timestampStart time.Time
}
func escapeNonPrintableChars(data []byte) string {
result := ""
for i := 0; i < len(data); {
r, size := utf8.DecodeRune(data[i:])
if r == utf8.RuneError && size == 1 {
// Handle non-printable characters
result += fmt.Sprintf("\\u%04X", data[i])
i++
} else {
// Escape special JSON characters
if r == '"' {
result += "\\\""
} else if r == '\\' {
result += "\\\\"
} else if r < ' ' {
// Handle other non-printable characters
result += fmt.Sprintf("\\u%04X", r)
} else {
result += string(r)
}
i += size
}
}
return result
}
func (w *scriptWriter) WriteData(data []byte) {
timestamp := time.Since(w.timestampStart).Seconds()
// https://docs.asciinema.org/manual/asciicast/v2/
fmt.Fprintf(w.outputFile, `,[
%f,
"o",
"%s"
]`, timestamp, escapeNonPrintableChars(data))
}
func (w *scriptWriter) WriteSize(size WindowSizeT) {
ts := time.Since(w.timestampStart).Seconds()
// https://docs.asciinema.org/manual/asciicast/v2/
fmt.Fprintf(w.outputFile, `,[
%f,
"r",
"%dx%d"
]`, ts, size.cols, size.rows)
}
func (w *scriptWriter) Begin(size WindowSizeT) error {
// Read the header
binFile, err := Asset("templates/output_header.html.in")
if err != nil {
panic(err.Error())
}
w.outputFile, err = os.Create(w.outFileName)
if err != nil {
panic(err.Error())
}
w.outputFile.Write(binFile)
w.timestampStart = time.Now()
fmt.Fprintf(w.outputFile, `{
version: 2,
width:%d,
height:%d
}`, size.cols, size.rows)
return nil
}
func (w *scriptWriter) End() error {
binFile, err := Asset("templates/output_footer.html.in")
if err != nil {
panic(err.Error())
}
tempOut := template.New("output")
tempOut.Parse(string(binFile))
// Read the rest of the template files
for _, fileName := range []string{"asciinema-player.min.js", "asciinema-player.css"} {
binFile, err = Asset(fileName)
if err != nil {
panic(err.Error())
}
tempOut.New(fileName).Parse(string(binFile))
}
err = tempOut.ExecuteTemplate(w.outputFile, "output", nil)
if err != nil {
panic(err.Error())
}
return w.outputFile.Close()
}
func (w *scriptWriter) Write(data []byte) (n int, err error) {
w.WriteData(data)
return len(data), err
}