color.go 1.1 KB

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