gitea源码

color.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. var _ fmt.Formatter = (*ColoredValue)(nil)
  78. func (c *ColoredValue) Format(f fmt.State, verb rune) {
  79. _, _ = f.Write(ColorBytes(c.colors...))
  80. s := fmt.Sprintf(fmt.FormatString(f, verb), c.v)
  81. _, _ = f.Write([]byte(s))
  82. _, _ = f.Write(resetBytes)
  83. }
  84. func (c *ColoredValue) Value() any {
  85. return c.v
  86. }
  87. func NewColoredValue(v any, color ...ColorAttribute) *ColoredValue {
  88. return &ColoredValue{v: v, colors: color}
  89. }
  90. // ColorBytes converts a list of ColorAttributes to a byte array
  91. func ColorBytes(attrs ...ColorAttribute) []byte {
  92. bytes := make([]byte, 0, 20)
  93. bytes = append(bytes, escape[0], '[')
  94. if len(attrs) > 0 {
  95. bytes = append(bytes, strconv.Itoa(int(attrs[0]))...)
  96. for _, a := range attrs[1:] {
  97. bytes = append(bytes, ';')
  98. bytes = append(bytes, strconv.Itoa(int(a))...)
  99. }
  100. } else {
  101. bytes = append(bytes, strconv.Itoa(int(Bold))...)
  102. }
  103. bytes = append(bytes, 'm')
  104. return bytes
  105. }