-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
auto.go
68 lines (65 loc) · 2.01 KB
/
auto.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
package color
import (
"fmt"
"strings"
)
var colorsToRotate = []string{
Red, Green, Yellow, Blue,
}
// Autof automatically colors the arguments given for a specific format.
// Works exactly like fmt.Sprintf.
//
// WARNING: THIS IS AN EXPERIMENTAL FEATURE AND IT MAY BE REMOVED BASED ON USER FEEDBACK.
// IF YOU USE THIS FEATURE, PLEASE PROVIDE FEEDBACK ON https://github.com/TwiN/go-color/discussions/13
//
// Example:
//
// println(Autof("Hello, %s.", "world"))
func Autof(format string, v ...any) string {
if len(v) == 0 { // || Reset == ""
return fmt.Sprintf(format, v...)
}
currentColorIndex, maxColorIndex := 0, len(colorsToRotate)-1
var insideSpecifier bool
formatLength := len(format)
var lastMergedIndex int
sb := &strings.Builder{}
for i, c := range format {
if format[i] == '%' {
// If the character has a % before or after it, it's just an escaped %, so ignore it
if (i+1 < formatLength && format[i+1] == '%') || (i-1 >= 0 && format[i-1] == '%') {
// %% is an escape sequence for a single %, so we won't color this one
continue
}
// otherwise we're inside a specifier
insideSpecifier = true
// and we need to start coloring it
sb.WriteString(format[lastMergedIndex:i])
sb.WriteString(colorsToRotate[currentColorIndex])
sb.WriteRune(c)
lastMergedIndex = i + 1
currentColorIndex++
if currentColorIndex > maxColorIndex {
currentColorIndex = 0
}
// since we know we're inside a specifier, we can skip the next character now
continue
}
if insideSpecifier {
switch c {
case 'v', 's', 'd', 'f', 'F', 'g', 'G', 'e', 'E', 'x', 'X', 'p', 'b', 'T', 'o', 'O', 'c', 'q', 'U', 'w':
insideSpecifier = false
// this is the end of the specifier, so we'll add the last character of the specifier and stop coloring
sb.WriteString(format[lastMergedIndex : i+1])
sb.WriteString(Reset)
lastMergedIndex = i + 1
default:
}
}
continue
}
if lastMergedIndex < formatLength {
sb.WriteString(format[lastMergedIndex:])
}
return fmt.Sprintf(sb.String(), v...)
}