github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/dump/dump.go (about) 1 // Package dump like fmt.Println but more pretty and beautiful print Go values. 2 package dump 3 4 import ( 5 "bytes" 6 "io" 7 "os" 8 9 "github.com/gookit/color" 10 ) 11 12 // These flags define which print caller information 13 const ( 14 Fnopos = 1 << iota // no position 15 Ffunc 16 Ffile 17 Ffname 18 Fline 19 ) 20 21 var ( 22 // valid flag for print caller info 23 callerFlags = []int{Ffunc, Ffile, Ffname, Fline} 24 // default theme 25 defaultTheme = Theme{ 26 "caller": "magenta", 27 "field": "green", // field name color of the map, struct. 28 "value": "normal", 29 // special type 30 "msType": "green", // for keywords map, struct type 31 "lenTip": "gray", // tips comments for string, slice, map len 32 "string": "green", 33 "integer": "lightBlue", 34 } 35 36 // std dumper 37 std = NewDumper(os.Stdout, 3) 38 ) 39 40 // Theme color code/tag map for dump 41 type Theme map[string]string 42 43 func (ct Theme) caller(s string) string { return ct.wrap("caller", s) } 44 func (ct Theme) field(s string) string { return ct.wrap("field", s) } 45 func (ct Theme) value(s string) string { return ct.wrap("value", s) } 46 func (ct Theme) msType(s string) string { return ct.wrap("msType", s) } 47 func (ct Theme) lenTip(s string) string { return ct.wrap("lenTip", s) } 48 func (ct Theme) string(s string) string { return ct.wrap("string", s) } 49 func (ct Theme) integer(s string) string { return ct.wrap("integer", s) } 50 51 // wrap color tag. 52 func (ct Theme) wrap(key string, s string) string { 53 if tag := ct[key]; tag != "" { 54 return color.WrapTag(s, tag) 55 } 56 return s 57 } 58 59 // Std dumper 60 func Std() *Dumper { 61 return std 62 } 63 64 // Reset std dumper 65 func Reset() { 66 std = NewDumper(os.Stdout, 3) 67 } 68 69 // Config std dumper 70 func Config(fn func(opts *Options)) { 71 std.WithOptions(fn) 72 } 73 74 // V like fmt.Println, but the output is clearer and more beautiful 75 func V(vs ...interface{}) { 76 std.Dump(vs...) 77 } 78 79 // P like fmt.Println, but the output is clearer and more beautiful 80 func P(vs ...interface{}) { 81 std.Print(vs...) 82 } 83 84 // Print like fmt.Println, but the output is clearer and more beautiful 85 func Print(vs ...interface{}) { 86 std.Print(vs...) 87 } 88 89 // Println like fmt.Println, but the output is clearer and more beautiful 90 func Println(vs ...interface{}) { 91 std.Println(vs...) 92 } 93 94 // Fprint like fmt.Println, but the output is clearer and more beautiful 95 func Fprint(w io.Writer, vs ...interface{}) { 96 std.Fprint(w, vs...) 97 } 98 99 // Format like fmt.Println, but the output is clearer and more beautiful 100 func Format(vs ...interface{}) string { 101 w := &bytes.Buffer{} 102 103 NewDumper(w, 3). 104 WithOptions(func(opts *Options) { 105 opts.ShowFlag = Fnopos 106 }). 107 Println(vs...) 108 return w.String() 109 }