forked from gosuri/uiprogress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bar.go
376 lines (313 loc) · 9.11 KB
/
bar.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package jprogress
import (
"bytes"
"errors"
"fmt"
"sync"
"time"
"github.com/chroblert/jprogress/util/strutil"
)
var (
// Fill is the default character representing completed progress
Fill byte = '='
// Head is the default character that moves when progress is updated
Head byte = '>'
// Empty is the default character that represents the empty progress
Empty byte = '-'
// LeftEnd is the default character in the left most part of the progress indicator
LeftEnd byte = '['
// RightEnd is the default character in the right most part of the progress indicator
RightEnd byte = ']'
// Width is the default width of the progress bar
Width = 70
// ErrMaxCurrentReached is error when trying to set current value that exceeds the total value
ErrMaxCurrentReached = errors.New("errors: current value is greater total value")
)
// Bar represents a progress bar
type Bar struct {
// Total of the total for the progress bar
Total int64
// LeftEnd is character in the left most part of the progress indicator. Defaults to '['
LeftEnd byte
// RightEnd is character in the right most part of the progress indicator. Defaults to ']'
RightEnd byte
// Fill is the character representing completed progress. Defaults to '='
Fill byte
// Head is the character that moves when progress is updated. Defaults to '>'
Head byte
// Empty is the character that represents the empty progress. Default is '-'
Empty byte
// TimeStated is time progress began
TimeStarted time.Time
// Width is the width of the progress bar
Width int
// timeElased is the time elapsed for the progress
timeElapsed time.Duration
current int64
mtx *sync.RWMutex
appendFuncs []DecoratorFunc
prependFuncs []DecoratorFunc
}
// DecoratorFunc is a function that can be prepended and appended to the progress bar
type DecoratorFunc func(b *Bar) string
// NewBar returns a new progress bar
func NewBar(total int) *Bar {
return &Bar{
Total: int64(total),
Width: Width,
LeftEnd: LeftEnd,
RightEnd: RightEnd,
Head: Head,
Fill: Fill,
Empty: Empty,
mtx: &sync.RWMutex{},
}
}
// NewBar64 returns a new progress bar
func NewBar64(total int64) *Bar {
return &Bar{
Total: total,
Width: Width,
LeftEnd: LeftEnd,
RightEnd: RightEnd,
Head: Head,
Fill: Fill,
Empty: Empty,
mtx: &sync.RWMutex{},
}
}
// Set the current count of the bar. It returns ErrMaxCurrentReached when trying n exceeds the total value. This is atomic operation and concurrency safe.
func (b *Bar) Set(n int) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if int64(n) > b.Total {
return ErrMaxCurrentReached
}
b.current = int64(n)
return nil
}
// Set64 the current count of the bar. It returns ErrMaxCurrentReached when trying n exceeds the total value. This is atomic operation and concurrency safe.
func (b *Bar) Set64(n int64) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if n > b.Total {
return ErrMaxCurrentReached
}
b.current = n
return nil
}
// Incr increments the current value by 1, time elapsed to current time and returns true. It returns false if the cursor has reached or exceeds total value.
func (b *Bar) Incr() bool {
b.mtx.Lock()
defer b.mtx.Unlock()
n := b.current + 1
if n > b.Total {
return false
}
var t time.Time
if b.TimeStarted == t {
b.TimeStarted = time.Now()
}
b.timeElapsed = time.Since(b.TimeStarted)
b.current = n
return true
}
// Add increments the current value by num, time elapsed to current time and returns true. It returns false if the cursor has reached or exceeds total value.
func (b *Bar) Add(num int) bool {
b.mtx.Lock()
defer b.mtx.Unlock()
n := b.current + int64(num)
if n > b.Total {
return false
}
var t time.Time
if b.TimeStarted == t {
b.TimeStarted = time.Now()
}
b.timeElapsed = time.Since(b.TimeStarted)
b.current = n
return true
}
// Add64 increments the current value by num, time elapsed to current time and returns true. It returns false if the cursor has reached or exceeds total value.
func (b *Bar) Add64(num int64) bool {
b.mtx.Lock()
defer b.mtx.Unlock()
n := b.current + num
if n > b.Total {
return false
}
var t time.Time
if b.TimeStarted == t {
b.TimeStarted = time.Now()
}
b.timeElapsed = time.Since(b.TimeStarted)
b.current = n
return true
}
// Finish set the current value to total, time elapsed to current time
func (b *Bar) Finish() error {
b.mtx.Lock()
defer b.mtx.Unlock()
var t time.Time
if b.TimeStarted == t {
b.TimeStarted = time.Now()
}
b.timeElapsed = time.Since(b.TimeStarted)
b.current = b.Total
return nil
}
// Current64 returns the current progress of the bar
func (b *Bar) Current64() int64 {
b.mtx.RLock()
defer b.mtx.RUnlock()
return b.current
}
// Current returns the current progress of the bar
func (b *Bar) Current() int {
b.mtx.RLock()
defer b.mtx.RUnlock()
return int(b.current)
}
// AppendFunc runs the decorator function and renders the output on the right of the progress bar
func (b *Bar) AppendFunc(f DecoratorFunc) *Bar {
b.mtx.Lock()
defer b.mtx.Unlock()
b.appendFuncs = append(b.appendFuncs, f)
return b
}
// AppendCompleted appends the completion percent to the progress bar
func (b *Bar) AppendCompleted() *Bar {
b.AppendFunc(func(b *Bar) string {
return b.CompletedPercentString()
})
return b
}
// AppendElapsed appends the time elapsed the be progress bar
func (b *Bar) AppendElapsed() *Bar {
b.AppendFunc(func(b *Bar) string {
return strutil.PadLeft(b.TimeElapsedString(), 5, ' ')
})
return b
}
// PrependFunc runs decorator function and render the output left the progress bar
func (b *Bar) PrependFunc(f DecoratorFunc) *Bar {
b.mtx.Lock()
defer b.mtx.Unlock()
b.prependFuncs = append(b.prependFuncs, f)
return b
}
// PrependCompleted prepends the precent completed to the progress bar
func (b *Bar) PrependCompleted() *Bar {
b.PrependFunc(func(b *Bar) string {
return b.CompletedPercentString()
})
return b
}
// PrependSlashNum prepends <processed num>/<total> to the progress bar
func (b *Bar) PrependSlashNum() *Bar {
b.PrependFunc(func(b *Bar) string {
return fmt.Sprintf("%d/%d:%.2f", b.Current64(), b.Total, b.TimeElapsed().Seconds())
})
return b
}
// AppendSlashNum append <processed num>/<total> to the progress bar
func (b *Bar) AppendSlashNum() *Bar {
b.AppendFunc(func(b *Bar) string {
return strutil.PadLeft(fmt.Sprintf("%d/%d", b.Current64(), b.Total), 10, ' ')
})
return b
}
// AppendStr append str to the progress bar
func (b *Bar) AppendStr(str string) *Bar {
b.AppendFunc(func(b *Bar) string {
return str
})
return b
}
// PrependStr prepends str to the progress bar
func (b *Bar) PrependStr(str string) *Bar {
b.AppendFunc(func(b *Bar) string {
return str
})
return b
}
// PrependDesc prepends <processed num>/<total> to the progress bar
func (b *Bar) PrependDesc(description string) *Bar {
b.PrependFunc(func(b *Bar) string {
return description
})
return b
}
// AppendETA append the eta to the progress bar
func (b *Bar) AppendETA() *Bar {
b.AppendFunc(func(b *Bar) string {
elapsedSeconds := b.TimeElapsed().Seconds()
etaSeconds := elapsedSeconds/(float64(b.Current64())/float64(b.Total)) - elapsedSeconds
return strutil.PrettyTime(time.Duration(etaSeconds) * time.Second)
})
return b
}
// PrependElapsed prepends the time elapsed to the begining of the bar
func (b *Bar) PrependElapsed() *Bar {
b.PrependFunc(func(b *Bar) string {
return strutil.PadLeft(b.TimeElapsedString(), 5, ' ')
})
return b
}
// Bytes returns the byte presentation of the progress bar
func (b *Bar) Bytes() []byte {
completedWidth := int(float64(b.Width) * (b.CompletedPercent() / 100.00))
// add fill and empty bits
var buf bytes.Buffer
for i := 0; i < completedWidth; i++ {
buf.WriteByte(b.Fill)
}
for i := 0; i < b.Width-completedWidth; i++ {
buf.WriteByte(b.Empty)
}
// set head bit
pb := buf.Bytes()
if completedWidth > 0 && completedWidth < b.Width {
pb[completedWidth-1] = b.Head
}
// set left and right ends bits
pb[0], pb[len(pb)-1] = b.LeftEnd, b.RightEnd
// render append functions to the right of the bar
for _, f := range b.appendFuncs {
pb = append(pb, ' ')
pb = append(pb, []byte(f(b))...)
}
// render prepend functions to the left of the bar
for _, f := range b.prependFuncs {
args := []byte(f(b))
args = append(args, ' ')
pb = append(args, pb...)
}
return pb
}
// String returns the string representation of the bar
func (b *Bar) String() string {
return string(b.Bytes())
}
// CompletedPercent return the percent completed
func (b *Bar) CompletedPercent() float64 {
return (float64(b.Current64()) / float64(b.Total)) * 100.00
}
// CompletedPercent return the percent completed
func (b *Bar) IsComplete() bool {
return b.Current64() == b.Total
}
// CompletedPercentString returns the formatted string representation of the completed percent
func (b *Bar) CompletedPercentString() string {
return fmt.Sprintf("%3.f%%", b.CompletedPercent())
}
// TimeElapsed returns the time elapsed
func (b *Bar) TimeElapsed() time.Duration {
b.mtx.RLock()
defer b.mtx.RUnlock()
return b.timeElapsed
}
// TimeElapsedString returns the formatted string represenation of the time elapsed
func (b *Bar) TimeElapsedString() string {
return strutil.PrettyTime(b.TimeElapsed())
}