You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

colors.go 8.6 kB

Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package log
  5. import (
  6. "fmt"
  7. "io"
  8. "strconv"
  9. "strings"
  10. )
  11. const escape = "\033"
  12. // ColorAttribute defines a single SGR Code
  13. type ColorAttribute int
  14. // Base ColorAttributes
  15. const (
  16. Reset ColorAttribute = iota
  17. Bold
  18. Faint
  19. Italic
  20. Underline
  21. BlinkSlow
  22. BlinkRapid
  23. ReverseVideo
  24. Concealed
  25. CrossedOut
  26. )
  27. // Foreground text colors
  28. const (
  29. FgBlack ColorAttribute = iota + 30
  30. FgRed
  31. FgGreen
  32. FgYellow
  33. FgBlue
  34. FgMagenta
  35. FgCyan
  36. FgWhite
  37. )
  38. // Foreground Hi-Intensity text colors
  39. const (
  40. FgHiBlack ColorAttribute = iota + 90
  41. FgHiRed
  42. FgHiGreen
  43. FgHiYellow
  44. FgHiBlue
  45. FgHiMagenta
  46. FgHiCyan
  47. FgHiWhite
  48. )
  49. // Background text colors
  50. const (
  51. BgBlack ColorAttribute = iota + 40
  52. BgRed
  53. BgGreen
  54. BgYellow
  55. BgBlue
  56. BgMagenta
  57. BgCyan
  58. BgWhite
  59. )
  60. // Background Hi-Intensity text colors
  61. const (
  62. BgHiBlack ColorAttribute = iota + 100
  63. BgHiRed
  64. BgHiGreen
  65. BgHiYellow
  66. BgHiBlue
  67. BgHiMagenta
  68. BgHiCyan
  69. BgHiWhite
  70. )
  71. var colorAttributeToString = map[ColorAttribute]string{
  72. Reset: "Reset",
  73. Bold: "Bold",
  74. Faint: "Faint",
  75. Italic: "Italic",
  76. Underline: "Underline",
  77. BlinkSlow: "BlinkSlow",
  78. BlinkRapid: "BlinkRapid",
  79. ReverseVideo: "ReverseVideo",
  80. Concealed: "Concealed",
  81. CrossedOut: "CrossedOut",
  82. FgBlack: "FgBlack",
  83. FgRed: "FgRed",
  84. FgGreen: "FgGreen",
  85. FgYellow: "FgYellow",
  86. FgBlue: "FgBlue",
  87. FgMagenta: "FgMagenta",
  88. FgCyan: "FgCyan",
  89. FgWhite: "FgWhite",
  90. FgHiBlack: "FgHiBlack",
  91. FgHiRed: "FgHiRed",
  92. FgHiGreen: "FgHiGreen",
  93. FgHiYellow: "FgHiYellow",
  94. FgHiBlue: "FgHiBlue",
  95. FgHiMagenta: "FgHiMagenta",
  96. FgHiCyan: "FgHiCyan",
  97. FgHiWhite: "FgHiWhite",
  98. BgBlack: "BgBlack",
  99. BgRed: "BgRed",
  100. BgGreen: "BgGreen",
  101. BgYellow: "BgYellow",
  102. BgBlue: "BgBlue",
  103. BgMagenta: "BgMagenta",
  104. BgCyan: "BgCyan",
  105. BgWhite: "BgWhite",
  106. BgHiBlack: "BgHiBlack",
  107. BgHiRed: "BgHiRed",
  108. BgHiGreen: "BgHiGreen",
  109. BgHiYellow: "BgHiYellow",
  110. BgHiBlue: "BgHiBlue",
  111. BgHiMagenta: "BgHiMagenta",
  112. BgHiCyan: "BgHiCyan",
  113. BgHiWhite: "BgHiWhite",
  114. }
  115. func (c *ColorAttribute) String() string {
  116. return colorAttributeToString[*c]
  117. }
  118. var colorAttributeFromString = map[string]ColorAttribute{}
  119. // ColorAttributeFromString will return a ColorAttribute given a string
  120. func ColorAttributeFromString(from string) ColorAttribute {
  121. lowerFrom := strings.TrimSpace(strings.ToLower(from))
  122. return colorAttributeFromString[lowerFrom]
  123. }
  124. // ColorString converts a list of ColorAttributes to a color string
  125. func ColorString(attrs ...ColorAttribute) string {
  126. return string(ColorBytes(attrs...))
  127. }
  128. // ColorBytes converts a list of ColorAttributes to a byte array
  129. func ColorBytes(attrs ...ColorAttribute) []byte {
  130. bytes := make([]byte, 0, 20)
  131. bytes = append(bytes, escape[0], '[')
  132. if len(attrs) > 0 {
  133. bytes = append(bytes, strconv.Itoa(int(attrs[0]))...)
  134. for _, a := range attrs[1:] {
  135. bytes = append(bytes, ';')
  136. bytes = append(bytes, strconv.Itoa(int(a))...)
  137. }
  138. } else {
  139. bytes = append(bytes, strconv.Itoa(int(Bold))...)
  140. }
  141. bytes = append(bytes, 'm')
  142. return bytes
  143. }
  144. var levelToColor = map[Level]string{
  145. TRACE: ColorString(Bold, FgCyan),
  146. DEBUG: ColorString(Bold, FgBlue),
  147. INFO: ColorString(Bold, FgGreen),
  148. WARN: ColorString(Bold, FgYellow),
  149. ERROR: ColorString(Bold, FgRed),
  150. CRITICAL: ColorString(Bold, BgMagenta),
  151. FATAL: ColorString(Bold, BgRed),
  152. NONE: ColorString(Reset),
  153. }
  154. var resetBytes = ColorBytes(Reset)
  155. var fgCyanBytes = ColorBytes(FgCyan)
  156. var fgGreenBytes = ColorBytes(FgGreen)
  157. var fgBoldBytes = ColorBytes(Bold)
  158. type protectedANSIWriterMode int
  159. const (
  160. escapeAll protectedANSIWriterMode = iota
  161. allowColor
  162. removeColor
  163. )
  164. type protectedANSIWriter struct {
  165. w io.Writer
  166. mode protectedANSIWriterMode
  167. }
  168. // Write will protect against unusual characters
  169. func (c *protectedANSIWriter) Write(bytes []byte) (int, error) {
  170. end := len(bytes)
  171. totalWritten := 0
  172. normalLoop:
  173. for i := 0; i < end; {
  174. lasti := i
  175. if c.mode == escapeAll {
  176. for i < end && (bytes[i] >= ' ' || bytes[i] == '\n') {
  177. i++
  178. }
  179. } else {
  180. for i < end && bytes[i] >= ' ' {
  181. i++
  182. }
  183. }
  184. if i > lasti {
  185. written, err := c.w.Write(bytes[lasti:i])
  186. totalWritten = totalWritten + written
  187. if err != nil {
  188. return totalWritten, err
  189. }
  190. }
  191. if i >= end {
  192. break
  193. }
  194. // If we're not just escaping all we should prefix all newlines with a \t
  195. if c.mode != escapeAll {
  196. if bytes[i] == '\n' {
  197. written, err := c.w.Write([]byte{'\n', '\t'})
  198. if written > 0 {
  199. totalWritten++
  200. }
  201. if err != nil {
  202. return totalWritten, err
  203. }
  204. i++
  205. continue normalLoop
  206. }
  207. if bytes[i] == escape[0] && i+1 < end && bytes[i+1] == '[' {
  208. for j := i + 2; j < end; j++ {
  209. if bytes[j] >= '0' && bytes[j] <= '9' {
  210. continue
  211. }
  212. if bytes[j] == ';' {
  213. continue
  214. }
  215. if bytes[j] == 'm' {
  216. if c.mode == allowColor {
  217. written, err := c.w.Write(bytes[i : j+1])
  218. totalWritten = totalWritten + written
  219. if err != nil {
  220. return totalWritten, err
  221. }
  222. } else {
  223. totalWritten = j
  224. }
  225. i = j + 1
  226. continue normalLoop
  227. }
  228. break
  229. }
  230. }
  231. }
  232. // Process naughty character
  233. if _, err := fmt.Fprintf(c.w, `\%#o03d`, bytes[i]); err != nil {
  234. return totalWritten, err
  235. }
  236. i++
  237. totalWritten++
  238. }
  239. return totalWritten, nil
  240. }
  241. // ColoredValue will Color the provided value
  242. type ColoredValue struct {
  243. colorBytes *[]byte
  244. resetBytes *[]byte
  245. Value *interface{}
  246. }
  247. // NewColoredValue is a helper function to create a ColoredValue from a Value
  248. // If no color is provided it defaults to Bold with standard Reset
  249. // If a ColoredValue is provided it is not changed
  250. func NewColoredValue(value interface{}, color ...ColorAttribute) *ColoredValue {
  251. return NewColoredValuePointer(&value, color...)
  252. }
  253. // NewColoredValuePointer is a helper function to create a ColoredValue from a Value Pointer
  254. // If no color is provided it defaults to Bold with standard Reset
  255. // If a ColoredValue is provided it is not changed
  256. func NewColoredValuePointer(value *interface{}, color ...ColorAttribute) *ColoredValue {
  257. if val, ok := (*value).(*ColoredValue); ok {
  258. return val
  259. }
  260. if len(color) > 0 {
  261. bytes := ColorBytes(color...)
  262. return &ColoredValue{
  263. colorBytes: &bytes,
  264. resetBytes: &resetBytes,
  265. Value: value,
  266. }
  267. }
  268. return &ColoredValue{
  269. colorBytes: &fgBoldBytes,
  270. resetBytes: &resetBytes,
  271. Value: value,
  272. }
  273. }
  274. // NewColoredValueBytes creates a value from the provided value with color bytes
  275. // If a ColoredValue is provided it is not changed
  276. func NewColoredValueBytes(value interface{}, colorBytes *[]byte) *ColoredValue {
  277. if val, ok := value.(*ColoredValue); ok {
  278. return val
  279. }
  280. return &ColoredValue{
  281. colorBytes: colorBytes,
  282. resetBytes: &resetBytes,
  283. Value: &value,
  284. }
  285. }
  286. // Format will format the provided value and protect against ANSI spoofing within the value
  287. func (cv *ColoredValue) Format(s fmt.State, c rune) {
  288. s.Write([]byte(*cv.colorBytes))
  289. fmt.Fprintf(&protectedANSIWriter{w: s}, fmtString(s, c), *(cv.Value))
  290. s.Write([]byte(*cv.resetBytes))
  291. }
  292. // SetColorBytes will allow a user to set the colorBytes of a colored value
  293. func (cv *ColoredValue) SetColorBytes(colorBytes []byte) {
  294. cv.colorBytes = &colorBytes
  295. }
  296. // SetColorBytesPointer will allow a user to set the colorBytes pointer of a colored value
  297. func (cv *ColoredValue) SetColorBytesPointer(colorBytes *[]byte) {
  298. cv.colorBytes = colorBytes
  299. }
  300. // SetResetBytes will allow a user to set the resetBytes pointer of a colored value
  301. func (cv *ColoredValue) SetResetBytes(resetBytes []byte) {
  302. cv.resetBytes = &resetBytes
  303. }
  304. // SetResetBytesPointer will allow a user to set the resetBytes pointer of a colored value
  305. func (cv *ColoredValue) SetResetBytesPointer(resetBytes *[]byte) {
  306. cv.resetBytes = resetBytes
  307. }
  308. func fmtString(s fmt.State, c rune) string {
  309. var width, precision string
  310. base := make([]byte, 0, 8)
  311. base = append(base, '%')
  312. for _, c := range []byte(" +-#0") {
  313. if s.Flag(int(c)) {
  314. base = append(base, c)
  315. }
  316. }
  317. if w, ok := s.Width(); ok {
  318. width = strconv.Itoa(w)
  319. }
  320. if p, ok := s.Precision(); ok {
  321. precision = "." + strconv.Itoa(p)
  322. }
  323. return fmt.Sprintf("%s%s%s%c", base, width, precision, c)
  324. }
  325. func init() {
  326. for attr, from := range colorAttributeToString {
  327. colorAttributeFromString[strings.ToLower(from)] = attr
  328. }
  329. }