go项目脚手架
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sorbet/pkg/log/colorer.go

71 lines
2.0 KiB

package log
import (
"github.com/mattn/go-isatty"
"os"
)
type Colorer interface {
Black(s string) string
Red(s string) string
Green(s string) string
Yellow(s string) string
Blue(s string) string
Magenta(s string) string
Cyan(s string) string
White(s string) string
Grey(s string) string
}
func NewColorer() Colorer {
return &colorer{}
}
type clr string
const (
black clr = "\x1b[30m"
red clr = "\x1b[31m"
green clr = "\x1b[32m"
yellow clr = "\x1b[33m"
blue clr = "\x1b[34m"
magenta clr = "\x1b[35m"
cyan clr = "\x1b[36m"
white clr = "\x1b[37m"
grey clr = "\x1b[90m"
)
var (
// NoColor defines if the output is colorized or not. It's dynamically set to
// false or true based on the stdout's file descriptor referring to a terminal
// or not. It's also set to true if the NO_COLOR environment variable is
// set (regardless of its value). This is a global option and affects all
// colors. For more control over each Color block use the methods
// DisableColor() individually.
noColor = noColorIsSet() || os.Getenv("TERM") == "dumb" ||
(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
)
// noColorIsSet returns true if the environment variable NO_COLOR is set to a non-empty string.
func noColorIsSet() bool {
return os.Getenv("NO_COLOR") != ""
}
func (c clr) f(s string) string {
if noColorIsSet() || noColor {
return s
}
return string(c) + s + "\x1b[0m"
}
type colorer struct{}
func (c *colorer) Black(s string) string { return black.f(s) }
func (c *colorer) Red(s string) string { return red.f(s) }
func (c *colorer) Green(s string) string { return green.f(s) }
func (c *colorer) Yellow(s string) string { return yellow.f(s) }
func (c *colorer) Blue(s string) string { return blue.f(s) }
func (c *colorer) Magenta(s string) string { return magenta.f(s) }
func (c *colorer) Cyan(s string) string { return cyan.f(s) }
func (c *colorer) White(s string) string { return white.f(s) }
func (c *colorer) Grey(s string) string { return grey.f(s) }