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