Compare commits

..

No commits in common. "86590435bdad71bf1e0819431125cbf7c6dd555a" and "cf14f3468e2cd0a834abfc9f7ecad234cbd1bbf4" have entirely different histories.

2 changed files with 18 additions and 45 deletions

View File

@ -1,10 +1,3 @@
# Color # Color
Supported colors: black, white, red, green, blue, yellow, magenta, cyan CLI colors, based on ANSI.
```go
color.Blue.Print("Blue")
color.Blue.Printf("%s", "Blue")
color.Blue.Println("Blue")
blue := color.Blue.String("Blue")
```

View File

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