Codebase list golang-github-vbauerster-mpb / b770800
use BarFillerMiddleware Vladimir Bauer 6 years ago
1 changed file(s) with 26 addition(s) and 43 deletion(s). Raw diff Collapse all Expand all
1717 total := 100
1818 msgCh := make(chan string)
1919 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 }),
2244 mpb.PrependDecorators(
2345 decor.Name("my bar:"),
2446 ),
7597 ew.Unlock()
7698 }
7799
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 {
118101 base := decor.Percentage()
119102 fn := func(s decor.Statistics) string {
120103 select {
121 case <-ch:
104 case <-nextCh:
122105 return ""
123106 default:
124107 return base.Decor(s)