-
Notifications
You must be signed in to change notification settings - Fork 0
/
color.go
384 lines (339 loc) · 8.48 KB
/
color.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Copyright 2016 Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// Copyright 2013, Meng Zhang. All rights reserved.
// URL: https://github.com/wsxiaoys/terminal
// File URL: https://github.com/wsxiaoys/terminal/blob/decf4e097e2e3471b254da8d30c3599d330fe7ba/color/color.go
// Package color provides printing in ANSI colors.
//
// TODO: Need to document this. See the Color function for now.
//
// This package uses code from [github.com/wsxiaoys/terminal](https://github.com/wsxiaoys/terminal). Many thanks.
package color
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"golang.org/x/crypto/ssh/terminal"
)
// Mapping from character to concrete escape code.
var codeMap = map[int]int{
'|': 0,
'!': 1,
'.': 2,
'/': 3,
'_': 4,
'^': 5,
'&': 6,
'?': 7,
'-': 8,
'k': 30,
'r': 31,
'g': 32,
'y': 33,
'b': 34,
'm': 35,
'c': 36,
'w': 37,
'd': 39,
'K': 40,
'R': 41,
'G': 42,
'Y': 43,
'B': 44,
'M': 45,
'C': 46,
'W': 47,
'D': 49,
}
// ErrInvalidEscape is an error that is used when the parser panics.
var ErrInvalidEscape = errors.New("invalid escape rune")
var ErrUnexpectedEOF = errors.New("unexpected EOF while parsing")
// ColorReset is the string that resets the text to default style.
const ColorReset = "\033[0m"
// ColorCode compiles a color syntax string like "rG" to escape code.
func ColorCode(s string) string {
attr := 0
fg := 39
bg := 49
for _, key := range s {
c, ok := codeMap[int(key)]
if !ok {
panic("wrong color syntax: " + string(key))
}
switch {
case 0 <= c && c <= 8:
attr = c
case 30 <= c && c <= 37:
fg = c
case 40 <= c && c <= 47:
bg = c
}
}
return fmt.Sprintf("\033[%d;%d;%dm", attr, fg, bg)
}
// Color translates a string into an escaped string.
//
// This example will output the text with a Blue foreground and a Black background
// color.Println("@{bK}Example Text")
//
// This one will output the text with a red foreground
// color.Println("@rExample Text")
//
// This one will escape the @
// color.Println("@@")
//
// Full color syntax code
// @{rgbcmykwRGBCMYKW} foreground/background color
// r/R: Red
// g/G: Green
// b/B: Blue
// c/C: Cyan
// m/M: Magenta
// y/Y: Yellow
// k/K: Black
// w/W: White
// @{|} Reset format style
// @{!./_} Bold / Dim / Italic / Underline
// @{^&} Blink / Fast blink
// @{?} Reverse the foreground and background color
// @{-} Hide the text
// Note some of the functions are not widely supported, like "Fast blink" and "Italic".
func Color(s string, escape rune) string {
return newParser(escape, true).translateReset(s)
}
// Decolor cleans a string of @x color codes.
func Decolor(s string, escape rune) string {
return newParser(escape, false).translateReset(s)
}
// Uncolor cleans a string of ANSI color codes.
func Uncolor(s string) string {
panic("not implemented")
}
type Colorizer struct {
status string
w io.Writer
*parser
}
func New() *Colorizer {
c := &Colorizer{
parser: newParser('@', true),
}
c.SetFile(os.Stdout)
return c
}
func (c *Colorizer) EscapeChar() rune {
return c.parser.escape
}
// String returns the current state, either always or never.
func (c Colorizer) String() string {
return c.status
}
// Returns the name of the type: "Colorizer".
//
// TODO: This is implemented to fulfil the github.com/spf13/pflag.Value interface.
// It's not very well documented what this is for however.
func (c Colorizer) Type() string {
return "Colorizer"
}
// Set sets c on or off, with s one of "auto", "always", or "never",
// otherwise an error is returned.
//
// Note: if "auto" is passed, and SetOutput was passed an io.Writer that
// is not an *os.File, nothing will happen.
// This lets you decide whether you want it to fall back to enabled or disabled.
func (c *Colorizer) Set(s string) (err error) {
switch s {
case "auto":
if w, ok := c.w.(*os.File); ok {
c.SetFile(w)
}
// TODO: Decide what to do in this case. It's a writer, but not to a file,
// so I don't know how it will act. The conservative thing to do would be
// to disable it, the liberal thing would be to allow the user (programmer)
// to decide before-hand what will happen.
case "always":
c.SetEnabled(true)
case "never":
c.SetEnabled(false)
default:
err = errors.New("expect one of auto, always, or never")
}
return err
}
// SetEscapeChar sets the escape character, which can be one of the following characters:
//
// @ * + = ~
//
// If it is none of these characters, then this function panics with ErrInvalidEscape.
func (c *Colorizer) SetEscapeChar(r rune) {
if c.EscapeChar() == r {
return
}
for _, q := range []rune{'*', '@', '+', '=', '~'} {
if r == q {
c.parser.escape = r
return
}
}
panic(ErrInvalidEscape)
}
func (c *Colorizer) Enabled() bool {
return c.parser.color
}
func (c *Colorizer) SetEnabled(b bool) {
if b {
c.status = "always"
} else {
c.status = "never"
}
c.parser.color = b
}
func (c *Colorizer) SetOutput(w io.Writer) {
// TODO: should I set anything here?
c.w = w
}
func (c *Colorizer) SetFile(f *os.File) {
c.SetEnabled(terminal.IsTerminal(int(f.Fd())))
c.status = "auto"
c.w = f
}
func (c *Colorizer) Color(s string) string {
return c.translateReset(s)
}
func (c *Colorizer) colorAny(args []interface{}) []interface{} {
n := len(args)
r := make([]interface{}, n, n+1)
for i, x := range args {
if str, ok := x.(string); ok {
x = c.translateOnly(str)
}
r[i] = x
}
if c.Enabled() {
r = append(r, ColorReset)
}
return r
}
func (c *Colorizer) Print(a ...interface{}) (int, error) {
return fmt.Fprint(c.w, c.colorAny(a)...)
}
func (c *Colorizer) Println(a ...interface{}) (int, error) {
return fmt.Fprintln(c.w, c.colorAny(a)...)
}
func (c *Colorizer) Printf(format string, a ...interface{}) (int, error) {
return fmt.Fprintf(c.w, c.translateReset(format), a...)
}
func (c *Colorizer) Fprint(w io.Writer, a ...interface{}) (int, error) {
return fmt.Fprint(w, c.colorAny(a)...)
}
func (c *Colorizer) Fprintln(w io.Writer, a ...interface{}) (int, error) {
return fmt.Fprintln(w, c.colorAny(a)...)
}
func (c *Colorizer) Fprintf(w io.Writer, format string, a ...interface{}) (int, error) {
return fmt.Fprintf(w, c.translateReset(format), a...)
}
func (c *Colorizer) Sprint(a ...interface{}) string {
return fmt.Sprint(c.colorAny(a)...)
}
func (c *Colorizer) Sprintln(a ...interface{}) string {
return fmt.Sprintln(c.colorAny(a)...)
}
func (c *Colorizer) Sprintf(format string, a ...interface{}) string {
return fmt.Sprintf(c.translateReset(format), a...)
}
type parser struct {
escape rune
color bool
}
func newParser(escape rune, color bool) *parser {
return &parser{
escape: escape,
color: color,
}
}
type handler func(p *parser, in, out *bytes.Buffer) (handler, error)
func (p *parser) translateReset(s string) string {
in := bytes.NewBufferString(s)
out := bytes.NewBufferString("")
var h = handleRegular
var err error
for {
h, err = h(p, in, out)
if err != nil {
panic(err)
}
if h == nil {
break
}
}
if p.color {
out.WriteString(ColorReset)
}
return out.String()
}
func (p *parser) translateOnly(s string) string {
in := bytes.NewBufferString(s)
out := bytes.NewBufferString("")
var h = handleRegular
var err error
for {
h, err = h(p, in, out)
if err != nil {
panic(err)
}
if h == nil {
break
}
}
return out.String()
}
func handleRegular(p *parser, in, out *bytes.Buffer) (handler, error) {
for {
r, _, err := in.ReadRune()
// The only error that can happen here is that we have reached the end of file,
// or that a rune is messed up. If the rune is messed up, we treat it normally.
// This is why we only check for io.EOF.
if err == io.EOF {
break
}
if r == p.escape {
return handleEscape, nil
}
out.WriteRune(r)
}
return nil, nil
}
func handleEscape(p *parser, in, out *bytes.Buffer) (handler, error) {
r, _, err := in.ReadRune()
if err == io.EOF {
return nil, ErrUnexpectedEOF
}
if r == '{' {
return handleEscapeClause, nil
} else if r == p.escape {
out.WriteRune(p.escape)
} else if p.color {
out.WriteString(ColorCode(string(r)))
}
return handleRegular, nil
}
func handleEscapeClause(p *parser, in, out *bytes.Buffer) (handler, error) {
bs := bytes.NewBufferString("")
for {
r, _, err := in.ReadRune()
if err == io.EOF {
return nil, ErrUnexpectedEOF
}
if r == '}' {
break
}
bs.WriteRune(r)
}
if p.color {
out.WriteString(ColorCode(bs.String()))
}
return handleRegular, nil
}