Codebase list golang-github-mitchellh-colorstring-upstream / 8631ce9
ColorPrefix Mitchell Hashimoto 8 years ago
2 changed file(s) with 59 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
66 "fmt"
77 "io"
88 "regexp"
9 "strings"
910 )
1011
1112 // Color colorizes your strings using the default settings.
2425 // If you want to customize any of this behavior, use the Colorize struct.
2526 func Color(v string) string {
2627 return def.Color(v)
28 }
29
30 // ColorPrefix returns the color sequence that prefixes the given text.
31 //
32 // This is useful when wrapping text if you want to inherit the color
33 // of the wrapped text. For example, "[green]foo" will return "[green]".
34 // If there is no color sequence, then this will return "".
35 func ColorPrefix(v string) string {
36 return def.ColorPrefix(v)
2737 }
2838
2939 // Colorize colorizes your strings, giving you the ability to customize
8797 }
8898
8999 return result.String()
100 }
101
102 // ColorPrefix returns the first color sequence that exists in this string.
103 //
104 // For example: "[green]foo" would return "[green]". If no color sequence
105 // exists, then "" is returned. This is especially useful when wrapping
106 // colored texts to inherit the color of the wrapped text.
107 func (c *Colorize) ColorPrefix(v string) string {
108 return prefixRe.FindString(strings.TrimSpace(v))
90109 }
91110
92111 // DefaultColors are the default colors used when colorizing.
158177 }
159178
160179 var def Colorize
161 var parseRe = regexp.MustCompile(`(?i)\[[a-z0-9_-]+\]`)
180 var parseReRaw = `\[[a-z0-9_-]+\]`
181 var parseRe = regexp.MustCompile(`(?i)` + parseReRaw)
182 var prefixRe = regexp.MustCompile(`^(?i)(` + parseReRaw + `)+`)
162183
163184 // Print is a convenience wrapper for fmt.Print with support for color codes.
164185 //
4747
4848 for _, tc := range cases {
4949 actual := Color(tc.Input)
50 if actual != tc.Output {
51 t.Errorf(
52 "Input: %#v\n\nOutput: %#v\n\nExpected: %#v",
53 tc.Input,
54 actual,
55 tc.Output)
56 }
57 }
58 }
59
60 func TestColorPrefix(t *testing.T) {
61 cases := []struct {
62 Input, Output string
63 }{
64 {
65 Input: "foo",
66 Output: "",
67 },
68
69 {
70 Input: "[blue]foo",
71 Output: "[blue]",
72 },
73
74 {
75 Input: "[bold][blue]foo",
76 Output: "[bold][blue]",
77 },
78
79 {
80 Input: " [bold][blue]foo",
81 Output: "[bold][blue]",
82 },
83 }
84
85 for _, tc := range cases {
86 actual := ColorPrefix(tc.Input)
5087 if actual != tc.Output {
5188 t.Errorf(
5289 "Input: %#v\n\nOutput: %#v\n\nExpected: %#v",