| 1 | // This source inspired by https://github.com/fatih/color. |
| 2 | package printer |
| 3 | |
| 4 | import ( |
| 5 | "fmt" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | type ColorAttribute int |
| 10 | |
| 11 | const ( |
| 12 | ColorReset ColorAttribute = iota |
| 13 | ColorBold |
| 14 | ColorFaint |
| 15 | ColorItalic |
| 16 | ColorUnderline |
| 17 | ColorBlinkSlow |
| 18 | ColorBlinkRapid |
| 19 | ColorReverseVideo |
| 20 | ColorConcealed |
| 21 | ColorCrossedOut |
| 22 | ) |
| 23 | |
| 24 | const ( |
| 25 | ColorFgHiBlack ColorAttribute = iota + 90 |
| 26 | ColorFgHiRed |
| 27 | ColorFgHiGreen |
| 28 | ColorFgHiYellow |
| 29 | ColorFgHiBlue |
| 30 | ColorFgHiMagenta |
| 31 | ColorFgHiCyan |
| 32 | ColorFgHiWhite |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | ColorResetBold ColorAttribute = iota + 22 |
| 37 | ColorResetItalic |
| 38 | ColorResetUnderline |
| 39 | ColorResetBlinking |
| 40 | |
| 41 | ColorResetReversed |
| 42 | ColorResetConcealed |
| 43 | ColorResetCrossedOut |
| 44 | ) |
| 45 | |
| 46 | const escape = "\x1b" |
| 47 | |
| 48 | var colorResetMap = map[ColorAttribute]ColorAttribute{ |
| 49 | ColorBold: ColorResetBold, |
| 50 | ColorFaint: ColorResetBold, |
| 51 | ColorItalic: ColorResetItalic, |
| 52 | ColorUnderline: ColorResetUnderline, |
| 53 | ColorBlinkSlow: ColorResetBlinking, |
| 54 | ColorBlinkRapid: ColorResetBlinking, |
| 55 | ColorReverseVideo: ColorResetReversed, |
| 56 | ColorConcealed: ColorResetConcealed, |
| 57 | ColorCrossedOut: ColorResetCrossedOut, |
| 58 | } |
| 59 | |
| 60 | func format(attrs ...ColorAttribute) string { |
| 61 | format := make([]string, 0, len(attrs)) |
| 62 | for _, attr := range attrs { |
| 63 | format = append(format, fmt.Sprint(attr)) |
| 64 | } |
| 65 | return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";")) |
| 66 | } |
| 67 | |
| 68 | func unformat(attrs ...ColorAttribute) string { |
| 69 | format := make([]string, len(attrs)) |
| 70 | for _, attr := range attrs { |
| 71 | v := fmt.Sprint(ColorReset) |
| 72 | reset, exists := colorResetMap[attr] |
| 73 | if exists { |
| 74 | v = fmt.Sprint(reset) |
| 75 | } |
| 76 | format = append(format, v) |
| 77 | } |
| 78 | return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";")) |
| 79 | } |
| 80 | |
| 81 | func colorize(msg string, attrs ...ColorAttribute) string { |
| 82 | return format(attrs...) + msg + unformat(attrs...) |
| 83 | } |