witty/cmd/replay/replay.go

84 lines
1.6 KiB
Go
Raw Normal View History

2022-01-14 23:04:50 +01:00
package main
import (
"encoding/json"
2022-01-18 12:35:58 +01:00
"flag"
2022-01-14 23:04:50 +01:00
"io"
"log"
"os"
"time"
"golang.org/x/term"
)
type writeRecord struct {
Dur time.Duration `json:"Duration"`
Data []byte `json:"Data"`
}
func main() {
2022-01-18 12:35:58 +01:00
var wait uint
flag.UintVar(&wait, "w", 2000, "Max wait time between outputs")
flag.UintVar(&wait, "wait", 2000, "Max wait time between outputs")
flag.Parse()
left := flag.Args()
if len(left) != 1 {
2022-01-18 12:44:02 +01:00
fmt.Println("Usage: replay -w/wait time <recordfile>")
return
2022-01-14 23:04:50 +01:00
}
2022-01-18 12:35:58 +01:00
fp, err := os.Open(left[0])
2022-01-14 23:04:50 +01:00
if err != nil {
log.Fatalln("Failed to open record file", err)
}
screen := struct {
io.Reader
io.Writer
}{os.Stdin, os.Stdout}
2022-01-18 12:35:58 +01:00
t := term.NewTerminal(screen, "$")
2022-01-14 23:04:50 +01:00
if t == nil {
log.Fatalln("Failed to create terminal")
}
2022-01-14 23:16:06 +01:00
w, h, _ := term.GetSize(int(os.Stdout.Fd()))
2022-01-14 23:04:50 +01:00
if (w != 120) || (h != 36) {
2022-01-16 00:54:15 +01:00
log.Println("Set terminal window to 120x36 before continue")
2022-01-14 23:04:50 +01:00
}
decoder := json.NewDecoder(fp)
if decoder == nil {
log.Fatalln("Failed to create JSON decoder")
}
2022-01-16 00:54:15 +01:00
// To work with javascript decoder, we organize the file as
// an array of writeRecord. golang decode instead decode
// as individual record. Call decoder.Token to skip opening [
decoder.Token()
2022-01-14 23:04:50 +01:00
for decoder.More() {
var record writeRecord
if err := decoder.Decode(&record); err != nil {
log.Println("Failed to decode record", err)
continue
}
2022-01-18 12:35:58 +01:00
if record.Dur > time.Duration(wait)*time.Millisecond {
record.Dur = time.Duration(wait) * time.Millisecond
}
2022-01-14 23:04:50 +01:00
time.Sleep(record.Dur)
t.Write(record.Data)
}
2022-01-16 00:54:15 +01:00
t.Write([]byte("\n\n---end of replay---\n\n"))
2022-01-14 23:04:50 +01:00
}