1package bug
2
3import (
4 "crypto/sha256"
5 "fmt"
6 "image/color"
7
8 fcolor "github.com/fatih/color"
9
10 "github.com/MichaelMure/git-bug/util/text"
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 := sha256.Sum256([]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 !text.SafeOneLine(str) {
61 return fmt.Errorf("label has unsafe characters")
62 }
63
64 return nil
65}
66
67type LabelColor color.RGBA
68
69func (lc LabelColor) RGBA() color.RGBA {
70 return color.RGBA(lc)
71}
72
73func (lc LabelColor) Term256() Term256 {
74 red := Term256(lc.R) * 6 / 256
75 green := Term256(lc.G) * 6 / 256
76 blue := Term256(lc.B) * 6 / 256
77
78 return red*36 + green*6 + blue + 16
79}
80
81type Term256 int
82
83func (t Term256) Escape() string {
84 if fcolor.NoColor {
85 return ""
86 }
87 return fmt.Sprintf("\x1b[38;5;%dm", t)
88}
89
90func (t Term256) Unescape() string {
91 if fcolor.NoColor {
92 return ""
93 }
94 return "\x1b[0m"
95}