format/color.go

86 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-05-22 21:06:06 +02:00
package main
2022-05-22 22:39:08 +02:00
import (
"fmt"
"strings"
"github.com/fatih/color"
)
2022-05-22 21:06:06 +02:00
var colorCache = map[string]*color.Color{}
2022-05-22 22:39:08 +02:00
func makeColor(colorSpec string) (c *color.Color) {
2022-05-22 21:06:06 +02:00
// caching
2022-05-22 22:39:08 +02:00
if c, ok := colorCache[colorSpec]; ok {
2022-05-22 21:06:06 +02:00
return c
}
2022-05-22 22:39:08 +02:00
defer func() { colorCache[colorSpec] = c }()
splits := strings.Split(colorSpec, ",")
name := strings.TrimSpace(splits[0])
c = color.New()
2022-05-22 21:06:06 +02:00
switch name {
case "black":
2022-05-22 22:39:08 +02:00
c.Add(color.FgBlack)
2022-05-22 21:06:06 +02:00
case "red":
2022-05-22 22:39:08 +02:00
c.Add(color.FgRed)
2022-05-22 21:06:06 +02:00
case "green":
2022-05-22 22:39:08 +02:00
c.Add(color.FgGreen)
2022-05-22 21:06:06 +02:00
case "yellow":
2022-05-22 22:39:08 +02:00
c.Add(color.FgYellow)
2022-05-22 21:06:06 +02:00
case "blue":
2022-05-22 22:39:08 +02:00
c.Add(color.FgBlue)
2022-05-22 21:06:06 +02:00
case "magenta":
2022-05-22 22:39:08 +02:00
c.Add(color.FgMagenta)
2022-05-22 21:06:06 +02:00
case "cyan":
2022-05-22 22:39:08 +02:00
c.Add(color.FgCyan)
2022-05-22 21:06:06 +02:00
case "white":
2022-05-22 22:39:08 +02:00
c.Add(color.FgWhite)
2022-05-22 21:06:06 +02:00
case "":
default:
panic("unknown color name. valid color names: black, red, green, yellow, blue, magenta, cyan, white")
}
2022-05-22 22:39:08 +02:00
if len(splits) >= 2 {
attr := splits[1]
switch attr {
case "bold":
fmt.Println("bold")
c.Add(color.Bold)
case "faint":
fmt.Println("faint")
c.Add(color.Faint)
case "italic":
fmt.Println("italic")
c.Add(color.Italic)
case "underline":
fmt.Println("underline")
c.Add(color.Underline)
case "blink_slow":
fmt.Println("blink_slow")
c.Add(color.BlinkSlow)
case "blink_rapid":
fmt.Println("blink_rapid")
c.Add(color.BlinkRapid)
case "reverse_video":
fmt.Println("reverse_video")
c.Add(color.ReverseVideo)
case "concealed":
fmt.Println("concealed")
c.Add(color.Concealed)
case "crossed_out":
fmt.Println("crossed_out")
c.Add(color.CrossedOut)
case "":
fmt.Println("")
default:
panic("unknown attribute. valid attributes: bold, faint, italic, underline, blink_slow, blink_rapid, reverse_video, concealed, crossed_out")
}
}
return c
2022-05-22 21:06:06 +02:00
}