43 lines
1015 B
Go
Raw Normal View History

2024-03-05 17:47:02 +01:00
package color
import (
"fmt"
)
// Color represents an RGB color.
type Color struct {
2024-03-06 00:18:51 +01:00
R Value
G Value
B Value
2024-03-05 17:47:02 +01:00
}
// Print writes the text in the given color to standard output.
2024-03-11 22:08:28 +01:00
func (c Color) Print(args ...any) {
2024-03-05 17:47:02 +01:00
if !Terminal {
2024-03-11 22:08:28 +01:00
fmt.Print(args...)
2024-03-05 19:10:27 +01:00
return
2024-03-05 17:47:02 +01:00
}
2024-03-11 22:08:28 +01:00
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
}
2024-03-11 23:28:37 +01:00
// Printf formats according to a format specifier and writes the text in the given color to standard output.
2024-03-11 22:08:28 +01:00
func (c Color) Printf(format string, args ...any) {
if !Terminal {
fmt.Printf(format, args...)
return
}
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprintf(format, args...))
2024-03-05 17:47:02 +01:00
}
// Println writes the text in the given color to standard output and appends a newline.
2024-03-11 22:08:28 +01:00
func (c Color) Println(args ...any) {
2024-03-05 17:47:02 +01:00
if !Terminal {
2024-03-11 22:08:28 +01:00
fmt.Println(args...)
2024-03-05 19:10:27 +01:00
return
2024-03-05 17:47:02 +01:00
}
2024-03-11 22:08:28 +01:00
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\n\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
2024-03-05 17:47:02 +01:00
}