blob: dc73941e340bad0ce0c2eef16dbf46bb55d399e5 (
plain) (
blame)
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
|
package util
import (
"io"
"regexp"
)
const ANSI_REGEX string = "\x1b[[0-9;]*m"
// Strip ansi control characters from source
//
// The source reader is automatically closed when stripper reader is
type AnsiFilterReadCloser struct {
regex regexp.Regexp
readCloser io.ReadCloser
}
func NewAnsiFilterReadCloser(readCloser io.ReadCloser) *AnsiFilterReadCloser {
r := new(AnsiFilterReadCloser)
r.regex = *regexp.MustCompile(ANSI_REGEX)
r.readCloser = readCloser
return r
}
func (rc AnsiFilterReadCloser) Read(p []byte) (int, error) {
n, err := rc.readCloser.Read(p)
if err != io.EOF && err != nil {
return n, err
}
filtered := rc.regex.ReplaceAll(p[:n], []byte(""))
n = copy(p, filtered)
return n, err
}
func (rc AnsiFilterReadCloser) Close() error {
return rc.readCloser.Close()
}
type AnsiFilterWriter struct {
regex regexp.Regexp
writer io.Writer
}
func NewAnsiFilterWriter(writer io.Writer) *AnsiFilterWriter {
w := new(AnsiFilterWriter)
w.regex = *regexp.MustCompile(ANSI_REGEX)
w.writer = writer
return w
}
func (w AnsiFilterWriter) Write(p []byte) (int, error) {
filtered := w.regex.ReplaceAll(p, []byte(""))
n, err := w.writer.Write(filtered)
if n < len(filtered) {
return n, io.ErrShortWrite
}
// NOTE: report the original size not the filtered size to indicate to caller
// that input has been consumed
return len(p), err
}
|