Codebase list golang-github-vbauerster-mpb / f9cca86
suppress bar example Vladimir Bauer 6 years ago
2 changed file(s) with 96 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 module github.com/vbauerster/mpb/_examples/suppressBar
1
2 go 1.13
3
4 require github.com/vbauerster/mpb/v4 v4.9.4-0.20190913124757-1f1fd0ab790e // indirect
0 package main
1
2 import (
3 "fmt"
4 "io"
5 "math/rand"
6 "time"
7
8 "github.com/vbauerster/mpb/v4"
9 "github.com/vbauerster/mpb/v4/decor"
10 )
11
12 func main() {
13 p := mpb.New()
14
15 total := 100
16 msgCh := make(chan string)
17 filler, nextCh := makeCustomFiller(15, msgCh)
18 bar := p.Add(int64(total), filler,
19 mpb.PrependDecorators(
20 decor.Name("my bar:"),
21 ),
22 mpb.AppendDecorators(
23 newCustomPercentage(decor.Percentage(), nextCh),
24 ),
25 )
26 // simulating some work
27 go func() {
28 rng := rand.New(rand.NewSource(time.Now().UnixNano()))
29 max := 100 * time.Millisecond
30 for i := 0; i < total; i++ {
31 time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
32 if i == 33 {
33 msgCh <- "some error, retrying..."
34 }
35 bar.Increment()
36 }
37 }()
38
39 p.Wait()
40 }
41
42 func makeCustomFiller(maxFlash int, ch <-chan string) (mpb.FillerFunc, <-chan struct{}) {
43 type refiller interface {
44 SetRefill(int64)
45 }
46 filler := mpb.NewBarFiller()
47 nextCh := make(chan struct{}, 1)
48 var msg string
49 var count int
50 return func(w io.Writer, width int, st *decor.Statistics) {
51 if count != 0 {
52 nextCh <- struct{}{}
53 limitFmt := fmt.Sprintf("%%.%ds", width)
54 fmt.Fprintf(w, limitFmt, msg)
55 count--
56 return
57 }
58 select {
59 case msg = <-ch:
60 nextCh <- struct{}{}
61 if f, ok := filler.(refiller); ok {
62 defer f.SetRefill(st.Current)
63 }
64 count = maxFlash
65 default:
66 }
67 filler.Fill(w, width, st)
68 }, nextCh
69 }
70
71 type myPercentageDecorator struct {
72 decor.Decorator
73 ch <-chan struct{}
74 }
75
76 func (d *myPercentageDecorator) Decor(st *decor.Statistics) string {
77 select {
78 case <-d.ch:
79 return ""
80 default:
81 return d.Decorator.Decor(st)
82 }
83 }
84
85 func newCustomPercentage(base decor.Decorator, ch <-chan struct{}) decor.Decorator {
86 return &myPercentageDecorator{
87 Decorator: base,
88 ch: ch,
89 }
90 }