File: color.go

package info (click to toggle)
golang-github-goccy-go-yaml 1.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,968 kB
  • sloc: javascript: 505; makefile: 57
file content (83 lines) | stat: -rw-r--r-- 1,764 bytes parent folder | download
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
// This source inspired by https://github.com/fatih/color.
package printer

import (
	"fmt"
	"strings"
)

type ColorAttribute int

const (
	ColorReset ColorAttribute = iota
	ColorBold
	ColorFaint
	ColorItalic
	ColorUnderline
	ColorBlinkSlow
	ColorBlinkRapid
	ColorReverseVideo
	ColorConcealed
	ColorCrossedOut
)

const (
	ColorFgHiBlack ColorAttribute = iota + 90
	ColorFgHiRed
	ColorFgHiGreen
	ColorFgHiYellow
	ColorFgHiBlue
	ColorFgHiMagenta
	ColorFgHiCyan
	ColorFgHiWhite
)

const (
	ColorResetBold ColorAttribute = iota + 22
	ColorResetItalic
	ColorResetUnderline
	ColorResetBlinking

	ColorResetReversed
	ColorResetConcealed
	ColorResetCrossedOut
)

const escape = "\x1b"

var colorResetMap = map[ColorAttribute]ColorAttribute{
	ColorBold:         ColorResetBold,
	ColorFaint:        ColorResetBold,
	ColorItalic:       ColorResetItalic,
	ColorUnderline:    ColorResetUnderline,
	ColorBlinkSlow:    ColorResetBlinking,
	ColorBlinkRapid:   ColorResetBlinking,
	ColorReverseVideo: ColorResetReversed,
	ColorConcealed:    ColorResetConcealed,
	ColorCrossedOut:   ColorResetCrossedOut,
}

func format(attrs ...ColorAttribute) string {
	format := make([]string, 0, len(attrs))
	for _, attr := range attrs {
		format = append(format, fmt.Sprint(attr))
	}
	return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";"))
}

func unformat(attrs ...ColorAttribute) string {
	format := make([]string, len(attrs))
	for _, attr := range attrs {
		v := fmt.Sprint(ColorReset)
		reset, exists := colorResetMap[attr]
		if exists {
			v = fmt.Sprint(reset)
		}
		format = append(format, v)
	}
	return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";"))
}

func colorize(msg string, attrs ...ColorAttribute) string {
	return format(attrs...) + msg + unformat(attrs...)
}