use BarFillerMiddleware
Vladimir Bauer
6 years ago
| 17 | 17 | total := 100 |
| 18 | 18 | msgCh := make(chan string) |
| 19 | 19 | resumeCh := make(chan struct{}) |
| 20 | filler, nextCh := newCustomFiller(msgCh, resumeCh) | |
| 21 | bar := p.Add(int64(total), filler, | |
| 20 | nextCh := make(chan struct{}, 1) | |
| 21 | bar := p.AddBar(int64(total), | |
| 22 | mpb.BarFillerMiddleware(func(base mpb.BarFiller) mpb.BarFiller { | |
| 23 | var msg *string | |
| 24 | return mpb.BarFillerFunc(func(w io.Writer, reqWidth int, st decor.Statistics) { | |
| 25 | select { | |
| 26 | case m := <-msgCh: | |
| 27 | defer func() { | |
| 28 | msg = &m | |
| 29 | }() | |
| 30 | nextCh <- struct{}{} | |
| 31 | case <-resumeCh: | |
| 32 | msg = nil | |
| 33 | default: | |
| 34 | } | |
| 35 | if msg != nil { | |
| 36 | limitFmt := fmt.Sprintf("%%.%ds", st.AvailableWidth) | |
| 37 | fmt.Fprintf(w, limitFmt, *msg) | |
| 38 | nextCh <- struct{}{} | |
| 39 | } else { | |
| 40 | base.Fill(w, reqWidth, st) | |
| 41 | } | |
| 42 | }) | |
| 43 | }), | |
| 22 | 44 | mpb.PrependDecorators( |
| 23 | 45 | decor.Name("my bar:"), |
| 24 | 46 | ), |
| 75 | 97 | ew.Unlock() |
| 76 | 98 | } |
| 77 | 99 | |
| 78 | type myBarFiller struct { | |
| 79 | mpb.BarFiller | |
| 80 | base mpb.BarFiller | |
| 81 | } | |
| 82 | ||
| 83 | func (cf *myBarFiller) Base() mpb.BarFiller { | |
| 84 | return cf.base | |
| 85 | } | |
| 86 | ||
| 87 | func newCustomFiller(ch <-chan string, resume <-chan struct{}) (mpb.BarFiller, <-chan struct{}) { | |
| 88 | base := mpb.NewBarFiller(mpb.DefaultBarStyle, false) | |
| 89 | nextCh := make(chan struct{}, 1) | |
| 90 | var msg *string | |
| 91 | filler := mpb.BarFillerFunc(func(w io.Writer, width int, st decor.Statistics) { | |
| 92 | select { | |
| 93 | case m := <-ch: | |
| 94 | defer func() { | |
| 95 | msg = &m | |
| 96 | }() | |
| 97 | nextCh <- struct{}{} | |
| 98 | case <-resume: | |
| 99 | msg = nil | |
| 100 | default: | |
| 101 | } | |
| 102 | if msg != nil { | |
| 103 | limitFmt := fmt.Sprintf("%%.%ds", st.AvailableWidth) | |
| 104 | fmt.Fprintf(w, limitFmt, *msg) | |
| 105 | nextCh <- struct{}{} | |
| 106 | } else { | |
| 107 | base.Fill(w, width, st) | |
| 108 | } | |
| 109 | }) | |
| 110 | cf := &myBarFiller{ | |
| 111 | BarFiller: filler, | |
| 112 | base: base, | |
| 113 | } | |
| 114 | return cf, nextCh | |
| 115 | } | |
| 116 | ||
| 117 | func newCustomPercentage(ch <-chan struct{}) decor.Decorator { | |
| 100 | func newCustomPercentage(nextCh <-chan struct{}) decor.Decorator { | |
| 118 | 101 | base := decor.Percentage() |
| 119 | 102 | fn := func(s decor.Statistics) string { |
| 120 | 103 | select { |
| 121 | case <-ch: | |
| 104 | case <-nextCh: | |
| 122 | 105 | return "" |
| 123 | 106 | default: |
| 124 | 107 | return base.Decor(s) |