-
Notifications
You must be signed in to change notification settings - Fork 0
/
slog.go
101 lines (90 loc) · 2.31 KB
/
slog.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
package slog
import (
"bytes"
"fmt"
"io"
"sync"
)
const (
_CSI = "\x1B["
)
var (
_CR = []byte{'\r'}
_LF = []byte{'\n'}
)
type Slog struct {
wr io.Writer
footprint int
bannerMemo []byte
mu sync.Mutex
partial *bytes.Buffer
scwr *scrollbackWriter
}
func newSlog(wr io.Writer) *Slog {
s := &Slog{
wr: wr,
partial: &bytes.Buffer{},
}
s.scwr = &scrollbackWriter{s}
return s
}
func (s *Slog) SetBanner(b Banner) {
// Ask the new thing to fmt itself all out.
var buf bytes.Buffer
b.WriteTo(&buf)
// Lock for the remainder.
s.mu.Lock()
defer s.mu.Unlock()
// Save the new state.
s.bannerMemo = buf.Bytes()
s.footprint = bytes.Count(s.bannerMemo, _LF)
// Render.
s.clearDown() // the previous one
io.Copy(s.wr, bytes.NewBuffer(s.bannerMemo))
s.jumpUp(s.footprint)
}
func (s *Slog) jumpUp(n int) {
if n > 0 {
//all these ops should work even on windows ANSI.SYS.
s.wr.Write(_CR) // set cursor to beginning of line.
fmt.Fprint(s.wr, _CSI, n, "A") // jump cursor up. should be supported even on windows.
}
}
func (s *Slog) clearDown() {
fmt.Fprint(s.wr, _CSI, "J") // clear from cursor to end of screen.
}
// must be full lines or we will have a sad time
func (s *Slog) write(msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
// scan for the last (or any) cuts so we can decide what to do
lastBreak := bytes.LastIndexByte(msg, '\n') + 1
// fmt.Printf("::> %q ; %d/%d <::\n", string(msg), lastBreak, len(msg))
if lastBreak <= 0 {
s.partial.Write(msg)
return
}
// clear down, obliterating our previous banner print
s.clearDown()
// if we have any buffered partial lines, flush that first
if s.partial.Len() > 0 {
io.Copy(s.wr, s.partial)
s.partial.Reset()
}
// now flush all other complete lines
io.Copy(s.wr, bytes.NewBuffer(msg[0:lastBreak]))
// and the banner again
io.Copy(s.wr, bytes.NewBuffer(s.bannerMemo))
// retain anything after lastbreak in the partial line buffer
s.partial.Write(msg[lastBreak:])
// jump the cursor back up (so that even if there's out-of-control writers to the
// tty, they'll stomp our banner (which can reappear), rather than us making them disappear).
s.jumpUp(s.footprint)
}
type scrollbackWriter struct {
s *Slog
}
func (scwr *scrollbackWriter) Write(msg []byte) (int, error) {
scwr.s.write(msg)
return len(msg), nil
}