Debian Codegraph @

interpret.go

raw symbols SCIP
1 package rgbterm
2
3 import (
4 "bufio"
5 "bytes"
6 "io"
7 "os"
8 "regexp"
9 "strconv"
10 "strings"
11 )
12
13 // MaxEscapeCodeLen is the maximum number of bytes that the contents of an escape
14 // code may be. If the escape code is longer than this, it is output verbatim
15 // without being replaced. If MaxEscapeCodeLen is set to 0 escape codes may be
16 // any length (checking is not performed)
17 //
18 // This is used to avoid a possible denial of service.
19 var MaxEscapeCodeLen uint = 15
20
21 // interpret reads from r and writes to w. While reading any color escape codes detected
22 // are replaced by the result of calling subst with the escape code.
23 func interpret(r io.ByteReader, w io.Writer, subst func(s string) []byte) (err error) {
24 inEscape := false
25 escape := &bytes.Buffer{}
26 out := bufio.NewWriter(w)
27 defer func() {
28 if err == nil {
29 err = out.Flush()
30 }
31 }()
32
33 for {
34 var c byte
35 c, err = r.ReadByte()
36 if err != nil {
37 // EOF. Don't consider this a failure of interpret()
38 err = nil
39 break
40 }
41
42 if inEscape {
43 if rune(c) == '{' && escape.Len() == 0 {
44 // False alarm: this was the sequence {{ which means the user wanted to
45 // output {.
46 _, err = out.Write([]byte("{"))
47 escape.Reset()
48 inEscape = false
49 } else if rune(c) == '}' {
50 _, err = out.Write(subst(escape.String()))
51 escape.Reset()
52 inEscape = false
53 } else {
54 escape.WriteByte(c)
55 if MaxEscapeCodeLen > 0 && uint(escape.Len()) > MaxEscapeCodeLen {
56 // Escape code too long
57 out.Write([]byte("{"))
58 _, err = out.Write(escape.Bytes())
59 inEscape = false
60 }
61 }
62 } else {
63 if rune(c) == '{' {
64 inEscape = true
65 } else {
66 _, err = out.Write([]byte{c})
67 }
68 }
69
70 if err != nil {
71 // Write error occurred
72 return
73 }
74 }
75
76 return
77 }
78
79 // colorRegex matches color escape codes
80 var colorRegex *regexp.Regexp = regexp.MustCompile(`#([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})`)
81
82 func parseEscape(s string) ([]uint8, []uint8) {
83 parts := strings.Split(s, ",")
84
85 atoi := func(s []string) (r []uint8) {
86 r = make([]uint8, len(s))
87 for i, v := range s {
88 i64, _ := strconv.ParseInt(v, 16, 0)
89 r[i] = uint8(i64)
90 }
91 return
92 }
93
94 escapes := make([][]uint8, 2)
95 for i, p := range parts {
96 match := colorRegex.FindStringSubmatch(p)
97 if match != nil {
98 escapes[i] = atoi(match[1:])
99 }
100 }
101
102 return escapes[0], escapes[1]
103 }
104
105 func substColor(s string) (c []byte) {
106 fg, bg := parseEscape(s)
107
108 if fg == nil && bg == nil {
109 // Reset colors to default
110 return reset
111 }
112
113 if fg != nil {
114 c = append(c, color(fg[0], fg[1], fg[2], true)...)
115 }
116 if bg != nil {
117 if len(c) > 0 {
118 c = append(c, byte(';'))
119 }
120
121 c = append(c, color(bg[0], bg[1], bg[2], false)...)
122 }
123
124 c = append(before, c...)
125 c = append(c, after...)
126
127 return
128 }
129
130 // Interpret reads data from r and writes it to w,
131 // while substituting the color escapes in the input.
132 //
133 // Color escapes are directives having one of forms
134 // on the following lines:
135 //
136 // {#RRGGBB}
137 // {#RRGGBB,#RRGGBB}
138 // {,#RRGGBB}
139 // {}
140 //
141 // The first form sets the terminal foreground color to
142 // the color RR,GG,BB where RR is the red component,
143 // GG green and BB blue. Each component is in hex.
144 //
145 // The second form sets the foreground and background
146 // colors, while the third sets only the background.
147 //
148 // The fourth form resets the terminal colors to defaults.
149 //
150 // To output a literal { character, use two braces: {{.
151 func Interpret(r io.ByteReader, w io.Writer) error {
152 return interpret(r, w, substColor)
153 }
154
155 // ColorizeTemplate substitutes the color escapes in the
156 // string s and returns the resulting string.
157 //
158 // See Interpret for a description of color escapes.
159 func InterpretStr(s string) string {
160 var out bytes.Buffer
161 Interpret(bytes.NewBuffer([]byte(s)), &out)
162 return out.String()
163 }
164
165 // ColorTemplateWriter writes to an underlying io.Writer
166 // while substituting the color escapes in the input.
167 //
168 // See Interpret for a description of color escapes.
169 type InterpretingWriter struct {
170 p *io.PipeWriter
171 }
172
173 // NewColorTemplateWriter creates a ColorTemplateWriter that writes to
174 // w while substituting the color escapes in the input.
175 //
176 // See Interpret for a description of color escapes.
177 func NewInterpretingWriter(w io.Writer) InterpretingWriter {
178 pr, pw := io.Pipe()
179
180 go Interpret(bufio.NewReader(pr), w)
181
182 return InterpretingWriter{p: pw}
183 }
184
185 // Write writes to the underlying io.Writer while substituting the
186 // color escapes in the input.
187 //
188 // See Interpret for a description of color escapes.
189 func (tw InterpretingWriter) Write(p []byte) (n int, err error) {
190 return tw.p.Write(p)
191 }
192
193 var (
194 // ColorOut is a io.Writer that writes to os.Stdout
195 // while substituting the the color escapes in it's input.
196 //
197 // See Interpret for a description of color escapes.
198 ColorOut io.Writer = NewInterpretingWriter(os.Stdout)
199 // ColorErr is a io.Writer that writes to os.Stderr
200 // while substituting the the color escapes in it's input.
201 //
202 // See Interpret for a description of color escapes.
203 ColorErr io.Writer = NewInterpretingWriter(os.Stderr)
204 )