-
Notifications
You must be signed in to change notification settings - Fork 0
/
gocolor.go
86 lines (68 loc) · 1.56 KB
/
gocolor.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
package gocolor
import (
"fmt"
"github.com/shiena/ansicolor"
"io"
"os"
"regexp"
"runtime"
"strings"
)
const (
startSeq = "\033["
endSeq = "\033[0m"
)
type textPrint struct {
text string
}
var colors map[string]string
var Out io.Writer
var (
colorGroupRE *regexp.Regexp = regexp.MustCompile(`(\{\w*\}[^{}]+)`)
colorPartRE *regexp.Regexp = regexp.MustCompile(`{(\w*)}`)
textPartRE *regexp.Regexp = regexp.MustCompile(`^{\w*}(.*)`)
)
func (p *textPrint) In(color string) {
p.text = "{" + color + "}" + p.text
p.inFormat()
}
func (p *textPrint) inFormat() {
matches := colorGroupRE.FindAllStringSubmatch(p.text, -1)
for _, value := range matches {
color := colorPartRE.FindStringSubmatch(value[0])[1]
colorcode := getColor(color)
text := textPartRE.FindStringSubmatch(value[0])[1]
clifmt := startSeq + colorcode + text + endSeq
p.text = strings.Replace(p.text, value[0], clifmt, -1)
}
fmt.Fprintln(Out, p.text)
}
func init() {
colors = make(map[string]string)
colors["black"] = "30m"
colors["red"] = "31m"
colors["green"] = "32m"
colors["yellow"] = "33m"
colors["blue"] = "34m"
colors["magenta"] = "35m"
colors["cyan"] = "36m"
colors["white"] = "37m"
colors["default"] = "39m"
if runtime.GOOS == "windows" {
Out = ansicolor.NewAnsiColorWriter(os.Stdout)
} else {
Out = os.Stdout
}
}
func getColor(color string) string {
var colorcode string
if value, ok := colors[color]; ok {
colorcode = value
} else {
colorcode = colors["default"]
}
return colorcode
}
func Print(color string) *textPrint {
return &textPrint{color}
}