-
Notifications
You must be signed in to change notification settings - Fork 0
/
rich.go
264 lines (221 loc) · 6.65 KB
/
rich.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
package rich
// (c) 2024 by github.com/rvfet
// This package is a simple utility to print the formatted text with colors and styles in the terminal.
// Inspired by the rich library in Python.
import (
"fmt"
"reflect"
"regexp"
"strings"
)
type Style struct {
Name string
Code string
IsColor bool
}
var KeywordMap = map[string]string{
"SUCCESS": "green",
"ERROR": "red",
"WARNING": "yellow",
"INFO": "cyan",
"DEBUG": "gray",
}
var IconMap = map[string]string{
"mail": "",
"github.com": "",
"github.dev": "",
"github.io": "",
"facebook.com": "",
"fb.me": "",
"telegram.org": "",
"t.me": "",
"google.com": "",
"youtube.com": "",
"yt.be": "",
"youtu.be": "",
"instagram.com": "",
"ig.me": "",
"translate.google.com": "",
"openai.com": "",
"go.dev": "",
"golang.org": "",
"python.org": "",
"spotify.com": "",
}
var (
styles = []Style{
{Name: "reset", Code: "0", IsColor: false},
{Name: "unstyle", Code: "22", IsColor: false},
{Name: "b", Code: "1", IsColor: false},
{Name: "i", Code: "3", IsColor: false},
{Name: "u", Code: "4", IsColor: false},
{Name: "s", Code: "9", IsColor: false},
{Name: "blink", Code: "5", IsColor: false},
{Name: "x", Code: "7", IsColor: false},
{Name: "white", Code: "97", IsColor: true},
{Name: "gray", Code: "37", IsColor: true},
{Name: "red", Code: "31", IsColor: true},
{Name: "green", Code: "32", IsColor: true},
{Name: "cyan", Code: "36", IsColor: true},
{Name: "blue", Code: "34", IsColor: true},
{Name: "yellow", Code: "33", IsColor: true},
}
styleMap = make(map[string]Style)
)
var formatterMap map[reflect.Kind]func(reflect.Value) string
func init() {
for _, style := range styles {
styleMap[style.Name] = style
}
formatterMap = map[reflect.Kind]func(reflect.Value) string{
reflect.String: formatString,
reflect.Bool: formatBool,
reflect.Float32: formatNumber,
reflect.Float64: formatNumber,
reflect.Int: formatNumber,
reflect.Int8: formatNumber,
reflect.Int16: formatNumber,
reflect.Int32: formatNumber,
reflect.Int64: formatNumber,
reflect.Uint: formatNumber,
reflect.Uint8: formatNumber,
reflect.Uint16: formatNumber,
reflect.Uint32: formatNumber,
reflect.Uint64: formatNumber,
reflect.Map: formatMap,
reflect.Slice: formatSlice,
reflect.Struct: formatStruct,
}
}
func parseTags(str string) string {
var stack []string
segments := strings.Split(str, "[")
for index, segment := range segments {
if index == 0 {
continue
}
parts := strings.SplitN(segment, "]", 2)
if len(parts) != 2 {
continue
}
tags, rest := parts[0], parts[1]
for _, tag := range strings.Fields(tags) {
tag = strings.ToLower(strings.Trim(tag, "[]"))
if tag == "/" {
stack = nil
} else if strings.HasPrefix(tag, "/") {
if len(stack) > 0 {
stack = stack[:len(stack)-1]
}
} else if style, ok := styleMap[tag]; ok {
stack = append(stack, style.Code)
}
}
segments[index] = applyStyling(rest, stack)
}
return strings.Join(segments, "")
}
func applyStyling(str string, stack []string) string {
return fmt.Sprintf("\033[%sm%s", strings.Join(stack, ";"), str)
}
func formatValue(value reflect.Value) string {
if formatter, ok := formatterMap[value.Kind()]; ok {
return formatter(value)
}
return formatString(value)
}
func formatString(str reflect.Value) string {
urlRe := `((http|https):\/\/)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(:[0-9]{1,5})?(\/[^:;\|\s\t]+)?`
emailRe := `([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})`
if matched, _ := regexp.MatchString(urlRe, fmt.Sprintf("%v", str)); matched {
for domain, icon := range IconMap {
if strings.Contains(fmt.Sprintf("%v", str), domain) {
return parseTags(fmt.Sprintf("[cyan]%v %v[/]", icon, str))
}
}
}
if matched, _ := regexp.MatchString(emailRe, fmt.Sprintf("%v", str)); matched {
return parseTags(fmt.Sprintf("[cyan]%v %v[/]", IconMap["mail"], str))
}
return parseTags(fmt.Sprintf("%v", str))
}
func formatBool(value reflect.Value) string {
if reflect.ValueOf(value.Interface()).Bool() {
return parseTags("[green][bold]true[/]")
}
return parseTags("[red][bold]false[/]")
}
func formatNumber(value reflect.Value) string {
return parseTags(fmt.Sprintf("[cyan][bold]%v[/]", value))
}
func formatMap(value reflect.Value) string {
var result strings.Builder
result.WriteString("{\n")
for _, key := range value.MapKeys() {
leftSideType := reflect.ValueOf(key.Interface()).Kind()
rightSideType := reflect.ValueOf(value.MapIndex(key).Interface()).Kind()
leftSide := parseTags(fmt.Sprintf("[yellow]%s[/]", formatterMap[leftSideType](key)))
rightSide := formatterMap[rightSideType](value.MapIndex(key))
result.WriteString(fmt.Sprintf(" %s: %s,\n", leftSide, rightSide))
}
result.WriteString("}")
return result.String()
}
func formatSlice(value reflect.Value) string {
var result strings.Builder
result.WriteString("[ ")
for index := range make([]struct{}, value.Len()) {
element := value.Index(index)
elementType := reflect.ValueOf(element.Interface()).Kind()
result.WriteString(formatterMap[elementType](element))
if index < value.Len()-1 {
result.WriteString(", ")
}
}
result.WriteString(" ]")
return result.String()
}
func formatStruct(value reflect.Value) string {
var result strings.Builder
result.WriteString("{\n")
for index := range value.NumField() {
leftSide := parseTags(fmt.Sprintf("[yellow]%s[/]", value.Type().Field(index).Name))
rightSide := formatValue(value.Field(index))
result.WriteString(fmt.Sprintf(" %s: %s,\n", leftSide, rightSide))
}
result.WriteString("}")
return result.String()
}
func Print(args ...any) {
formattedStrings := make([]string, 0, len(args))
for _, arg := range args {
formattedStrings = append(formattedStrings, formatValue(reflect.ValueOf(arg)))
}
fmt.Println(strings.Join(formattedStrings, " "))
}
func logWithPrefix(prefix string, args ...any) {
var pad string
if len(pad) < 10 {
pad += strings.Repeat(" ", 8-len(prefix))
}
if color, ok := KeywordMap[prefix]; ok {
prefix = fmt.Sprintf("[%s]%s[/]", color, prefix)
}
prefix += pad
Print(append([]any{prefix}, args...)...)
}
func Info(args ...any) {
logWithPrefix("INFO", args...)
}
func Success(args ...any) {
logWithPrefix("SUCCESS", args...)
}
func Error(args ...any) {
logWithPrefix("ERROR", args...)
}
func Warning(args ...any) {
logWithPrefix("WARNING", args...)
}
func Debug(args ...any) {
logWithPrefix("DEBUG", args...)
}