Convert Figma logo to code with AI

gookit logocolor

🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染

1,496
85
1,496
9

Top Related Projects

7,254

Color package for Go (golang)

1,707

Advanced ANSI style & color support for your terminal applications

1,416

Golang ultimate ANSI-colors that supports Printf/Sprintf methods

Quick Overview

The gookit/color is a Go package that provides a simple and easy-to-use API for adding color and formatting to console output. It supports a wide range of color and formatting options, making it a useful tool for creating more visually appealing and informative command-line applications.

Pros

  • Cross-platform Compatibility: The library works seamlessly across different operating systems, including Windows, macOS, and Linux.
  • Extensive Color Support: It supports a wide range of color options, including 16-bit, 256-bit, and true-color (24-bit) palettes.
  • Flexible Formatting: The library allows you to apply various formatting options, such as bold, italic, underline, and strikethrough, to your console output.
  • Easy to Use: The API is straightforward and intuitive, making it easy to integrate into your Go projects.

Cons

  • Dependency on External Libraries: The library relies on external libraries, such as github.com/mattn/go-isatty and github.com/xo/terminfo, which may increase the complexity of your project's dependencies.
  • Limited Customization: While the library provides a good set of default color and formatting options, it may not offer the level of customization that some developers might require for their specific use cases.
  • Potential Performance Impact: Depending on the complexity of your console output and the frequency of color/formatting changes, the library may have a slight performance impact on your application.
  • Lack of Windows Support for True-color: The library's true-color (24-bit) support is not fully implemented on Windows, which may be a limitation for some users.

Code Examples

Here are a few examples of how to use the gookit/color library in your Go code:

  1. Applying a Single Color:
import "github.com/gookit/color"

color.Red.Println("This text is red.")
color.Green.Printf("This text is %s.\n", "green")
  1. Applying Multiple Colors and Formatting:
import "github.com/gookit/color"

color.Style{color.FgCyan, color.OpBold}.Println("This text is bold and cyan.")
color.Style{color.FgYellow, color.BgBlue, color.OpItalic}.Printf("This text is %s, %s, and %s.\n", "yellow", "blue background", "italic")
  1. Creating Custom Color Styles:
import "github.com/gookit/color"

myStyle := color.New(color.FgWhite, color.BgRed, color.OpBold)
myStyle.Println("This text has a custom style.")
  1. Disabling Color Output:
import "github.com/gookit/color"

color.Disable()
color.Red.Println("This text will not be colored.")

Getting Started

To use the gookit/color library in your Go project, follow these steps:

  1. Install the library using the Go package manager:
go get -u github.com/gookit/color
  1. Import the library in your Go file:
import "github.com/gookit/color"
  1. Use the library's functions to add color and formatting to your console output:
color.Red.Println("This text is red.")
color.Style{color.FgCyan, color.OpBold}.Println("This text is bold and cyan.")
  1. (Optional) Customize the color and formatting options to suit your needs:
myStyle := color.New(color.FgWhite, color.BgRed, color.OpBold)
myStyle.Println("This text has a custom style.")
  1. (Optional) Disable color output if needed:
color.Disable()
color.Red.Println("This text will not be colored.")

That's it! You can now use the gookit/color library to enhance the visual appeal and readability of your Go-based command-line applications.

Competitor Comparisons

7,254

Color package for Go (golang)

Pros of color (fatih)

  • More established and widely used in the Go community
  • Simpler API with fewer functions, making it easier to learn and use
  • Supports Windows console coloring out of the box

Cons of color (fatih)

  • Limited color palette compared to gookit/color
  • Fewer formatting options and styles available
  • Less actively maintained with fewer recent updates

Code Comparison

color (fatih):

color.New(color.FgBlue).Add(color.Bold).Println("Hello, World!")
color.Set(color.FgYellow)
fmt.Println("This is yellow text")
color.Unset()

color (gookit):

color.Blue.Bold.Println("Hello, World!")
color.Yellow.Printf("This is %s text\n", "yellow")
color.Reset()

Both libraries provide similar functionality for basic color output, but gookit/color offers a more fluent interface and additional features for more complex color combinations and styles. The fatih/color library focuses on simplicity and ease of use, while gookit/color provides a wider range of options and customization.

1,707

Advanced ANSI style & color support for your terminal applications

Pros of termenv

  • More comprehensive terminal environment handling, including cursor movement and screen manipulation
  • Better support for color profiles and automatic color space detection
  • Includes utilities for parsing and manipulating ANSI escape sequences

Cons of termenv

  • Slightly more complex API compared to color's straightforward color manipulation functions
  • Fewer pre-defined color constants and named colors
  • Less extensive documentation and examples for basic color operations

Code Comparison

termenv:

p := termenv.ColorProfile()
s := termenv.String("Hello World")
fmt.Println(s.Foreground(p.Color("#ff0000")))

color:

color.Red.Println("Hello World")
color.RGB(255, 0, 0).Println("Hello World")

Both libraries provide functionality for terminal color output, but termenv offers a more comprehensive approach to terminal manipulation. color focuses primarily on color-related operations with a simpler API, while termenv provides a broader set of features for terminal interaction. The choice between the two depends on the specific requirements of your project, with color being more suitable for basic color output and termenv for more complex terminal operations.

1,416

Golang ultimate ANSI-colors that supports Printf/Sprintf methods

Pros of aurora

  • Simpler API with fewer functions, making it easier to learn and use
  • Supports both 8-color and 256-color modes
  • Includes built-in support for gradients and color blending

Cons of aurora

  • Less actively maintained compared to color (last commit over 2 years ago)
  • Fewer features and customization options
  • Limited documentation and examples

Code Comparison

aurora:

aurora.Red("This is red").Bold()
aurora.BgBlue("This has a blue background")
aurora.Cyan("This is cyan").Italic()

color:

color.Red.Println("This is red")
color.BgBlue.Print("This has a blue background")
color.Style{color.FgCyan, color.OpItalic}.Println("This is cyan and italic")

Both libraries provide similar functionality for basic color output, but color offers more granular control over styles and a wider range of formatting options. aurora's chaining syntax may be more intuitive for some users, while color's approach allows for more complex combinations of styles and colors.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

CLI Color

GitHub go.mod Go version Actions Status Codacy Badge GoDoc GitHub tag (latest SemVer) Build Status Coverage Status Go Report Card

A command-line color library with 16/256/True color support, universal API methods and Windows support.

中文说明

Basic color preview:

basic-color

Now, 256 colors and RGB colors have also been supported to work in Windows CMD and PowerShell:

color-on-cmd-pwsh

Features

  • Simple to use, zero dependencies
  • Supports rich color output: 16-color (4-bit), 256-color (8-bit), true color (24-bit, RGB)
    • 16-color output is the most commonly used and most widely supported, working on any Windows version
    • Since v1.2.4 the 256-color (8-bit), true color (24-bit) support windows CMD and PowerShell
    • See this gist for information on true color support
  • Support converts HEX HSL value to RGB color
  • Generic API methods: Print, Printf, Println, Sprint, Sprintf
  • Supports HTML tag-style color rendering, such as <green>message</> <fg=red;bg=blue>text</>.
    • In addition to using built-in tags, it also supports custom color attributes
    • Custom color attributes support the use of 16 color names, 256 color values, rgb color values and hex color values
    • Support working on Windows cmd and powerShell terminal
  • Basic colors: Bold, Black, White, Gray, Red, Green, Yellow, Blue, Magenta, Cyan
  • Additional styles: Info, Note, Light, Error, Danger, Notice, Success, Comment, Primary, Warning, Question, Secondary
  • Support by set NO_COLOR for disable color or use FORCE_COLOR for force open color render.
  • Support Rgb, 256, 16 color conversion

GoDoc

Install

go get github.com/gookit/color

Quick start

package main

import (
	"fmt"

	"github.com/gookit/color"
)

func main() {
	// quick use package func
	color.Redp("Simple to use color")
	color.Redln("Simple to use color")
	color.Greenp("Simple to use color\n")
	color.Cyanln("Simple to use color")
	color.Yellowln("Simple to use color")

	// quick use like fmt.Print*
	color.Red.Println("Simple to use color")
	color.Green.Print("Simple to use color\n")
	color.Cyan.Printf("Simple to use %s\n", "color")
	color.Yellow.Printf("Simple to use %s\n", "color")

	// use like func
	red := color.FgRed.Render
	green := color.FgGreen.Render
	fmt.Printf("%s line %s library\n", red("Command"), green("color"))

	// custom color
	color.New(color.FgWhite, color.BgBlack).Println("custom color style")

	// can also:
	color.Style{color.FgCyan, color.OpBold}.Println("custom color style")

	// internal theme/style:
	color.Info.Tips("message")
	color.Info.Prompt("message")
	color.Info.Println("message")
	color.Warn.Println("message")
	color.Error.Println("message")

	// use style tag
	color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")
	// Custom label attr: Supports the use of 16 color names, 256 color values, rgb color values and hex color values
	color.Println("<fg=11aa23>he</><bg=120,35,156>llo</>, <fg=167;bg=232>wel</><fg=red>come</>")

	// apply a style tag
	color.Tag("info").Println("info style text")

	// prompt message
	color.Info.Prompt("prompt style message")
	color.Warn.Prompt("prompt style message")

	// tips message
	color.Info.Tips("tips style message")
	color.Warn.Tips("tips style message")
}

Run demo: go run ./_examples/demo.go

colored-out

Basic/16 color

Supported on any Windows version. Provide generic API methods: Print, Printf, Println, Sprint, Sprintf

color.Bold.Println("bold message")
color.Cyan.Println("yellow message")
color.Yellow.Println("yellow message")
color.Magenta.Println("yellow message")

// Only use foreground color
color.FgCyan.Printf("Simple to use %s\n", "color")
// Only use background color
color.BgRed.Printf("Simple to use %s\n", "color")

Run demo: go run ./_examples/color_16.go

basic-color

Custom build color

// Full custom: foreground, background, option
myStyle := color.New(color.FgWhite, color.BgBlack, color.OpBold)
myStyle.Println("custom color style")

// can also:
color.Style{color.FgCyan, color.OpBold}.Println("custom color style")

custom set console settings:

// set console color
color.Set(color.FgCyan)

// print message
fmt.Print("message")

// reset console settings
color.Reset()

Additional styles

provide generic API methods: Print, Printf, Println, Sprint, Sprintf

print message use defined style:

color.Info.Println("Info message")
color.Notice.Println("Notice message")
color.Error.Println("Error message")
// ...

Run demo: go run ./_examples/theme_basic.go

theme-basic

Tips style

color.Info.Tips("Info tips message")
color.Notice.Tips("Notice tips message")
color.Error.Tips("Error tips message")
color.Secondary.Tips("Secondary tips message")

Run demo: go run ./_examples/theme_tips.go

theme-tips

Prompt Style

color.Info.Prompt("Info prompt message")
color.Notice.Prompt("Notice prompt message")
color.Error.Prompt("Error prompt message")
// ...

Run demo: go run ./_examples/theme_prompt.go

theme-prompt

Block Style

color.Danger.Block("Danger block message")
color.Warn.Block("Warn block message")
// ...

Run demo: go run ./_examples/theme_block.go

theme-block

256-color usage

256 colors support Windows CMD, PowerShell environment after v1.2.4

Set the foreground or background color

  • color.C256(val uint8, isBg ...bool) Color256
c := color.C256(132) // fg color
c.Println("message")
c.Printf("format %s", "message")

c := color.C256(132, true) // bg color
c.Println("message")
c.Printf("format %s", "message")

256-color style

Can be used to set foreground and background colors at the same time.

  • S256(fgAndBg ...uint8) *Style256
s := color.S256(32, 203)
s.Println("message")
s.Printf("format %s", "message")

with options:

s := color.S256(32, 203)
s.SetOpts(color.Opts{color.OpBold})

s.Println("style with options")
s.Printf("style with %s\n", "options")

Run demo: go run ./_examples/color_256.go

color-tags

RGB/True color

RGB colors support Windows CMD, PowerShell environment after v1.2.4

Preview:

Run demo: Run demo: go run ./_examples/color_rgb.go

color-rgb

example:

color.RGB(30, 144, 255).Println("message. use RGB number")

color.HEX("#1976D2").Println("blue-darken")
color.HEX("#D50000", true).Println("red-accent. use HEX style")

color.RGBStyleFromString("213,0,0").Println("red-accent. use RGB number")
color.HEXStyle("eee", "D50000").Println("deep-purple color")

Set the foreground or background color

  • color.RGB(r, g, b uint8, isBg ...bool) RGBColor
c := color.RGB(30,144,255) // fg color
c.Println("message")
c.Printf("format %s", "message")

c := color.RGB(30,144,255, true) // bg color
c.Println("message")
c.Printf("format %s", "message")

Create a style from an hexadecimal color string:

  • color.HEX(hex string, isBg ...bool) RGBColor
c := color.HEX("ccc") // can also: "cccccc" "#cccccc"
c.Println("message")
c.Printf("format %s", "message")

c = color.HEX("aabbcc", true) // as bg color
c.Println("message")
c.Printf("format %s", "message")

RGB color style

Can be used to set the foreground and background colors at the same time.

  • color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle
s := color.NewRGBStyle(RGB(20, 144, 234), RGB(234, 78, 23))
s.Println("message")
s.Printf("format %s", "message")

Create a style from an hexadecimal color string:

  • color.HEXStyle(fg string, bg ...string) *RGBStyle
s := color.HEXStyle("11aa23", "eee")
s.Println("message")
s.Printf("format %s", "message")

with options:

s := color.HEXStyle("11aa23", "eee")
s.SetOpts(color.Opts{color.OpBold})

s.Println("style with options")
s.Printf("style with %s\n", "options")

HTML-like tag usage

Print,Printf,Println functions support auto parse and render color tags.

	text := `
  <mga1>gookit/color:</>
     A <green>command-line</> 
     <cyan>color library</> with <fg=167;bg=232>256-color</>
     and <fg=11aa23;op=bold>True-color</> support,
     <fg=mga;op=i>universal API</> methods
     and <cyan>Windows</> support.
`
	color.Print(text)

Preview, code please see _examples/demo_tag.go:

demo_tag

Tag formats:

  • Use built in tags: <TAG_NAME>CONTENT</> e.g: <info>message</>
  • Custom tag attributes: <fg=VALUE;bg=VALUE;op=VALUES>CONTENT</> e.g: <fg=167;bg=232>wel</>

Supported on Windows cmd.exe PowerShell.

Examples:

// use style tag
color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>")
color.Println("<suc>hello</>")
color.Println("<error>hello</>")
color.Println("<warning>hello</>")

// custom color attributes
color.Print("<fg=yellow;bg=black;op=underscore;>hello, welcome</>\n")

// Custom label attr: Supports the use of 16 color names, 256 color values, rgb color values and hex color values
color.Println("<fg=11aa23>he</><bg=120,35,156>llo</>, <fg=167;bg=232>wel</><fg=red>come</>")

Tag attributes

tag attributes format:

attr format:
 // VALUE please see var: FgColors, BgColors, AllOptions
 "fg=VALUE;bg=VALUE;op=VALUE"

16 color:
 "fg=yellow"
 "bg=red"
 "op=bold,underscore" // option is allow multi value
 "fg=white;bg=blue;op=bold"
 "fg=white;op=bold,underscore"

256 color:
 "fg=167"
 "fg=167;bg=23"
 "fg=167;bg=23;op=bold"
 
True color:
 // hex
 "fg=fc1cac"
 "fg=fc1cac;bg=c2c3c4"
 // r,g,b
 "fg=23,45,214"
 "fg=23,45,214;bg=109,99,88"

tag attributes parse please see func ParseCodeFromAttr()

Built-in tags

Built-in tags please see var colorTags in color_tag.go

// use style tag
color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>")
color.Println("<suc>hello</>")
color.Println("<error>hello</>")

Run demo: go run ./_examples/color_tag.go

color-tags

Use color.Tag build message:

// set a style tag
color.Tag("info").Print("info style text")
color.Tag("info").Printf("%s style text", "info")
color.Tag("info").Println("info style text")

Color convert

Supports conversion between Rgb, 256, 16 colors, Rgb <=> 256 <=> 16

basic := color.Red
basic.Println("basic color")

c256 := color.Red.C256()
c256.Println("256 color")
c256.C16().Println("basic color")

rgb := color.Red.RGB()
rgb.Println("rgb color")
rgb.C256().Println("256 color")

Convert utils

color has many built-in color conversion utility functions.

func Basic2hex(val uint8) string

func Bg2Fg(val uint8) uint8
func Fg2Bg(val uint8) uint8

func C256ToRgb(val uint8) (rgb []uint8)
func C256ToRgbV1(val uint8) (rgb []uint8)

func Hex2basic(hex string, asBg ...bool) uint8
func Hex2rgb(hex string) []int
func HexToRGB(hex string) []int
func HexToRgb(hex string) (rgb []int)

func HslIntToRgb(h, s, l int) (rgb []uint8)
func HslToRgb(h, s, l float64) (rgb []uint8)
func HsvToRgb(h, s, v int) (rgb []uint8)

func Rgb2ansi(r, g, b uint8, isBg bool) uint8
func Rgb2basic(r, g, b uint8, isBg bool) uint8
func Rgb2hex(rgb []int) string
func Rgb2short(r, g, b uint8) uint8
func RgbTo256(r, g, b uint8) uint8
func RgbTo256Table() map[string]uint8
func RgbToAnsi(r, g, b uint8, isBg bool) uint8
func RgbToHex(rgb []int) string
func RgbToHsl(r, g, b uint8) []float64
func RgbToHslInt(r, g, b uint8) []int

Convert to RGBColor:

  • func RGBFromSlice(rgb []uint8, isBg ...bool) RGBColor
  • func RGBFromString(rgb string, isBg ...bool) RGBColor
  • func HEX(hex string, isBg ...bool) RGBColor
  • func HSL(h, s, l float64, isBg ...bool) RGBColor
  • func HSLInt(h, s, l int, isBg ...bool) RGBColor

Util functions

There are some useful functions reference

  • Disable() disable color render
  • SetOutput(io.Writer) custom set the colored text output writer
  • ForceOpenColor() force open color render
  • Colors2code(colors ...Color) string Convert colors to code. return like "32;45;3"
  • ClearCode(str string) string Use for clear color codes
  • ClearTag(s string) string clear all color html-tag for a string
  • IsConsole(w io.Writer) Determine whether w is one of stderr, stdout, stdin

More useful func please see https://pkg.go.dev/github.com/gookit/color

Detect color level

color automatically checks the color levels supported by the current environment.

// Level is the color level supported by a terminal.
type Level = terminfo.ColorLevel

// terminal color available level alias of the terminfo.ColorLevel*
const (
	LevelNo  = terminfo.ColorLevelNone     // not support color.
	Level16  = terminfo.ColorLevelBasic    // basic - 3/4 bit color supported
	Level256 = terminfo.ColorLevelHundreds // hundreds - 8-bit color supported
	LevelRgb = terminfo.ColorLevelMillions // millions - (24 bit)true color supported
)
  • func SupportColor() bool Whether the current environment supports color output
  • func Support256Color() bool Whether the current environment supports 256-color output
  • func SupportTrueColor() bool Whether the current environment supports (RGB)True-color output
  • func TermColorLevel() Level Get the currently supported color level

Projects using color

Check out these projects, which use https://github.com/gookit/color :

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/slog Concise and extensible go log library
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

See also

License

MIT