-
Notifications
You must be signed in to change notification settings - Fork 1
/
progress_pool.go
145 lines (126 loc) · 2.28 KB
/
progress_pool.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
143
144
145
package gogress
import (
"context"
"os"
"sync"
"time"
"github.com/snakeice/gogress/writer"
)
func NewPool() *Pool {
ctx, fn := context.WithCancel(context.Background())
return &Pool{
bars: []*Progress{},
ctx: ctx,
stopFn: fn,
isRunning: false,
RefreshRate: time.Second / 45,
writer: writer.New(os.Stdout),
}
}
type Pool struct {
bars []*Progress
ctx context.Context
stopFn context.CancelFunc
RefreshRate time.Duration
writer *writer.Writer
isRunning bool
mu sync.Mutex
finishOnce sync.Once
}
func (p *Pool) AddBar(bar *Progress) int {
p.mu.Lock()
defer p.mu.Unlock()
p.bars = append(p.bars, bar)
bar.setWriter(p.writer)
bar.pooled = true
if p.isRunning {
bar.Start()
}
for id, _bar := range p.bars {
_bar.ID = id
}
return len(p.bars) - 1
}
func remove(slice []*Progress, id int) []*Progress {
return append(slice[:id], slice[id+1:]...)
}
func (p *Pool) RemoveBar(bar *Progress) int {
p.mu.Lock()
defer p.mu.Unlock()
p.bars = remove(p.bars, bar.ID)
for id, _bar := range p.bars {
_bar.ID = id
}
return len(p.bars) - 1
}
func (p *Pool) NewBarDef() *Progress {
bar := NewDef()
p.AddBar(bar)
return bar
}
func (p *Pool) NewBar(max int) *Progress {
return p.NewBar64(int64(max))
}
func (p *Pool) NewBar64(max int64) *Progress {
bar := New64(max)
p.AddBar(bar)
return bar
}
func (p *Pool) refresher() {
for {
select {
case <-p.ctx.Done():
p.isRunning = false
return
case <-time.After(p.RefreshRate):
p.Update()
}
}
}
func (p *Pool) Start() *Pool {
p.mu.Lock()
defer p.mu.Unlock()
if p.isRunning {
return p
}
p.isRunning = true
for _, bar := range p.bars {
bar.Start()
}
p.Update()
go p.refresher()
return p
}
func (p *Pool) Update() {
for _, bar := range p.bars {
bar.Update()
}
p.writer.Flush(len(p.bars))
}
func (p *Pool) FinishAll() {
p.finishOnce.Do(func() {
p.stopFn()
for _, bar := range p.bars {
bar.Finish()
}
p.mu.Lock()
defer p.mu.Unlock()
p.Update()
p.isRunning = false
})
}
func (p *Pool) IsFinished() bool {
var result = true
for _, bar := range p.bars {
result = bar.IsFinished() && result
if !result {
break
}
}
return result
}
func (p *Pool) Wait() {
for !p.IsFinished() {
time.Sleep(time.Millisecond * 100)
}
}