color

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2018 License: MIT Imports: 4 Imported by: 2,553

README

cli color

Command line color library, written using golang

中文说明

Features

  • Easy to use
  • supports rich color output
  • supports html tab-style color rendering
  • compatible with Windows

Install

  • use dep
dep ensure -add gopkg.in/gookit/color.v1 // is recommended
// OR
dep ensure -add github.com/gookit/color
  • go get
go get gopkg.in/gookit/color.v1 // is recommended
// OR
go get -u github.com/gookit/color
  • git clone
git clone https://github.com/gookit/color

Godoc

Quick start

import "gopkg.in/gookit/color.v1" // is recommended
// or
import "github.com/gookit/color"
package main

import (
    "github.com/gookit/color"
)

func main() {
	// simple usage
	color.FgCyan.Printf("Simple to use %s\n", "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")
	
	// use style tag
	color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")

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

	// use info style tips
	color.Tips("info").Print("tips style text")

	// use info style blocked tips
	color.LiteTips("info").Print("blocked tips style text")
}
Color output display

colored-out

More usage
Basic color functions

support on windows cmd.exe

  • color.Bold(args ...interface{})
  • color.Black(args ...interface{})
  • color.White(args ...interface{})
  • color.Gray(args ...interface{})
  • color.Red(args ...interface{})
  • color.Green(args ...interface{})
  • color.Yellow(args ...interface{})
  • color.Blue(args ...interface{})
  • color.Magenta(args ...interface{})
  • color.Cyan(args ...interface{})
color.Bold("bold message")
color.Yellow("yellow message")
Extra style functions

support on windows cmd.exe

  • color.Info()
  • color.Note()
  • color.Light()
  • color.Error()
  • color.Danger()
  • color.Notice()
  • color.Success()
  • color.Comment()
  • color.Primary()
  • color.Warning()
  • color.Question()
  • color.Secondary()
color.Info("Info message")
color.Success("Success message")
Use like html tag

not support on windows cmd.exe

// 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")
  • color.Tag
// 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")
Internal color tags
// Some internal defined style tags
// usage: <tag>content text</>

// basic tags
- red
- blue
- cyan
- black
- green
- brown
- white
- default  // no color
- normal// no color
- yellow  
- magenta 

// alert tags like bootstrap's alert
- suc // same "green" and "bold"
- success 
- info // same "green"
- comment  // same "brown"
- note 
- notice  
- warn
- warning 
- primary 
- danger // same "red"
- err 
- error

// more tags
- lightRed
- light_red
- lightGreen
- light_green
- lightBlue 
- light_blue
- lightCyan
- light_cyan
- lightDray
- light_gray
- gray
- darkGray
- dark_gray
- lightYellow
- light_yellow  
- lightMagenta  
- light_magenta 

// extra
- lightRedEx
- light_red_ex
- lightGreenEx
- light_green_ex 
- lightBlueEx
- light_blue_ex  
- lightCyanEx
- light_cyan_ex  
- whiteEx
- white_ex

// option
- bold
- underscore 
- reverse

Ref

License

MIT

Documentation

Index

Constants

View Source
const (
	// Regex to match color tags
	// golang 不支持反向引用.  即不支持使用 \1 引用第一个匹配 ([a-z=;]+)
	// TagExpr = `<([a-z=;]+)>(.*?)<\/\1>`
	// 所以调整一下 统一使用 `</>` 来结束标签,例如 "<info>some text</>"
	// 支持自定义颜色属性的tag "<fg=white;bg=blue;op=bold>content</>"
	// (?s:...) s - 让 "." 匹配换行
	TagExpr = `<([a-zA-Z_=,;]+)>(?s:(.*?))<\/>`

	// Regex to match color attributes
	AttrExpr = `(fg|bg|op)=([a-z,]+);?`

	// Regex used for removing color tags
	// StripExpr = `<[\/]?[a-zA-Z=;]+>`
	// 随着上面的做一些调整
	StripExpr = `<[\/]?[a-zA-Z_=,;]*>`
)

output colored text like use html tag. (not support windows cmd)

View Source
const CodeExpr = `\033\[[\d;?]+m`

Regex to clear color codes eg "\033[1;36mText\x1b[0m"

View Source
const FullColorTpl = "\x1b[%sm%s\x1b[0m"
View Source
const ResetCode = "\x1b[0m"

ESC 操作的表示 "\033"(Octal 8进制) = "\x1b"(Hexadecimal 16进制) = 27 (10进制)

View Source
const SetRgbBg = "\x1b[48;2;%d;%d;%dm"
View Source
const SetRgbFg = "\x1b[38;2;%d;%d;%dm"

24 byte RGB color RGB:

R 0-255 G 0-255 B 0-255
R 00-FF G 00-FF B 00-FF (16进制)

format:

ESC[ … 38;2;<r>;<g>;<b> … m // 选择RGB前景色
ESC[ … 48;2;<r>;<g>;<b> … m // 选择RGB背景色

links:

https://zh.wikipedia.org/wiki/ANSI转义序列#24位
View Source
const SettingTpl = "\x1b[%sm"

CLI color template

View Source
const SingleColorTpl = "\x1b[%dm%s\x1b[0m"
View Source
const Tpl256Bg = "48;5;%d"
View Source
const Tpl256Fg = "38;5;%d"

8 byte 256 color(`2^8`) format:

	ESC[ … 38;5;<n> … m // 选择前景色
 ESC[ … 48;5;<n> … m // 选择背景色

example:

fg "\x1b[38;5;242m"
bg "\x1b[48;5;208m"
both "\x1b[38;5;242;48;5;208m"

links:

https://zh.wikipedia.org/wiki/ANSI转义序列#8位

Variables

View Source
var BgColors = map[string]Color{
	"black":   BgBlack,
	"red":     BgRed,
	"green":   BgGreen,
	"yellow":  BgYellow,
	"blue":    BgBlue,
	"magenta": BgMagenta,
	"cyan":    BgCyan,
	"white":   BgWhite,
	"default": BgDefault,
}

Background colors map

View Source
var BuiltinStyles = map[string]Style{
	"info":      {OpReset, FgGreen},
	"note":      {OpBold, FgLightCyan},
	"light":     {FgLightWhite},
	"error":     {FgLightWhite, BgRed},
	"danger":    {OpBold, FgRed},
	"notice":    {OpBold, FgCyan},
	"success":   {OpBold, FgGreen},
	"comment":   {OpReset, FgYellow},
	"primary":   {OpReset, FgBlue},
	"warning":   {OpBold, FgYellow},
	"question":  {OpReset, FgMagenta},
	"secondary": {FgDarkGray},
}

Some defined styles, like bootstrap styles

View Source
var Enable = true

switch color display

View Source
var FgColors = map[string]Color{
	"black":   FgBlack,
	"red":     FgRed,
	"green":   FgGreen,
	"yellow":  FgYellow,
	"blue":    FgBlue,
	"magenta": FgMagenta,
	"cyan":    FgCyan,
	"white":   FgWhite,
	"default": FgDefault,
}

Foreground colors map

View Source
var LogLevel2tag = map[string]string{
	"info":    "info",
	"warn":    "warning",
	"warning": "warning",
	"debug":   "cyan",
	"notice":  "notice",
	"error":   "error",
}

log level to cli color style

View Source
var Options = map[string]Color{
	"reset":      OpReset,
	"bold":       OpBold,
	"fuzzy":      OpFuzzy,
	"italic":     OpItalic,
	"underscore": OpUnderscore,
	"blink":      OpBlink,
	"reverse":    OpReverse,
	"concealed":  OpConcealed,
}

color options map

Functions

func AddStyle

func AddStyle(name string, s Style)

AddStyle add a style

func Apply

func Apply(str string, colors ...Color) string

Apply apply custom colors usage:

	// (string, fg-color,bg-color, options...)
 color.Apply("text", color.FgGreen)
 color.Apply("text", color.FgGreen, color.BgBlack, color.OpBold)

func ApplyTag

func ApplyTag(tag string, args ...interface{}) string

ApplyTag

func Black

func Black(args ...interface{})

Black add black for message

func Blue

func Blue(args ...interface{})

Blue add blue for message

func Bold

func Bold(args ...interface{})

Bold add bold for message

func Byte24Color

func Byte24Color(str string)

Byte24Color use RGB color

func Byte8Color

func Byte8Color(str string, val Bt8Color)

Byte8Color use 8 byte, 0 - 255 color

func ClearCode

func ClearCode(str string) string

ClearCode clear color codes eg "\033[36;1mText\x1b[0m" -> "Text"

func ClearTag

func ClearTag(str string) string

ClearTag clear all tag for a string

func Comment

func Comment(args ...interface{})

Comment add comment style for message

func Cyan

func Cyan(args ...interface{})

Cyan add cyan for message

func Danger

func Danger(args ...interface{})

Danger add danger style for message

func Disable

func Disable()

Disable disable color output

func Err

func Err(args ...interface{})

Err add err style for message

func Error

func Error(args ...interface{})

Error add error style for message

func Fprint

func Fprint(w io.Writer, args ...interface{}) (int, error)

Fprint

func Fprintf

func Fprintf(w io.Writer, format string, args ...interface{}) (int, error)

Fprintf

func Fprintln

func Fprintln(w io.Writer, args ...interface{}) (int, error)

Fprintln

func GetColorTags

func GetColorTags() map[string]string

GetColorTags

func GetStyleCode

func GetStyleCode(name string) string

GetStyleCode get color code by tag name

func GetStyleName

func GetStyleName(name string) string

GetStyleName

func Gray

func Gray(args ...interface{})

Gray add gray for message

func Green

func Green(args ...interface{})

Green add green for message

func Info

func Info(args ...interface{})

Info add info style for message

func IsBgColor

func IsBgColor(name string) bool

IsBgColor

func IsDefinedTag

func IsDefinedTag(name string) bool

IsDefinedTag is defined tag name

func IsDisabled

func IsDisabled() bool

IsDisabled

func IsFgColor

func IsFgColor(name string) bool

IsFgColor

func IsOption

func IsOption(name string) bool

IsOption

func Light

func Light(args ...interface{})

Light add light style for message

func Magenta

func Magenta(args ...interface{})

Magenta add magenta for message

func Note

func Note(args ...interface{})

Note add note style for message

func Notice

func Notice(args ...interface{})

Notice add notice style for message

func ParseCodeFromAttr

func ParseCodeFromAttr(attr string) (code string)

ParseCodeFromAttr parse color attributes attr like: "fg=VALUE;bg=VALUE;op=VALUE", VALUE please see var: FgColors, BgColors, Options eg: "fg=yellow" "bg=red" "op=bold,underscore" option is allow multi value "fg=white;bg=blue;op=bold" "fg=white;op=bold,underscore"

func Primary

func Primary(args ...interface{})

Primary add primary style for message

func Print

func Print(args ...interface{}) (int, error)

Print

func Printf

func Printf(format string, args ...interface{}) (int, error)

Printf

func Println

func Println(args ...interface{}) (int, error)

Println

func Question

func Question(args ...interface{})

Question add question style for message

func Red

func Red(args ...interface{})

Red add red for message

func Render

func Render(args ...interface{}) string

Render return rendered string

func RenderCodes

func RenderCodes(code string, str string) string

RenderCodes "3;32;45"

func RenderStr

func RenderStr(str string) string

RenderStr alias of the ReplaceTag

func ReplaceTag

func ReplaceTag(str string, dumpIt ...bool) string

ReplaceTag parse string, replace tag and return rendered string

func Reset

func Reset() (int, error)

Reset reset console color attributes

func Secondary

func Secondary(args ...interface{})

Secondary add secondary style for message

func Set

func Set(colors ...Color) (int, error)

Set set console color attributes

func Suc

func Suc(args ...interface{})

Suc add suc style for message

func Success

func Success(args ...interface{})

Success add success style for message

func TrueColor

func TrueColor(str string, rgb RgbColor)

Byte24Color use RGB color

func Warn

func Warn(args ...interface{})

Warn add warn style for message

func Warning

func Warning(args ...interface{})

Warning add warning style for message

func White

func White(args ...interface{})

White add white for message

func WrapTag

func WrapTag(str string, tag string) string

WrapTag wrap a tag for a string "<tag>content</>"

func Yellow

func Yellow(args ...interface{})

Yellow add yellow for message

Types

type Bt8Color

type Bt8Color uint8

uint8 at 0 - 255 10进制和16进制都可 0x98 = 152 use 8 byte, 0 - 255 color

type Bt8Style

type Bt8Style struct {
	Fg, Bg Bt8Color
}

func (*Bt8Style) Print

func (s *Bt8Style) Print(args ...interface{}) (n int, err error)

func (*Bt8Style) String

func (s *Bt8Style) String() string

type Color

type Color uint8

Color represents a text color.

const (
	// basic Foreground colors 30 - 37
	FgBlack Color = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta // 品红
	FgCyan    // 青色
	FgWhite

	// revert default FG
	FgDefault Color = 39

	// extra Foreground color 90 - 97(非标准)
	FgDarkGray Color = iota + 90 // 亮黑(灰)
	FgLightRed
	FgLightGreen
	FgLightYellow
	FgLightBlue
	FgLightMagenta
	FgLightCyan
	FgLightWhite
)

Foreground colors.

const (
	// basic Background colors 40 - 47
	BgBlack Color = iota + 40
	BgRed
	BgGreen
	BgYellow // BgBrown like yellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite

	// revert default BG
	BgDefault Color = 49

	// extra Background color 100 - 107(非标准)
	BgDarkGray Color = iota + 100
	BgLightRed
	BgLightGreen
	BgLightYellow
	BgLightBlue
	BgLightMagenta
	BgLightCyan
	BgLightWhite
)

Background colors.

const (
	OpReset         Color = iota // 0 重置所有设置
	OpBold                       // 1 加粗
	OpFuzzy                      // 2 模糊(不是所有的终端仿真器都支持)
	OpItalic                     // 3 斜体(不是所有的终端仿真器都支持)
	OpUnderscore                 // 4 下划线
	OpBlink                      // 5 闪烁
	OpFastBlink                  // 5 快速闪烁(未广泛支持)
	OpReverse                    // 7 颠倒的 交换背景色与前景色
	OpConcealed                  // 8 隐匿的
	OpStrikethrough              // 9 删除的,删除线(未广泛支持)
)

Option settings

func (Color) IsValid

func (c Color) IsValid() bool

IsValid 检测是否为一个有效的 Color 值

func (Color) Print

func (c Color) Print(args ...interface{}) (int, error)

Print

func (Color) Printf

func (c Color) Printf(format string, args ...interface{}) (int, error)

Printf usage:

color.FgCyan.Printf("string %s", "arg0")

func (Color) Println

func (c Color) Println(args ...interface{}) (int, error)

Println

func (Color) Render

func (c Color) Render(args ...interface{}) string

Render

func (Color) Renderf

func (c Color) Renderf(format string, args ...interface{}) string

Renderf

func (Color) String

func (c Color) String() string

String to string

type LiteTips

type LiteTips string

LiteTips will only add color for tag name value is a defined style name

func (LiteTips) Print

func (t LiteTips) Print(args ...interface{}) (int, error)

Print

func (LiteTips) Printf

func (t LiteTips) Printf(format string, args ...interface{}) (int, error)

Printf

func (LiteTips) Println

func (t LiteTips) Println(args ...interface{}) (int, error)

Println

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger console logger

func NewLog

func NewLog(fields map[string]string) *Logger

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

func (*Logger) Log

func (l *Logger) Log(args ...interface{})

type RgbColor

type RgbColor [3]uint8

type RgbStyle

type RgbStyle struct {
	Fg, Bg RgbColor
}

type Style

type Style []Color

Style a colored style can add: fg color, bg color, color options quick use:

color.Style(color.FgGreen).

func GetStyle

func GetStyle(name string) Style

GetStyle get style by name

func New

func New(colors ...Color) Style

New create a custom style

func (Style) Apply

func (s Style) Apply(args ...interface{}) string

Apply is alias of the 'Render'

func (Style) Print

func (s Style) Print(args ...interface{}) (int, error)

Print render and Print text

func (Style) Printf

func (s Style) Printf(format string, args ...interface{}) (int, error)

Printf render and Print text

func (Style) Println

func (s Style) Println(args ...interface{}) (int, error)

Println render and Print text

func (Style) Render

func (s Style) Render(args ...interface{}) string

Render render text usage:

color.New(color.FgGreen).Render("text")
color.New(color.FgGreen, color.BgBlack, color.OpBold).Render("text")

func (Style) Save

func (s Style) Save(name string)

Save save to styles map

type Tag

type Tag string

value is a defined style name

func (Tag) Print

func (tg Tag) Print(args ...interface{})

Print

func (Tag) Printf

func (tg Tag) Printf(format string, args ...interface{})

Printf

func (Tag) Println

func (tg Tag) Println(args ...interface{})

Println

type Tips

type Tips string

Tips will add color for all text value is a defined style name

func (Tips) Print

func (t Tips) Print(args ...interface{}) (int, error)

Print

func (Tips) Printf

func (t Tips) Printf(format string, args ...interface{}) (int, error)

Printf

func (Tips) Println

func (t Tips) Println(args ...interface{}) (int, error)

Println

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL