Files
lazygit/pkg/utils/color.go
T
Stefan HallerandClaude Opus 5.5 ae1b43dc96 Extract converting a configured color to a text style
The next commit needs it for a single color.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 08:16:06 +02:00

76 lines
1.6 KiB
Go

package utils
import (
"regexp"
"sync"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/samber/lo"
)
var (
decoloriseCache = make(map[string]string)
decoloriseMutex sync.RWMutex
colorCodeRe = regexp.MustCompile(`\x1B\[([0-9]{1,3}(;[0-9]{1,3})*)?[mGK]`)
linkRe = regexp.MustCompile(`\x1B]8;[^;]*;(.*?)(\x1B.|\x07)`)
)
// Decolorise strips a string of color
func Decolorise(str string) string {
decoloriseMutex.RLock()
val, ok := decoloriseCache[str]
decoloriseMutex.RUnlock()
if ok {
return val
}
ret := colorCodeRe.ReplaceAllString(str, "")
ret = linkRe.ReplaceAllString(ret, "")
decoloriseMutex.Lock()
decoloriseCache[str] = ret
decoloriseMutex.Unlock()
return ret
}
func IsValidHexValue(v string) bool {
if len(v) != 4 && len(v) != 7 {
return false
}
if v[0] != '#' {
return false
}
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
}
}
return true
}
func SetCustomColors(customColors map[string]string) map[string]*style.TextStyle {
return lo.MapValues(customColors, func(c string, key string) *style.TextStyle {
value := CustomColorStyle(c)
return &value
})
}
// CustomColorStyle returns the text style for a color that the user
// configured, either by the name of a terminal color or as a hex value.
func CustomColorStyle(c string) style.TextStyle {
if s, ok := style.ColorMap[c]; ok {
return s.Foreground
}
return style.New().SetFg(style.NewRGBColor(color.HEX(c, false)))
}