-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
100 lines (79 loc) · 1.61 KB
/
writer.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
package writer
import (
"io"
)
type ColorWriter struct {
writer io.Writer
isTTY func() bool
}
func NewWriter(w io.Writer) *ColorWriter {
return &ColorWriter{
writer: w,
isTTY: isTTY,
}
}
func (w *ColorWriter) SetTTY(isTTY func() bool) {
w.isTTY = isTTY
}
func (w *ColorWriter) Writer() io.Writer {
return w.writer
}
func (w *ColorWriter) Write(p []byte) (n int, err error) {
// If writer is TTY, just pass through.
if w.isTTY() {
return w.writer.Write(p)
}
// Scan for and remove CSI sequences.
const (
ESC = '\x1b'
CSI = '['
SGR = 'm'
)
var (
bytesWritten int
rangeStart = 0
seqStart = -1
isCSI = false
)
for i, b := range p {
switch {
// Start of escape sequence.
case b == ESC:
seqStart = i
isCSI = false
// Start of CSI sequence.
case b == CSI && seqStart == i-1:
isCSI = true
// CSI parameter bytes.
case b >= 0x30 && b <= 0x3f && isCSI:
// CSI intermediate bytes.
case b >= 0x20 && b <= 0x2f && isCSI:
// CSI terminal byte: SGR.
case b == SGR && isCSI:
// TODO: Consider whether to only ignore SGR or all CSI terminators.
fallthrough
// CSI terminal byte.
case b >= 0x40 && b <= 0x7e && isCSI:
// Write buffer up til start of escape sequence.
if bytesWritten, err = w.writer.Write(p[rangeStart:seqStart]); err != nil {
return
}
n += bytesWritten
rangeStart = i + 1
fallthrough
// Reset.
default:
seqStart = -1
isCSI = false
}
}
// Write remaining buffer.
if bytesWritten, err = w.writer.Write(p[rangeStart:]); err != nil {
return
}
n += bytesWritten
return
}
func isTTY() bool {
return false
}