color.go 1.3 KB

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