label.go

 1package bug
 2
 3import (
 4	"crypto/sha1"
 5	"fmt"
 6	"image/color"
 7	"strings"
 8
 9	"github.com/MichaelMure/git-bug/util/text"
10	fcolor "github.com/fatih/color"
11)
12
13type Label string
14
15func (l Label) String() string {
16	return string(l)
17}
18
19// RGBA from a Label computed in a deterministic way
20func (l Label) Color() LabelColor {
21	// colors from: https://material-ui.com/style/color/
22	colors := []LabelColor{
23		{R: 244, G: 67, B: 54, A: 255},   // red
24		{R: 233, G: 30, B: 99, A: 255},   // pink
25		{R: 156, G: 39, B: 176, A: 255},  // purple
26		{R: 103, G: 58, B: 183, A: 255},  // deepPurple
27		{R: 63, G: 81, B: 181, A: 255},   // indigo
28		{R: 33, G: 150, B: 243, A: 255},  // blue
29		{R: 3, G: 169, B: 244, A: 255},   // lightBlue
30		{R: 0, G: 188, B: 212, A: 255},   // cyan
31		{R: 0, G: 150, B: 136, A: 255},   // teal
32		{R: 76, G: 175, B: 80, A: 255},   // green
33		{R: 139, G: 195, B: 74, A: 255},  // lightGreen
34		{R: 205, G: 220, B: 57, A: 255},  // lime
35		{R: 255, G: 235, B: 59, A: 255},  // yellow
36		{R: 255, G: 193, B: 7, A: 255},   // amber
37		{R: 255, G: 152, B: 0, A: 255},   // orange
38		{R: 255, G: 87, B: 34, A: 255},   // deepOrange
39		{R: 121, G: 85, B: 72, A: 255},   // brown
40		{R: 158, G: 158, B: 158, A: 255}, // grey
41		{R: 96, G: 125, B: 139, A: 255},  // blueGrey
42	}
43
44	id := 0
45	hash := sha1.Sum([]byte(l))
46	for _, char := range hash {
47		id = (id + int(char)) % len(colors)
48	}
49
50	return colors[id]
51}
52
53func (l Label) Validate() error {
54	str := string(l)
55
56	if text.Empty(str) {
57		return fmt.Errorf("empty")
58	}
59
60	if strings.Contains(str, "\n") {
61		return fmt.Errorf("should be a single line")
62	}
63
64	if !text.Safe(str) {
65		return fmt.Errorf("not fully printable")
66	}
67
68	return nil
69}
70
71type LabelColor color.RGBA
72
73func (lc LabelColor) RGBA() color.RGBA {
74	return color.RGBA(lc)
75}
76
77func (lc LabelColor) Term256() Term256 {
78	red := Term256(lc.R) * 6 / 256
79	green := Term256(lc.G) * 6 / 256
80	blue := Term256(lc.B) * 6 / 256
81
82	return red*36 + green*6 + blue + 16
83}
84
85type Term256 int
86
87func (t Term256) Escape() string {
88	if fcolor.NoColor {
89		return ""
90	}
91	return fmt.Sprintf("\x1b[38;5;%dm", t)
92}
93
94func (t Term256) Unescape() string {
95	if fcolor.NoColor {
96		return ""
97	}
98	return "\x1b[0m"
99}