github.com/neilotoole/jsoncolor@v0.6.0/helper/fatihcolor/fatihcolor.go (about) 1 // Package fatihcolor provides an adapter between fatih/color 2 // and neilotoole/jsoncolor's native mechanism. See ToCoreColors. 3 package fatihcolor 4 5 import ( 6 "bytes" 7 8 "github.com/fatih/color" 9 "github.com/neilotoole/jsoncolor" 10 ) 11 12 // Colors encapsulates JSON color output, using fatih/color elements. 13 // It can be converted to a jsoncolor.Colors using ToCoreColors. 14 type Colors struct { 15 // Bool is the color for boolean values. 16 Bool *color.Color 17 18 // Bytes is the color for byte / binary values. 19 Bytes *color.Color 20 21 // Datetime is the color for time-related values. 22 Datetime *color.Color 23 24 // Null is the color for null. 25 Null *color.Color 26 27 // Number is the color for number values, including int, 28 // float, decimal etc. 29 Number *color.Color 30 31 // String is the color for string values. 32 String *color.Color 33 34 // Key is the color for keys such as a JSON field name. 35 Key *color.Color 36 37 // Punc is the color for punctuation such as colons, braces, etc. 38 // Frequently Punc will just be color.Bold. 39 Punc *color.Color 40 } 41 42 // DefaultColors returns default Colors instance. 43 func DefaultColors() *Colors { 44 return &Colors{ 45 Bool: color.New(color.FgYellow), 46 Bytes: color.New(color.Faint), 47 Datetime: color.New(color.FgGreen, color.Faint), 48 Key: color.New(color.FgBlue, color.Bold), 49 Null: color.New(color.Faint), 50 Number: color.New(color.FgCyan), 51 String: color.New(color.FgGreen), 52 Punc: color.New(color.Bold), 53 } 54 } 55 56 // ToCoreColors converts clrs to a core jsoncolor.Colors instance. 57 func ToCoreColors(clrs *Colors) *jsoncolor.Colors { 58 if clrs == nil { 59 return nil 60 } 61 62 return &jsoncolor.Colors{ 63 Null: ToCoreColor(clrs.Null), 64 Bool: ToCoreColor(clrs.Bool), 65 Number: ToCoreColor(clrs.Number), 66 String: ToCoreColor(clrs.String), 67 Key: ToCoreColor(clrs.Key), 68 Bytes: ToCoreColor(clrs.Bytes), 69 Time: ToCoreColor(clrs.Datetime), 70 Punc: ToCoreColor(clrs.Punc), 71 } 72 } 73 74 // ToCoreColor creates a jsoncolor.Color instance from a fatih/color 75 // instance. 76 func ToCoreColor(c *color.Color) jsoncolor.Color { 77 if c == nil { 78 return jsoncolor.Color{} 79 } 80 81 // Dirty conversion function ahead: print 82 // a space using c, then grab the bytes printed 83 // before the space, as those are the bytes we need. 84 // There's definitely a better way of doing this, but 85 // it works for now. 86 87 // Make a copy because the pkg-level color.NoColor could be false. 88 c2 := *c 89 c2.EnableColor() 90 91 b := []byte(c2.Sprint(" ")) 92 i := bytes.IndexByte(b, ' ') 93 if i <= 0 { 94 return jsoncolor.Color{} 95 } 96 97 return b[:i] 98 }