template.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package pb
  2. import (
  3. "math/rand"
  4. "sync"
  5. "text/template"
  6. "github.com/fatih/color"
  7. )
  8. // ProgressBarTemplate that template string
  9. type ProgressBarTemplate string
  10. // New creates new bar from template
  11. func (pbt ProgressBarTemplate) New(total int) *ProgressBar {
  12. return New(total).SetTemplate(pbt)
  13. }
  14. // Start64 create and start new bar with given int64 total value
  15. func (pbt ProgressBarTemplate) Start64(total int64) *ProgressBar {
  16. return New64(total).SetTemplate(pbt).Start()
  17. }
  18. // Start create and start new bar with given int total value
  19. func (pbt ProgressBarTemplate) Start(total int) *ProgressBar {
  20. return pbt.Start64(int64(total))
  21. }
  22. var templateCacheMu sync.Mutex
  23. var templateCache = make(map[string]*template.Template)
  24. var defaultTemplateFuncs = template.FuncMap{
  25. // colors
  26. "black": color.New(color.FgBlack).SprintFunc(),
  27. "red": color.New(color.FgRed).SprintFunc(),
  28. "green": color.New(color.FgGreen).SprintFunc(),
  29. "yellow": color.New(color.FgYellow).SprintFunc(),
  30. "blue": color.New(color.FgBlue).SprintFunc(),
  31. "magenta": color.New(color.FgMagenta).SprintFunc(),
  32. "cyan": color.New(color.FgCyan).SprintFunc(),
  33. "white": color.New(color.FgWhite).SprintFunc(),
  34. "resetcolor": color.New(color.Reset).SprintFunc(),
  35. "rndcolor": rndcolor,
  36. "rnd": rnd,
  37. }
  38. func getTemplate(tmpl string) (t *template.Template, err error) {
  39. templateCacheMu.Lock()
  40. defer templateCacheMu.Unlock()
  41. t = templateCache[tmpl]
  42. if t != nil {
  43. // found in cache
  44. return
  45. }
  46. t = template.New("")
  47. fillTemplateFuncs(t)
  48. _, err = t.Parse(tmpl)
  49. if err != nil {
  50. t = nil
  51. return
  52. }
  53. templateCache[tmpl] = t
  54. return
  55. }
  56. func fillTemplateFuncs(t *template.Template) {
  57. t.Funcs(defaultTemplateFuncs)
  58. emf := make(template.FuncMap)
  59. elementsM.Lock()
  60. for k, v := range elements {
  61. element := v
  62. emf[k] = func(state *State, args ...string) string { return element.ProgressElement(state, args...) }
  63. }
  64. elementsM.Unlock()
  65. t.Funcs(emf)
  66. return
  67. }
  68. func rndcolor(s string) string {
  69. c := rand.Intn(int(color.FgWhite-color.FgBlack)) + int(color.FgBlack)
  70. return color.New(color.Attribute(c)).Sprint(s)
  71. }
  72. func rnd(args ...string) string {
  73. if len(args) == 0 {
  74. return ""
  75. }
  76. return args[rand.Intn(len(args))]
  77. }