color.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package text
  2. import "fmt"
  3. const (
  4. redCode = "\x1b[31m"
  5. greenCode = "\x1b[32m"
  6. yellowCode = "\x1b[33m"
  7. magentaCode = "\x1b[35m"
  8. CyanCode = "\x1b[36m"
  9. boldCode = "\x1b[1m"
  10. ResetCode = "\x1b[0m"
  11. )
  12. // UseColor determines if package will emit colors
  13. var UseColor = true
  14. func stylize(startCode, in string) string {
  15. if UseColor {
  16. return startCode + in + ResetCode
  17. }
  18. return in
  19. }
  20. func red(in string) string {
  21. return stylize(redCode, in)
  22. }
  23. func green(in string) string {
  24. return stylize(greenCode, in)
  25. }
  26. func yellow(in string) string {
  27. return stylize(yellowCode, in)
  28. }
  29. func cyan(in string) string {
  30. return stylize(CyanCode, in)
  31. }
  32. func Magenta(in string) string {
  33. return stylize(magentaCode, in)
  34. }
  35. func Bold(in string) string {
  36. return stylize(boldCode, in)
  37. }
  38. // ColorHash Colors text using a hashing algorithm. The same text will always produce the
  39. // same color while different text will produce a different color.
  40. func ColorHash(name string) (output string) {
  41. if !UseColor {
  42. return name
  43. }
  44. var hash uint = 5381
  45. for i := 0; i < len(name); i++ {
  46. hash = uint(name[i]) + ((hash << 5) + (hash))
  47. }
  48. return fmt.Sprintf("\x1b[%dm%s\x1b[0m", hash%6+31, name)
  49. }