Codebase list golang-github-vbauerster-mpb / 086ddfa
introduce OnAbort decorator wrapper address issue #103 Vladimir Bauer 4 years ago
2 changed file(s) with 40 addition(s) and 7 deletion(s). Raw diff Collapse all Expand all
2323 mpb.BarOptional(mpb.BarRemoveOnComplete(), i == 0),
2424 mpb.PrependDecorators(
2525 decor.Name(name),
26 decor.EwmaETA(decor.ET_STYLE_GO, 60, decor.WCSyncSpace),
2726 ),
2827 mpb.AppendDecorators(
2928 decor.Any(func(s decor.Statistics) string {
3231 decor.Any(func(s decor.Statistics) string {
3332 return fmt.Sprintf("aborted: %v", s.Aborted)
3433 }, decor.WCSyncSpaceR),
35 decor.OnComplete(decor.Percentage(decor.WCSyncSpace), "done"),
34 decor.OnComplete(decor.NewPercentage("%d", decor.WCSyncSpace), "done"),
35 decor.OnAbort(decor.NewPercentage("%d", decor.WCSyncSpace), "ohno"),
3636 ),
3737 )
3838 go func() {
4040 rng := rand.New(rand.NewSource(time.Now().UnixNano()))
4141 max := 100 * time.Millisecond
4242 for i := 0; !bar.Completed(); i++ {
43 // start variable is solely for EWMA calculation
44 // EWMA's unit of measure is an iteration's duration
45 start := time.Now()
4643 if bar.ID() == 2 && i >= 42 {
4744 bar.Abort(false)
4845 }
4946 time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
5047 bar.Increment()
51 // we need to call DecoratorEwmaUpdate to fulfill ewma decorator's contract
52 bar.DecoratorEwmaUpdate(time.Since(start))
5348 }
5449 }()
5550 }
0 package decor
1
2 // OnAbort returns decorator, which wraps provided decorator with sole
3 // purpose to display provided message on abort event. It has no effect
4 // if bar.Abort(drop bool) is called with true argument.
5 //
6 // `decorator` Decorator to wrap
7 //
8 // `message` message to display on complete event
9 //
10 func OnAbort(decorator Decorator, message string) Decorator {
11 d := &onAbortWrapper{
12 Decorator: decorator,
13 msg: message,
14 }
15 if md, ok := decorator.(*mergeDecorator); ok {
16 d.Decorator, md.Decorator = md.Decorator, d
17 return md
18 }
19 return d
20 }
21
22 type onAbortWrapper struct {
23 Decorator
24 msg string
25 }
26
27 func (d *onAbortWrapper) Decor(s Statistics) string {
28 if s.Aborted {
29 wc := d.GetConf()
30 return wc.FormatMsg(d.msg)
31 }
32 return d.Decorator.Decor(s)
33 }
34
35 func (d *onAbortWrapper) Base() Decorator {
36 return d.Decorator
37 }