Change Code to Color, add better terminal support

This commit is contained in:
Sky Johnson 2024-09-06 08:26:16 -05:00
parent cf14f3468e
commit c93f6e0af0

View File

@ -3,17 +3,15 @@ package color
import ( import (
"fmt" "fmt"
"os" "os"
"strings"
) )
// Whether the terminal supports true color // Color type
var TrueColor = os.Getenv("COLORTERM") == "truecolor" type Color int
// Color code
type Code int
// Color codes // Color codes
const ( const (
Black Code = iota + 30 Black Color = iota + 30
Red Red
Green Green
Yellow Yellow
@ -23,33 +21,55 @@ const (
White White
) )
func (code Code) String(args ...any) string { func (c Color) String(args ...any) string {
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", code, fmt.Sprint(args...)) return fmt.Sprintf("\x1b[%dm%s\x1b[0m", c, fmt.Sprint(args...))
} }
func (code Code) Print(args ...any) { func (c Color) Print(args ...any) {
if !TrueColor { if !supportsColors() {
fmt.Print(args...) fmt.Print(args...)
return return
} }
fmt.Printf("\x1b[%dm%s\x1b[0m", code, fmt.Sprint(args...)) fmt.Printf("\x1b[%dm%s\x1b[0m", c, fmt.Sprint(args...))
} }
func (code Code) Printf(format string, args ...any) { func (c Color) Printf(format string, args ...any) {
if !TrueColor { if !supportsColors() {
fmt.Printf(format, args...) fmt.Printf(format, args...)
return return
} }
fmt.Printf("\x1b[%dm%s\x1b[0m", code, fmt.Sprintf(format, args...)) fmt.Printf("\x1b[%dm%s\x1b[0m", c, fmt.Sprintf(format, args...))
} }
func (code Code) Println(args ...any) { func (c Color) Println(args ...any) {
if !TrueColor { if !supportsColors() {
fmt.Println(args...) fmt.Println(args...)
return return
} }
fmt.Printf("\x1b[%dm%s\x1b[0m\n", code, fmt.Sprint(args...)) 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
} }