introduce OnAbort decorator wrapper
address issue #103
Vladimir Bauer
4 years ago
| 23 | 23 |
mpb.BarOptional(mpb.BarRemoveOnComplete(), i == 0),
|
| 24 | 24 |
mpb.PrependDecorators(
|
| 25 | 25 |
decor.Name(name),
|
| 26 | |
decor.EwmaETA(decor.ET_STYLE_GO, 60, decor.WCSyncSpace),
|
| 27 | 26 |
),
|
| 28 | 27 |
mpb.AppendDecorators(
|
| 29 | 28 |
decor.Any(func(s decor.Statistics) string {
|
|
| 32 | 31 |
decor.Any(func(s decor.Statistics) string {
|
| 33 | 32 |
return fmt.Sprintf("aborted: %v", s.Aborted)
|
| 34 | 33 |
}, 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"),
|
| 36 | 36 |
),
|
| 37 | 37 |
)
|
| 38 | 38 |
go func() {
|
|
| 40 | 40 |
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
|
| 41 | 41 |
max := 100 * time.Millisecond
|
| 42 | 42 |
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()
|
| 46 | 43 |
if bar.ID() == 2 && i >= 42 {
|
| 47 | 44 |
bar.Abort(false)
|
| 48 | 45 |
}
|
| 49 | 46 |
time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
|
| 50 | 47 |
bar.Increment()
|
| 51 | |
// we need to call DecoratorEwmaUpdate to fulfill ewma decorator's contract
|
| 52 | |
bar.DecoratorEwmaUpdate(time.Since(start))
|
| 53 | 48 |
}
|
| 54 | 49 |
}()
|
| 55 | 50 |
}
|
|
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 |
}
|