custom filler impl BaseFiller
Vladimir Bauer
6 years ago
| 16 | 16 | total := 100 |
| 17 | 17 | msgCh := make(chan string) |
| 18 | 18 | resumeCh := make(chan struct{}) |
| 19 | filler, nextCh := makeCustomFiller(msgCh, resumeCh) | |
| 19 | filler, nextCh := newCustomFiller(msgCh, resumeCh) | |
| 20 | 20 | bar := p.Add(int64(total), filler, |
| 21 | 21 | mpb.PrependDecorators( |
| 22 | 22 | decor.Name("my bar:"), |
| 32 | 32 | var err error |
| 33 | 33 | for i := 0; i < total; i++ { |
| 34 | 34 | if err != nil { |
| 35 | bar.SetRefill(int64(i)) | |
| 35 | 36 | time.Sleep(3 * time.Second) |
| 36 | 37 | resumeCh <- struct{}{} |
| 37 | 38 | err = nil |
| 49 | 50 | p.Wait() |
| 50 | 51 | } |
| 51 | 52 | |
| 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) | |
| 57 | 65 | nextCh := make(chan struct{}, 1) |
| 58 | 66 | 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) { | |
| 60 | 68 | select { |
| 61 | 69 | case m := <-ch: |
| 62 | 70 | defer func() { |
| 63 | if f, ok := filler.(refiller); ok { | |
| 64 | f.SetRefill(st.Current) | |
| 65 | } | |
| 66 | 71 | msg = &m |
| 67 | 72 | }() |
| 68 | 73 | nextCh <- struct{}{} |
| 75 | 80 | fmt.Fprintf(w, limitFmt, *msg) |
| 76 | 81 | nextCh <- struct{}{} |
| 77 | 82 | } else { |
| 78 | filler.Fill(w, width, st) | |
| 83 | base.Fill(w, width, st) | |
| 79 | 84 | } |
| 80 | }, nextCh | |
| 85 | }) | |
| 86 | cf := &customFiller{ | |
| 87 | Filler: filler, | |
| 88 | base: base, | |
| 89 | } | |
| 90 | return cf, nextCh | |
| 81 | 91 | } |
| 82 | 92 | |
| 83 | 93 | type myPercentageDecorator struct { |