1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-04 10:34:55 +02:00
lazygit/pkg/utils/color.go

66 lines
1.2 KiB
Go
Raw Normal View History

2021-05-30 07:22:04 +02:00
package utils
import (
"regexp"
2021-10-31 13:29:43 +02:00
"sync"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/samber/lo"
2021-05-30 07:22:04 +02:00
)
2022-03-19 00:38:49 +02:00
var (
decoloriseCache = make(map[string]string)
decoloriseMutex sync.RWMutex
)
2021-10-31 13:29:43 +02:00
2021-05-30 07:22:04 +02:00
// Decolorise strips a string of color
func Decolorise(str string) string {
2021-11-02 07:39:15 +02:00
decoloriseMutex.RLock()
val := decoloriseCache[str]
decoloriseMutex.RUnlock()
2021-10-31 13:29:43 +02:00
2021-11-02 07:39:15 +02:00
if val != "" {
return val
2021-10-31 13:29:43 +02:00
}
2021-10-24 07:07:42 +02:00
re := regexp.MustCompile(`\x1B\[([0-9]{1,3}(;[0-9]{1,3})*)?[mGK]`)
2021-10-31 13:29:43 +02:00
ret := re.ReplaceAllString(str, "")
2021-11-02 07:39:15 +02:00
decoloriseMutex.Lock()
2021-10-31 13:29:43 +02:00
decoloriseCache[str] = ret
2021-11-02 07:39:15 +02:00
decoloriseMutex.Unlock()
2021-10-31 13:29:43 +02:00
return ret
2021-05-30 07:22:04 +02:00
}
2021-07-31 04:54:28 +02:00
func IsValidHexValue(v string) bool {
if len(v) != 4 && len(v) != 7 {
return false
}
if v[0] != '#' {
2021-07-31 04:54:28 +02:00
return false
}
2021-07-31 04:54:28 +02:00
for _, char := range v[1:] {
switch char {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F':
continue
default:
return false
}
}
2021-07-31 04:54:28 +02:00
return true
}
func SetCustomColors(customColors map[string]string) map[string]style.TextStyle {
return lo.MapValues(customColors, func(c string, key string) style.TextStyle {
if s, ok := style.ColorMap[c]; ok {
return s.Foreground
}
return style.New().SetFg(style.NewRGBColor(color.HEX(c, false)))
})
}