-
Notifications
You must be signed in to change notification settings - Fork 10
/
decorator.go
142 lines (123 loc) · 2.41 KB
/
decorator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Copyright (C) 2016-2017 Vladimir Bauer
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package getparty
import (
"fmt"
"sync"
"github.com/vbauerster/mpb/v4/decor"
)
type msgGate struct {
msgCh chan *message
done chan struct{}
}
type message struct {
msg string
flashTimes int
final bool
done chan struct{}
}
type percentageDecorator struct {
decor.WC
format string
gate msgGate
mu sync.Mutex
messages []*message
finalMsg *message
}
func newPercentageWithTotal(pairFormat string, g msgGate, wc decor.WC) decor.Decorator {
wc.Init()
d := &percentageDecorator{
WC: wc,
format: pairFormat,
gate: g,
}
go d.receive()
return d
}
func (d *percentageDecorator) receive() {
for {
select {
case m := <-d.gate.msgCh:
d.mu.Lock()
if d.finalMsg == nil {
d.messages = append(d.messages, m)
}
d.mu.Unlock()
case <-d.gate.done:
return
}
}
}
func (d *percentageDecorator) Decor(stat *decor.Statistics) string {
if d.finalMsg != nil {
return d.FormatMsg(d.finalMsg.msg)
}
d.mu.Lock()
if len(d.messages) > 0 {
m := d.messages[0]
if m.flashTimes > 0 {
if m.final && d.finalMsg == nil {
d.finalMsg = m
close(m.done)
}
m.flashTimes--
d.mu.Unlock()
return d.FormatMsg(m.msg)
}
copy(d.messages, d.messages[1:])
d.messages = d.messages[:len(d.messages)-1]
}
d.mu.Unlock()
completed := percentage(stat.Total, stat.Current, 100)
msg := fmt.Sprintf(d.format, completed, decor.CounterKiB(stat.Total))
return d.FormatMsg(msg)
}
func (d *percentageDecorator) Shutdown() {
close(d.gate.done)
}
func percentage(total, current, ratio int64) float64 {
if total <= 0 {
return 0
}
return float64(ratio*current) / float64(total)
}
type tryGate struct {
msgCh chan string
done chan struct{}
}
type triesDecorator struct {
decor.WC
gate tryGate
mu sync.RWMutex
msg string
}
func newTriesDecorator(g tryGate, wc decor.WC) decor.Decorator {
wc.Init()
d := &triesDecorator{
WC: wc,
gate: g,
}
go d.receive()
return d
}
func (d *triesDecorator) receive() {
for {
select {
case m := <-d.gate.msgCh:
d.mu.Lock()
d.msg = m
d.mu.Unlock()
case <-d.gate.done:
return
}
}
}
func (d *triesDecorator) Decor(_ *decor.Statistics) string {
d.mu.RLock()
defer d.mu.RUnlock()
return d.FormatMsg(d.msg)
}
func (d *triesDecorator) Shutdown() {
close(d.gate.done)
}