refactoring suppressBar
Vladimir Bauer
3 years ago
| 19 | 19 | msgCh := make(chan string) |
| 20 | 20 | resumeCh := make(chan struct{}) |
| 21 | 21 | nextCh := make(chan struct{}, 1) |
| 22 | ew := &errorWrapper{} | |
| 23 | timer := time.AfterFunc(2*time.Second, func() { | |
| 24 | ew.reset(errors.New("timeout")) | |
| 25 | }) | |
| 26 | defer timer.Stop() | |
| 22 | 27 | bar := p.AddBar(int64(total), |
| 23 | 28 | mpb.BarFillerMiddleware(func(base mpb.BarFiller) mpb.BarFiller { |
| 24 | 29 | var msg *string |
| 25 | return mpb.BarFillerFunc(func(w io.Writer, st decor.Statistics) { | |
| 26 | select { | |
| 27 | case m := <-msgCh: | |
| 30 | var times int | |
| 31 | return mpb.BarFillerFunc(func(w io.Writer, st decor.Statistics) error { | |
| 32 | if msg == nil { | |
| 33 | select { | |
| 34 | case m := <-msgCh: | |
| 35 | msg = &m | |
| 36 | times = 10 | |
| 37 | nextCh <- struct{}{} | |
| 38 | default: | |
| 39 | } | |
| 40 | return base.Fill(w, st) | |
| 41 | } | |
| 42 | switch { | |
| 43 | case times == 0, st.Completed, st.Aborted: | |
| 28 | 44 | defer func() { |
| 29 | msg = &m | |
| 45 | msg = nil | |
| 30 | 46 | }() |
| 31 | nextCh <- struct{}{} | |
| 32 | case <-resumeCh: | |
| 33 | msg = nil | |
| 47 | resumeCh <- struct{}{} | |
| 34 | 48 | default: |
| 49 | times-- | |
| 35 | 50 | } |
| 36 | if msg != nil { | |
| 37 | io.WriteString(w, runewidth.Truncate(*msg, st.AvailableWidth, "…")) | |
| 38 | nextCh <- struct{}{} | |
| 39 | } else { | |
| 40 | base.Fill(w, st) | |
| 41 | } | |
| 51 | _, err := io.WriteString(w, runewidth.Truncate(*msg, st.AvailableWidth, "…")) | |
| 52 | nextCh <- struct{}{} | |
| 53 | return err | |
| 42 | 54 | }) |
| 43 | 55 | }), |
| 44 | 56 | mpb.PrependDecorators(decor.Name("my bar:")), |
| 45 | 57 | mpb.AppendDecorators(newCustomPercentage(nextCh)), |
| 46 | 58 | ) |
| 47 | ew := &errorWrapper{} | |
| 48 | time.AfterFunc(2*time.Second, func() { | |
| 49 | ew.reset(errors.New("timeout")) | |
| 50 | }) | |
| 51 | 59 | // simulating some work |
| 52 | 60 | go func() { |
| 53 | 61 | rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
| 56 | 64 | time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) |
| 57 | 65 | if ew.isErr() { |
| 58 | 66 | msgCh <- fmt.Sprintf("%s at %d, retrying...", ew.Error(), i) |
| 59 | go ew.reset(nil) | |
| 60 | 67 | i-- |
| 61 | 68 | bar.SetRefill(int64(i)) |
| 62 | time.Sleep(3 * time.Second) | |
| 63 | resumeCh <- struct{}{} | |
| 69 | ew.reset(nil) | |
| 70 | <-resumeCh | |
| 64 | 71 | continue |
| 65 | 72 | } |
| 66 | 73 | bar.Increment() |