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.

color.go 1.9KB

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