Codebase list golang-github-vbauerster-mpb / 62169fb
custom filler impl BaseFiller Vladimir Bauer 6 years ago
1 changed file(s) with 22 addition(s) and 12 deletion(s). Raw diff Collapse all Expand all
1616 total := 100
1717 msgCh := make(chan string)
1818 resumeCh := make(chan struct{})
19 filler, nextCh := makeCustomFiller(msgCh, resumeCh)
19 filler, nextCh := newCustomFiller(msgCh, resumeCh)
2020 bar := p.Add(int64(total), filler,
2121 mpb.PrependDecorators(
2222 decor.Name("my bar:"),
3232 var err error
3333 for i := 0; i < total; i++ {
3434 if err != nil {
35 bar.SetRefill(int64(i))
3536 time.Sleep(3 * time.Second)
3637 resumeCh <- struct{}{}
3738 err = nil
4950 p.Wait()
5051 }
5152
52 func makeCustomFiller(ch <-chan string, resume <-chan struct{}) (mpb.FillerFunc, <-chan struct{}) {
53 type refiller interface {
54 SetRefill(int64)
55 }
56 filler := mpb.NewBarFiller(mpb.DefaultBarStyle, false)
53 type customFiller struct {
54 mpb.Filler
55 base mpb.Filler
56 }
57
58 // implementing mpb.BaseFiller, so bar.SetRefill works
59 func (cf *customFiller) BaseFiller() mpb.Filler {
60 return cf.base
61 }
62
63 func newCustomFiller(ch <-chan string, resume <-chan struct{}) (mpb.Filler, <-chan struct{}) {
64 base := mpb.NewBarFiller(mpb.DefaultBarStyle, false)
5765 nextCh := make(chan struct{}, 1)
5866 var msg *string
59 return func(w io.Writer, width int, st *decor.Statistics) {
67 filler := mpb.FillerFunc(func(w io.Writer, width int, st *decor.Statistics) {
6068 select {
6169 case m := <-ch:
6270 defer func() {
63 if f, ok := filler.(refiller); ok {
64 f.SetRefill(st.Current)
65 }
6671 msg = &m
6772 }()
6873 nextCh <- struct{}{}
7580 fmt.Fprintf(w, limitFmt, *msg)
7681 nextCh <- struct{}{}
7782 } else {
78 filler.Fill(w, width, st)
83 base.Fill(w, width, st)
7984 }
80 }, nextCh
85 })
86 cf := &customFiller{
87 Filler: filler,
88 base: base,
89 }
90 return cf, nextCh
8191 }
8292
8393 type myPercentageDecorator struct {