From cf14f3468e2cd0a834abfc9f7ecad234cbd1bbf4 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Wed, 28 Aug 2024 09:37:42 -0500 Subject: [PATCH] Initial version --- color.go | 55 +++++++++++++++++++++++++++++++++++++++++++++ go.mod | 3 +++ go.sum | 0 tests/color_test.go | 40 +++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+) create mode 100644 color.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 tests/color_test.go diff --git a/color.go b/color.go new file mode 100644 index 0000000..1818a11 --- /dev/null +++ b/color.go @@ -0,0 +1,55 @@ +package color + +import ( + "fmt" + "os" +) + +// Whether the terminal supports true color +var TrueColor = os.Getenv("COLORTERM") == "truecolor" + +// Color code +type Code int + +// Color codes +const ( + Black Code = iota + 30 + Red + Green + Yellow + Blue + Magenta + Cyan + White +) + +func (code Code) String(args ...any) string { + return fmt.Sprintf("\x1b[%dm%s\x1b[0m", code, fmt.Sprint(args...)) +} + +func (code Code) Print(args ...any) { + if !TrueColor { + fmt.Print(args...) + return + } + + fmt.Printf("\x1b[%dm%s\x1b[0m", code, fmt.Sprint(args...)) +} + +func (code Code) Printf(format string, args ...any) { + if !TrueColor { + fmt.Printf(format, args...) + return + } + + fmt.Printf("\x1b[%dm%s\x1b[0m", code, fmt.Sprintf(format, args...)) +} + +func (code Code) Println(args ...any) { + if !TrueColor { + fmt.Println(args...) + return + } + + fmt.Printf("\x1b[%dm%s\x1b[0m\n", code, fmt.Sprint(args...)) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2be1b06 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.sharkk.net/Go/Color + +go 1.23.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/tests/color_test.go b/tests/color_test.go new file mode 100644 index 0000000..dbb9bc8 --- /dev/null +++ b/tests/color_test.go @@ -0,0 +1,40 @@ +package color_test + +import ( + "testing" + + color "git.sharkk.net/Go/Color" +) + +func TestPrint(t *testing.T) { + color.Black.Print("Black\n") + color.White.Print("White\n") + color.Red.Print("Red\n") + color.Green.Print("Green\n") + color.Blue.Print("Blue\n") + color.Yellow.Print("Yellow\n") + color.Magenta.Print("Magenta\n") + color.Cyan.Print("Cyan\n") +} + +func TestPrintf(t *testing.T) { + color.Black.Printf("%s\n", "Black") + color.White.Printf("%s\n", "White") + color.Red.Printf("%s\n", "Red") + color.Green.Printf("%s\n", "Green") + color.Blue.Printf("%s\n", "Blue") + color.Yellow.Printf("%s\n", "Yellow") + color.Magenta.Printf("%s\n", "Magenta") + color.Cyan.Printf("%s\n", "Cyan") +} + +func TestPrintln(t *testing.T) { + color.Black.Println("Black") + color.White.Println("White") + color.Red.Println("Red") + color.Green.Println("Green") + color.Blue.Println("Blue") + color.Yellow.Println("Yellow") + color.Magenta.Println("Magenta") + color.Cyan.Println("Cyan") +}