Use color helper to retrieve correct ANSI color index

This commit is contained in:
Christian Muehlhaeuser
2019-12-05 11:55:24 +01:00
parent 39a6da5fe7
commit cb80cfbb36
+19 -22
View File
@@ -1,6 +1,7 @@
package gold package gold
import ( import (
"errors"
"io" "io"
"strconv" "strconv"
@@ -15,6 +16,18 @@ type BaseElement struct {
Style StyleType Style StyleType
} }
func color(c string) (uint8, error) {
if len(c) == 0 {
return 0, errors.New("Invalid color")
}
if c[0] == '#' {
i, err := hexToANSIColor(c)
return uint8(i), err
}
i, err := strconv.Atoi(c)
return uint8(i), err
}
func renderText(w io.Writer, rules *ElementStyle, s string) { func renderText(w io.Writer, rules *ElementStyle, s string) {
if len(s) == 0 { if len(s) == 0 {
return return
@@ -23,29 +36,13 @@ func renderText(w io.Writer, rules *ElementStyle, s string) {
out := aurora.Reset(s) out := aurora.Reset(s)
if rules != nil { if rules != nil {
if rules.Color != "" { i, err := color(rules.Color)
var i int if err == nil {
var err error out = out.Index(i)
if rules.Color[0] == '#' {
i, err = hexToANSIColor(rules.Color)
} else {
i, err = strconv.Atoi(rules.Color)
}
if err == nil && i >= 0 && i <= 255 {
out = out.Index(uint8(i))
}
} }
if rules.BackgroundColor != "" { i, err = color(rules.BackgroundColor)
var i int if err == nil {
var err error out = out.BgIndex(i)
if rules.BackgroundColor[0] == '#' {
i, err = hexToANSIColor(rules.BackgroundColor)
} else {
i, err = strconv.Atoi(rules.BackgroundColor)
}
if err == nil && i >= 0 && i <= 255 {
out = out.BgIndex(uint8(i))
}
} }
if rules.Underline { if rules.Underline {