-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcolorwriter.go
110 lines (94 loc) · 2.26 KB
/
colorwriter.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
102
103
104
105
106
107
108
109
110
package sgr
import (
"bytes"
"io"
)
// ForcedNewline is written to the Writer set to ColorWriter when the written bytes didn't end with a newline
var ForcedNewline = []byte(FgWhite + BgRed + `↵ ` + Reset)
// ExistingNewline is written to the Writer set to ColorWriter when the written bytes ended with a newline
var ExistingNewline = []byte(FgWhite + BgGreen + `↵ ` + Reset)
var newlineBytes = []byte("\n")
var resetBytes = []byte(Reset)
// ColorWriter implements io.Writer
type ColorWriter struct {
writer io.Writer
colorBytes []byte
forceNewline bool
}
// NewColorWriter creates a new ColorWriter.
// example: NewColorWriter(os.Stdout, sgr.FgBlue, true)
func NewColorWriter(w io.Writer, color string, forceNewline bool) *ColorWriter {
return &ColorWriter{
writer: w,
colorBytes: []byte(color),
forceNewline: forceNewline,
}
}
// Write writes the bytes to underlying writer, but adds coloring
func (cw *ColorWriter) Write(p []byte) (n int, err error) {
var nExtra int
var nExtraAdd int
// make buffer for length of given byteslice, plus 40 for coloring, reset and newline indicators
buf := bytes.NewBuffer(make([]byte, 0, len(p)+40))
// add colors
nExtraAdd, err = buf.Write(cw.colorBytes)
if err != nil {
return
}
nExtra += nExtraAdd
// force newline if wanted && required
if !cw.forceNewline {
// write all bytes
_, err = buf.Write(p)
if err != nil {
return
}
} else {
// write tekst/data except last byte
_, err = buf.Write(p[:len(p)-1])
if err != nil {
return
}
// check last byte
if p[len(p)-1] == '\n' {
nExtraAdd, err = buf.Write(ExistingNewline)
if err != nil {
return
}
nExtra += nExtraAdd
_, err = buf.Write(p[len(p)-1:])
if err != nil {
return
}
} else {
_, err = buf.Write(p[len(p)-1:])
if err != nil {
return
}
nExtraAdd, err = buf.Write(ForcedNewline)
if err != nil {
return
}
nExtra += nExtraAdd
nExtraAdd, err = buf.Write(newlineBytes)
if err != nil {
return
}
nExtra += nExtraAdd
}
}
nExtraAdd, err = buf.Write(resetBytes)
if err != nil {
return
}
nExtra += nExtraAdd
// write buffer to actual writer
n, err = cw.writer.Write(buf.Bytes())
// fix n
n = n - nExtra
if n < 0 {
n = 0
}
// all done
return n, err
}