Codebase list golang-github-vbauerster-mpb / 12267ab
elapsed refactoring Vladimir Bauer 6 years ago
2 changed file(s) with 20 addition(s) and 29 deletion(s). Raw diff Collapse all Expand all
00 package decor
11
22 import (
3 "fmt"
43 "time"
54 )
65
7 // Elapsed returns elapsed time decorator.
6 // Elapsed decorator. It's wrapper of NewElapsed.
87 //
98 // `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
109 //
1110 // `wcc` optional WC config
1211 func Elapsed(style TimeStyle, wcc ...WC) Decorator {
12 return NewElapsed(style, time.Now(), wcc...)
13 }
14
15 // NewElapsed returns elapsed time decorator.
16 //
17 // `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
18 //
19 // `startTime` start time
20 //
21 // `wcc` optional WC config
22 func NewElapsed(style TimeStyle, startTime time.Time, wcc ...WC) Decorator {
1323 var wc WC
1424 for _, widthConf := range wcc {
1525 wc = widthConf
1727 wc.Init()
1828 d := &elapsedDecorator{
1929 WC: wc,
20 style: style,
21 startTime: time.Now(),
30 startTime: startTime,
31 producer: chooseTimeProducer(style),
2232 }
2333 return d
2434 }
2535
2636 type elapsedDecorator struct {
2737 WC
28 style TimeStyle
2938 startTime time.Time
39 producer func(time.Duration) string
3040 msg string
3141 completeMsg *string
3242 }
3949 return d.FormatMsg(d.msg)
4050 }
4151
42 timeElapsed := time.Since(d.startTime)
43 hours := int64((timeElapsed / time.Hour) % 60)
44 minutes := int64((timeElapsed / time.Minute) % 60)
45 seconds := int64((timeElapsed / time.Second) % 60)
46
47 switch d.style {
48 case ET_STYLE_GO:
49 d.msg = fmt.Sprint(time.Duration(timeElapsed.Seconds()) * time.Second)
50 case ET_STYLE_HHMMSS:
51 d.msg = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
52 case ET_STYLE_HHMM:
53 d.msg = fmt.Sprintf("%02d:%02d", hours, minutes)
54 case ET_STYLE_MMSS:
55 if hours > 0 {
56 d.msg = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
57 } else {
58 d.msg = fmt.Sprintf("%02d:%02d", minutes, seconds)
59 }
60 }
61
52 d.msg = d.producer(time.Since(d.startTime))
6253 return d.FormatMsg(d.msg)
6354 }
6455
5454 WC: wc,
5555 average: average,
5656 normalizer: normalizer,
57 producer: chooseEtaProducer(style),
57 producer: chooseTimeProducer(style),
5858 }
5959 return d
6060 }
9696 d.completeMsg = &msg
9797 }
9898
99 // AverageETA decorator.
99 // AverageETA decorator. It's wrapper of NewAverageETA.
100100 //
101101 // `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
102102 //
121121 d := &averageETA{
122122 WC: wc,
123123 startTime: startTime,
124 producer: chooseEtaProducer(style),
124 producer: chooseTimeProducer(style),
125125 }
126126 return d
127127 }
191191 })
192192 }
193193
194 func chooseEtaProducer(style TimeStyle) func(time.Duration) string {
194 func chooseTimeProducer(style TimeStyle) func(time.Duration) string {
195195 switch style {
196196 case ET_STYLE_HHMMSS:
197197 return func(remaining time.Duration) string {