File: noncolorable.go

package info (click to toggle)
golang-github-mattn-go-colorable 0.0.6-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 92 kB
  • ctags: 60
  • sloc: makefile: 3
file content (57 lines) | stat: -rw-r--r-- 978 bytes parent folder | download | duplicates (3)
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
package colorable

import (
	"bytes"
	"fmt"
	"io"
)

type NonColorable struct {
	out     io.Writer
	lastbuf bytes.Buffer
}

func NewNonColorable(w io.Writer) io.Writer {
	return &NonColorable{out: w}
}

func (w *NonColorable) Write(data []byte) (n int, err error) {
	er := bytes.NewBuffer(data)
loop:
	for {
		c1, _, err := er.ReadRune()
		if err != nil {
			break loop
		}
		if c1 != 0x1b {
			fmt.Fprint(w.out, string(c1))
			continue
		}
		c2, _, err := er.ReadRune()
		if err != nil {
			w.lastbuf.WriteRune(c1)
			break loop
		}
		if c2 != 0x5b {
			w.lastbuf.WriteRune(c1)
			w.lastbuf.WriteRune(c2)
			continue
		}

		var buf bytes.Buffer
		for {
			c, _, err := er.ReadRune()
			if err != nil {
				w.lastbuf.WriteRune(c1)
				w.lastbuf.WriteRune(c2)
				w.lastbuf.Write(buf.Bytes())
				break loop
			}
			if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
				break
			}
			buf.Write([]byte(string(c)))
		}
	}
	return len(data) - w.lastbuf.Len(), nil
}