Color/color.go

76 lines
1.3 KiB
Go

package color
import (
"fmt"
"os"
"strings"
)
// Color type
type Color int
// Color codes
const (
Black Color = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
White
)
func (c Color) String(args ...any) string {
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", c, fmt.Sprint(args...))
}
func (c Color) Print(args ...any) {
if !supportsColors() {
fmt.Print(args...)
return
}
fmt.Printf("\x1b[%dm%s\x1b[0m", c, fmt.Sprint(args...))
}
func (c Color) Printf(format string, args ...any) {
if !supportsColors() {
fmt.Printf(format, args...)
return
}
fmt.Printf("\x1b[%dm%s\x1b[0m", c, fmt.Sprintf(format, args...))
}
func (c Color) Println(args ...any) {
if !supportsColors() {
fmt.Println(args...)
return
}
fmt.Printf("\x1b[%dm%s\x1b[0m\n", c, fmt.Sprint(args...))
}
func supportsColors() bool {
colorterm := os.Getenv("COLORTERM")
term := os.Getenv("TERM")
// Check for true color (24-bit support)
if strings.Contains(colorterm, "truecolor") || strings.Contains(colorterm, "24bit") {
return true
}
// Check for 256 colors support
if strings.Contains(term, "256color") {
return true
}
// Check for basic color support
if term == "xterm" || term == "screen" || term == "vt100" || strings.Contains(term, "color") {
return true
}
return false
}