Skip to content

Commit

Permalink
add some new method and tool struct
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Feb 27, 2021
1 parent c228fec commit bb87a35
Show file tree
Hide file tree
Showing 7 changed files with 189 additions and 26 deletions.
7 changes: 5 additions & 2 deletions _examples/envcheck.go
Expand Up @@ -8,11 +8,14 @@ import (
// "github.com/gookit/goutil/dump"
)

// go run ./_examples/envcheck.go
func main() {
fmt.Println("OS", runtime.GOOS)

fmt.Println("IsSupport256Color", color.IsSupport256Color())
fmt.Println("IsSupportColor", color.IsSupportColor())
fmt.Println("IsSupportColor:", color.IsSupportColor())
fmt.Println("IsSupport256Color:", color.IsSupport256Color())
fmt.Println("IsSupportRGBColor:", color.IsSupportRGBColor())
fmt.Printf("SupColorMark: %#v\n", color.SupColorMark())

// dump.P(os.Environ())
}
10 changes: 10 additions & 0 deletions color.go
Expand Up @@ -25,6 +25,14 @@ import (
// ModeGrayscale
// )

// TODO console color available level
const (
LevelNo uint8 = iota // not support color.
Level16
Level256
LevelRgb
)

// color render templates
// ESC 操作的表示:
// "\033"(Octal 8进制) = "\x1b"(Hexadecimal 16进制) = 27 (10进制)
Expand All @@ -42,6 +50,8 @@ const CodeExpr = `\033\[[\d;?]+m`
var (
// Enable switch color render and display
Enable = true
// Level color support level for current terminal
Level = Level16
// RenderTag render HTML tag on call color.Xprint, color.PrintX
RenderTag = true
// errors on windows render OR print to io.Writer
Expand Down
111 changes: 111 additions & 0 deletions style.go
Expand Up @@ -283,3 +283,114 @@ func Warnf(format string, a ...interface{}) {
func Warnln(a ...interface{}) {
Warn.Println(a...)
}

/*************************************************************
* SimplePrinter struct
*************************************************************/

// SimplePrinter use for quick use color print on inject to struct
type SimplePrinter struct{}

// Print message
func (s *SimplePrinter) Print(v ...interface{}) {
Print(v...)
}

// Printf message
func (s *SimplePrinter) Printf(format string, v ...interface{}) {
Printf(format, v...)
}

// Println message
func (s *SimplePrinter) Println(v ...interface{}) {
Println(v...)
}

// Infof message
func (s *SimplePrinter) Infof(format string, a ...interface{}) {
Info.Printf(format, a...)
}

// Infoln message
func (s *SimplePrinter) Infoln(a ...interface{}) {
Info.Println(a...)
}

// Warnf message
func (s *SimplePrinter) Warnf(format string, a ...interface{}) {
Warn.Printf(format, a...)
}

// Warnln message
func (s *SimplePrinter) Warnln(a ...interface{}) {
Warn.Println(a...)
}

// Errorf message
func (s *SimplePrinter) Errorf(format string, a ...interface{}) {
Error.Printf(format, a...)
}

// Errorln message
func (s *SimplePrinter) Errorln(a ...interface{}) {
Error.Println(a...)
}

/*************************************************************
* color scheme
*************************************************************/

// Scheme struct
type Scheme struct {
Name string
Styles map[string]Style
}

// NewScheme create new Scheme
func NewScheme(name string, styles map[string]Style) *Scheme {
return &Scheme{Name: name, Styles: styles}
}

// NewDefaultScheme create an defuault color Scheme
func NewDefaultScheme(name string) *Scheme {
return NewScheme(name, map[string]Style{
"info": {OpReset, FgGreen},
"warn": {OpBold, FgYellow},
"error": {FgLightWhite, BgRed},
})
}

// Style get by name
func (s *Scheme) Style(name string) Style {
return s.Styles[name]
}

// Infof message print
func (s *Scheme) Infof(format string, a ...interface{}) {
s.Styles["info"].Printf(format, a...)
}

// Infoln message print
func (s *Scheme) Infoln(v ...interface{}) {
s.Styles["info"].Println(v...)
}

// Warnf message print
func (s *Scheme) Warnf(format string, a ...interface{}) {
s.Styles["warn"].Printf(format, a...)
}

// Warnln message print
func (s *Scheme) Warnln(v ...interface{}) {
s.Styles["warn"].Println(v...)
}

// Errorf message print
func (s *Scheme) Errorf(format string, a ...interface{}) {
s.Styles["error"].Printf(format, a...)
}

// Errorln message print
func (s *Scheme) Errorln(v ...interface{}) {
s.Styles["error"].Println(v...)
}
25 changes: 25 additions & 0 deletions style_test.go
Expand Up @@ -165,3 +165,28 @@ func TestStyleFunc(t *testing.T) {
assert.Equal(t, "\x1b[97;41mcolor message\x1b[0m", buf.String())
buf.Reset()
}

func TestSimplePrinter_Print(t *testing.T) {
sp := &SimplePrinter{}
sp.Printf("simple %s", "printer")
sp.Infof("simple %s", "printer")
sp.Warnf("simple %s", "printer")
sp.Errorf("simple %s", "printer")
sp.Print("simple printer\n")
sp.Println("simple printer")
sp.Infoln("simple printer")
sp.Warnln("simple printer")
sp.Errorln("simple printer")
}

func TestNewScheme(t *testing.T) {
cs := NewDefaultScheme("test")

cs.Infof("color %s\n", "scheme")
cs.Warnf("color %s\n", "scheme")
cs.Errorf("color %s\n", "scheme")
cs.Infoln("color scheme")
cs.Warnln("color scheme")
cs.Errorln("color scheme")
cs.Style("info").Println("color scheme")
}
8 changes: 7 additions & 1 deletion tag.go
Expand Up @@ -41,18 +41,24 @@ var (
var colorTags = map[string]string{
// basic tags,
"red": "0;31",
"red1": "1;31", // with bold
"blue": "0;34",
"blue1": "1;34", // with bold
"cyan": "0;36",
"cyan1": "1;36", // with bold
"black": "0;30",
"green": "0;32",
"green1": "1;32", // with bold
"white": "1;37",
"default": "0;39", // no color
"normal": "0;39", // no color
"ylw0": "0;33",
"ylw1": "1;33", // with bold
"brown": "0;33",
"yellow": "1;33",
"mga": "0;35", // short name
"magenta": "0;35",
"mgb": "1;35", // short name
"mgb": "1;35", // short name, with bold
"magentaB": "1;35", // add bold

// alert tags, like bootstrap's alert
Expand Down
49 changes: 28 additions & 21 deletions utils.go
Expand Up @@ -10,6 +10,9 @@ import (
"syscall"
)

// mark/flag
var supColorMark string

// Support color:
// "TERM=xterm"
// "TERM=xterm-vt220"
Expand All @@ -23,6 +26,11 @@ var specialColorTerms = map[string]bool{
"alacritty": true,
}

// SupColorMark get
func SupColorMark() string {
return supColorMark
}

/*************************************************************
* helper methods for check env
*************************************************************/
Expand Down Expand Up @@ -59,21 +67,25 @@ func IsMSys() bool {
func IsSupportColor() bool {
envTerm := os.Getenv("TERM")
if strings.Contains(envTerm, "term") {
supColorMark = "TERM=" + envTerm
return true
}

// it's special color term
if _, ok := specialColorTerms[envTerm]; ok {
supColorMark = "TERM=" + envTerm
return true
}

// like on ConEmu software, e.g "ConEmuANSI=ON"
if os.Getenv("ConEmuANSI") == "ON" {
supColorMark = "ConEmuANSI=ON"
return true
}

// like on ConEmu software, e.g "ANSICON=189x2000 (189x43)"
if os.Getenv("ANSICON") != "" {
if val := os.Getenv("ANSICON"); val != "" {
supColorMark = "ANSICON=" + val
return true
}

Expand All @@ -94,18 +106,29 @@ func isSupport256Color(termVal string) bool {
supported := strings.Contains(termVal, "256color")
if !supported {
// up: if support true-color, can also support 256-color.
supported = IsSupportTrueColor()
return IsSupportTrueColor()
}

supColorMark = "TERM=" + termVal
return supported
}

// IsSupportTrueColor render. IsSupportRGBColor
// IsSupportRGBColor render. alias of the IsSupportTrueColor()
func IsSupportRGBColor() bool {
return IsSupportTrueColor()
}

// IsSupportTrueColor render.
func IsSupportTrueColor() bool {
val := os.Getenv("COLORTERM")
v := os.Getenv("COLORTERM")
// "COLORTERM=truecolor"
// "COLORTERM=24bit"
return strings.Contains(val, "truecolor") || strings.Contains(val, "24bit")
ok := strings.Contains(v, "truecolor") || strings.Contains(v, "24bit")

if ok {
supColorMark = "COLORTERM=" + v
}
return ok
}

/*************************************************************
Expand Down Expand Up @@ -276,14 +299,6 @@ func Fprintf(w io.Writer, format string, a ...interface{}) {
str := fmt.Sprintf(format, a...)
_, err := fmt.Fprint(w, ReplaceTag(str))
saveInternalError(err)

// if isLikeInCmd {
// renderColorCodeOnCmd(func() {
// _, _ = fmt.Fprint(w, ReplaceTag(str))
// })
// } else {
// _, _ = fmt.Fprint(w, ReplaceTag(str))
// }
}

// Fprintln print rendered messages line to writer
Expand Down Expand Up @@ -359,14 +374,6 @@ func doPrintlnV2(code string, args []interface{}) {
str := formatArgsForPrintln(args)
_, err := fmt.Fprintln(output, RenderString(code, str))
saveInternalError(err)

// if isLikeInCmd {
// renderColorCodeOnCmd(func() {
// _, _ = fmt.Fprintln(output, RenderString(code, str))
// })
// } else {
// _, _ = fmt.Fprintln(output, RenderString(code, str))
// }
}

// if use Println, will add spaces for each arg
Expand Down
5 changes: 3 additions & 2 deletions utils_test.go
Expand Up @@ -47,6 +47,7 @@ func TestUtilFuncs(t *testing.T) {

// "COLORTERM=truecolor"
mockEnvValue("COLORTERM", "truecolor", func(_ string) {
is.True(IsSupportRGBColor())
is.True(IsSupportTrueColor())
})

Expand Down Expand Up @@ -91,7 +92,7 @@ func TestRgbTo256Table(t *testing.T) {
}

func TestC256ToRgbV1(t *testing.T) {
for i :=0; i < 256; i++ {
for i := 0; i < 256; i++ {
c256 := uint8(i)
C256(c256).Printf("C256:%d", c256)
fmt.Print(" => ")
Expand All @@ -106,7 +107,7 @@ func TestC256ToRgbV1(t *testing.T) {
}

func TestC256ToRgb(t *testing.T) {
for i :=0; i < 256; i++ {
for i := 0; i < 256; i++ {
c256 := uint8(i)
C256(c256).Printf("C256:%d", c256)
fmt.Print(" => ")
Expand Down

0 comments on commit bb87a35

Please sign in to comment.