code.gitea.io/gitea@v1.22.3/modules/log/color.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package log 5 6 import ( 7 "fmt" 8 "strconv" 9 ) 10 11 const escape = "\033" 12 13 // ColorAttribute defines a single SGR Code 14 type ColorAttribute int 15 16 // Base ColorAttributes 17 const ( 18 Reset ColorAttribute = iota 19 Bold 20 Faint 21 Italic 22 Underline 23 BlinkSlow 24 BlinkRapid 25 ReverseVideo 26 Concealed 27 CrossedOut 28 ) 29 30 // Foreground text colors 31 const ( 32 FgBlack ColorAttribute = iota + 30 33 FgRed 34 FgGreen 35 FgYellow 36 FgBlue 37 FgMagenta 38 FgCyan 39 FgWhite 40 ) 41 42 // Foreground Hi-Intensity text colors 43 const ( 44 FgHiBlack ColorAttribute = iota + 90 45 FgHiRed 46 FgHiGreen 47 FgHiYellow 48 FgHiBlue 49 FgHiMagenta 50 FgHiCyan 51 FgHiWhite 52 ) 53 54 // Background text colors 55 const ( 56 BgBlack ColorAttribute = iota + 40 57 BgRed 58 BgGreen 59 BgYellow 60 BgBlue 61 BgMagenta 62 BgCyan 63 BgWhite 64 ) 65 66 // Background Hi-Intensity text colors 67 const ( 68 BgHiBlack ColorAttribute = iota + 100 69 BgHiRed 70 BgHiGreen 71 BgHiYellow 72 BgHiBlue 73 BgHiMagenta 74 BgHiCyan 75 BgHiWhite 76 ) 77 78 var ( 79 resetBytes = ColorBytes(Reset) 80 fgCyanBytes = ColorBytes(FgCyan) 81 fgGreenBytes = ColorBytes(FgGreen) 82 ) 83 84 type ColoredValue struct { 85 v any 86 colors []ColorAttribute 87 } 88 89 func (c *ColoredValue) Format(f fmt.State, verb rune) { 90 _, _ = f.Write(ColorBytes(c.colors...)) 91 s := fmt.Sprintf(fmt.FormatString(f, verb), c.v) 92 _, _ = f.Write([]byte(s)) 93 _, _ = f.Write(resetBytes) 94 } 95 96 func NewColoredValue(v any, color ...ColorAttribute) *ColoredValue { 97 return &ColoredValue{v: v, colors: color} 98 } 99 100 // ColorBytes converts a list of ColorAttributes to a byte array 101 func ColorBytes(attrs ...ColorAttribute) []byte { 102 bytes := make([]byte, 0, 20) 103 bytes = append(bytes, escape[0], '[') 104 if len(attrs) > 0 { 105 bytes = append(bytes, strconv.Itoa(int(attrs[0]))...) 106 for _, a := range attrs[1:] { 107 bytes = append(bytes, ';') 108 bytes = append(bytes, strconv.Itoa(int(a))...) 109 } 110 } else { 111 bytes = append(bytes, strconv.Itoa(int(Bold))...) 112 } 113 bytes = append(bytes, 'm') 114 return bytes 115 }