-
-
Notifications
You must be signed in to change notification settings - Fork 228
/
progressbar.go
1490 lines (1289 loc) · 39.2 KB
/
progressbar.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package progressbar
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/mitchellh/colorstring"
"github.com/rivo/uniseg"
"golang.org/x/term"
)
// ProgressBar is a thread-safe, simple
// progress bar
type ProgressBar struct {
state state
config config
lock sync.Mutex
}
// State is the basic properties of the bar
type State struct {
Max int64
CurrentNum int64
CurrentPercent float64
CurrentBytes float64
SecondsSince float64
SecondsLeft float64
KBsPerSecond float64
Description string
}
type state struct {
currentNum int64
currentPercent int
lastPercent int
currentSaucerSize int
isAltSaucerHead bool
lastShown time.Time
startTime time.Time // time when the progress bar start working
counterTime time.Time
counterNumSinceLast int64
counterLastTenRates []float64
spinnerIdx int // the index of spinner
maxLineWidth int
currentBytes float64
finished bool
exit bool // Progress bar exit halfway
details []string // details to show,only used when detail row is set to more than 0
rendered string
}
type config struct {
max int64 // max number of the counter
maxHumanized string
maxHumanizedSuffix string
width int
writer io.Writer
theme Theme
renderWithBlankState bool
description string
iterationString string
ignoreLength bool // ignoreLength if max bytes not known
// whether the output is expected to contain color codes
colorCodes bool
// show rate of change in kB/sec or MB/sec
showBytes bool
// show the iterations per second
showIterationsPerSecond bool
showIterationsCount bool
// whether the progress bar should show the total bytes (e.g. 23/24 or 23/-, vs. just 23).
showTotalBytes bool
// whether the progress bar should show elapsed time.
// always enabled if predictTime is true.
elapsedTime bool
showElapsedTimeOnFinish bool
// whether the progress bar should attempt to predict the finishing
// time of the progress based on the start time and the average
// number of seconds between increments.
predictTime bool
// minimum time to wait in between updates
throttleDuration time.Duration
// clear bar once finished
clearOnFinish bool
// spinnerType should be a number between 0-75
spinnerType int
// spinnerTypeOptionUsed remembers if the spinnerType was changed manually
spinnerTypeOptionUsed bool
// spinnerChangeInterval the change interval of spinner
// if set this attribute to 0, the spinner only change when renderProgressBar was called
// for example, each time when Add() was called,which will call renderProgressBar function
spinnerChangeInterval time.Duration
// spinner represents the spinner as a slice of string
spinner []string
// fullWidth specifies whether to measure and set the bar to a specific width
fullWidth bool
// invisible doesn't render the bar at all, useful for debugging
invisible bool
onCompletion func()
// whether the render function should make use of ANSI codes to reduce console I/O
useANSICodes bool
// whether to use the IEC units (e.g. MiB) instead of the default SI units (e.g. MB)
useIECUnits bool
// showDescriptionAtLineEnd specifies whether description should be written at line end instead of line start
showDescriptionAtLineEnd bool
// specifies how many rows of details to show,default value is 0 and no details will be shown
maxDetailRow int
stdBuffer bytes.Buffer
}
// Theme defines the elements of the bar
type Theme struct {
Saucer string
AltSaucerHead string
SaucerHead string
SaucerPadding string
BarStart string
BarEnd string
// BarStartFilled is used after the Bar starts filling, if set. Otherwise, it defaults to BarStart.
BarStartFilled string
// BarEndFilled is used once the Bar finishes, if set. Otherwise, it defaults to BarEnd.
BarEndFilled string
}
var (
// ThemeDefault is given by default (if not changed with OptionSetTheme), and it looks like "|████ |".
ThemeDefault = Theme{Saucer: "█", SaucerPadding: " ", BarStart: "|", BarEnd: "|"}
// ThemeASCII is a predefined Theme that uses ASCII symbols. It looks like "[===>...]".
// Configure it with OptionSetTheme(ThemeASCII).
ThemeASCII = Theme{
Saucer: "=",
SaucerHead: ">",
SaucerPadding: ".",
BarStart: "[",
BarEnd: "]",
}
// ThemeUnicode is a predefined Theme that uses Unicode characters, displaying a graphic bar.
// It looks like "" (rendering will depend on font being used).
// It requires special symbols usually found in "nerd fonts" [2], or in Fira Code [1], and other sources.
// Configure it with OptionSetTheme(ThemeUnicode).
//
// [1] https://github.com/tonsky/FiraCode
// [2] https://www.nerdfonts.com/
ThemeUnicode = Theme{
Saucer: "\uEE04", //
SaucerHead: "\uEE04", //
SaucerPadding: "\uEE01", //
BarStart: "\uEE00", //
BarStartFilled: "\uEE03", //
BarEnd: "\uEE02", //
BarEndFilled: "\uEE05", //
}
)
// Option is the type all options need to adhere to
type Option func(p *ProgressBar)
// OptionSetWidth sets the width of the bar
func OptionSetWidth(s int) Option {
return func(p *ProgressBar) {
p.config.width = s
}
}
// OptionSetSpinnerChangeInterval sets the spinner change interval
// the spinner will change according to this value.
// By default, this value is 100 * time.Millisecond
// If you don't want to let this progressbar update by specified time interval
// you can set this value to zero, then the spinner will change each time rendered,
// such as when Add() or Describe() was called
func OptionSetSpinnerChangeInterval(interval time.Duration) Option {
return func(p *ProgressBar) {
p.config.spinnerChangeInterval = interval
}
}
// OptionSpinnerType sets the type of spinner used for indeterminate bars
func OptionSpinnerType(spinnerType int) Option {
return func(p *ProgressBar) {
p.config.spinnerTypeOptionUsed = true
p.config.spinnerType = spinnerType
}
}
// OptionSpinnerCustom sets the spinner used for indeterminate bars to the passed
// slice of string
func OptionSpinnerCustom(spinner []string) Option {
return func(p *ProgressBar) {
p.config.spinner = spinner
}
}
// OptionSetTheme sets the elements the bar is constructed with.
// There are two pre-defined themes you can use: ThemeASCII and ThemeUnicode.
func OptionSetTheme(t Theme) Option {
return func(p *ProgressBar) {
p.config.theme = t
}
}
// OptionSetVisibility sets the visibility
func OptionSetVisibility(visibility bool) Option {
return func(p *ProgressBar) {
p.config.invisible = !visibility
}
}
// OptionFullWidth sets the bar to be full width
func OptionFullWidth() Option {
return func(p *ProgressBar) {
p.config.fullWidth = true
}
}
// OptionSetWriter sets the output writer (defaults to os.StdOut)
func OptionSetWriter(w io.Writer) Option {
return func(p *ProgressBar) {
p.config.writer = w
}
}
// OptionSetRenderBlankState sets whether or not to render a 0% bar on construction
func OptionSetRenderBlankState(r bool) Option {
return func(p *ProgressBar) {
p.config.renderWithBlankState = r
}
}
// OptionSetDescription sets the description of the bar to render in front of it
func OptionSetDescription(description string) Option {
return func(p *ProgressBar) {
p.config.description = description
}
}
// OptionEnableColorCodes enables or disables support for color codes
// using mitchellh/colorstring
func OptionEnableColorCodes(colorCodes bool) Option {
return func(p *ProgressBar) {
p.config.colorCodes = colorCodes
}
}
// OptionSetElapsedTime will enable elapsed time. Always enabled if OptionSetPredictTime is true.
func OptionSetElapsedTime(elapsedTime bool) Option {
return func(p *ProgressBar) {
p.config.elapsedTime = elapsedTime
}
}
// OptionSetPredictTime will also attempt to predict the time remaining.
func OptionSetPredictTime(predictTime bool) Option {
return func(p *ProgressBar) {
p.config.predictTime = predictTime
}
}
// OptionShowCount will also print current count out of total
func OptionShowCount() Option {
return func(p *ProgressBar) {
p.config.showIterationsCount = true
}
}
// OptionShowIts will also print the iterations/second
func OptionShowIts() Option {
return func(p *ProgressBar) {
p.config.showIterationsPerSecond = true
}
}
// OptionShowElapsedTimeOnFinish will keep the display of elapsed time on finish.
func OptionShowElapsedTimeOnFinish() Option {
return func(p *ProgressBar) {
p.config.showElapsedTimeOnFinish = true
}
}
// OptionShowTotalBytes will keep the display of total bytes.
func OptionShowTotalBytes(flag bool) Option {
return func(p *ProgressBar) {
p.config.showTotalBytes = flag
}
}
// OptionSetItsString sets what's displayed for iterations a second. The default is "it" which would display: "it/s"
func OptionSetItsString(iterationString string) Option {
return func(p *ProgressBar) {
p.config.iterationString = iterationString
}
}
// OptionThrottle will wait the specified duration before updating again. The default
// duration is 0 seconds.
func OptionThrottle(duration time.Duration) Option {
return func(p *ProgressBar) {
p.config.throttleDuration = duration
}
}
// OptionClearOnFinish will clear the bar once its finished.
func OptionClearOnFinish() Option {
return func(p *ProgressBar) {
p.config.clearOnFinish = true
}
}
// OptionOnCompletion will invoke cmpl function once its finished
func OptionOnCompletion(cmpl func()) Option {
return func(p *ProgressBar) {
p.config.onCompletion = cmpl
}
}
// OptionShowBytes will update the progress bar
// configuration settings to display/hide kBytes/Sec
func OptionShowBytes(val bool) Option {
return func(p *ProgressBar) {
p.config.showBytes = val
}
}
// OptionUseANSICodes will use more optimized terminal i/o.
//
// Only useful in environments with support for ANSI escape sequences.
func OptionUseANSICodes(val bool) Option {
return func(p *ProgressBar) {
p.config.useANSICodes = val
}
}
// OptionUseIECUnits will enable IEC units (e.g. MiB) instead of the default
// SI units (e.g. MB).
func OptionUseIECUnits(val bool) Option {
return func(p *ProgressBar) {
p.config.useIECUnits = val
}
}
// OptionShowDescriptionAtLineEnd defines whether description should be written at line end instead of line start
func OptionShowDescriptionAtLineEnd() Option {
return func(p *ProgressBar) {
p.config.showDescriptionAtLineEnd = true
}
}
// OptionSetMaxDetailRow sets the max row of details
// the row count should be less than the terminal height, otherwise it will not give you the output you want
func OptionSetMaxDetailRow(row int) Option {
return func(p *ProgressBar) {
p.config.maxDetailRow = row
}
}
// NewOptions constructs a new instance of ProgressBar, with any options you specify
func NewOptions(max int, options ...Option) *ProgressBar {
return NewOptions64(int64(max), options...)
}
// NewOptions64 constructs a new instance of ProgressBar, with any options you specify
func NewOptions64(max int64, options ...Option) *ProgressBar {
b := ProgressBar{
state: state{
startTime: time.Time{},
lastShown: time.Time{},
counterTime: time.Time{},
},
config: config{
writer: os.Stdout,
theme: ThemeDefault,
iterationString: "it",
width: 40,
max: max,
throttleDuration: 0 * time.Nanosecond,
elapsedTime: max == -1,
predictTime: true,
spinnerType: 9,
invisible: false,
spinnerChangeInterval: 100 * time.Millisecond,
showTotalBytes: true,
},
}
for _, o := range options {
o(&b)
}
if b.config.spinnerType < 0 || b.config.spinnerType > 75 {
panic("invalid spinner type, must be between 0 and 75")
}
if b.config.maxDetailRow < 0 {
panic("invalid max detail row, must be greater than 0")
}
// ignoreLength if max bytes not known
if b.config.max == -1 {
b.lengthUnknown()
}
b.config.maxHumanized, b.config.maxHumanizedSuffix = humanizeBytes(float64(b.config.max),
b.config.useIECUnits)
if b.config.renderWithBlankState {
b.RenderBlank()
}
// if the render time interval attribute is set
if b.config.spinnerChangeInterval != 0 && !b.config.invisible && b.config.ignoreLength {
go func() {
ticker := time.NewTicker(b.config.spinnerChangeInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if b.IsFinished() {
return
}
if b.IsStarted() {
b.lock.Lock()
b.render()
b.lock.Unlock()
}
}
}
}()
}
return &b
}
func getBasicState() state {
now := time.Now()
return state{
startTime: now,
lastShown: now,
counterTime: now,
}
}
// New returns a new ProgressBar
// with the specified maximum
func New(max int) *ProgressBar {
return NewOptions(max)
}
// DefaultBytes provides a progressbar to measure byte
// throughput with recommended defaults.
// Set maxBytes to -1 to use as a spinner.
func DefaultBytes(maxBytes int64, description ...string) *ProgressBar {
desc := ""
if len(description) > 0 {
desc = description[0]
}
return NewOptions64(
maxBytes,
OptionSetDescription(desc),
OptionSetWriter(os.Stderr),
OptionShowBytes(true),
OptionShowTotalBytes(true),
OptionSetWidth(10),
OptionThrottle(65*time.Millisecond),
OptionShowCount(),
OptionOnCompletion(func() {
fmt.Fprint(os.Stderr, "\n")
}),
OptionSpinnerType(14),
OptionFullWidth(),
OptionSetRenderBlankState(true),
)
}
// DefaultBytesSilent is the same as DefaultBytes, but does not output anywhere.
// String() can be used to get the output instead.
func DefaultBytesSilent(maxBytes int64, description ...string) *ProgressBar {
// Mostly the same bar as DefaultBytes
desc := ""
if len(description) > 0 {
desc = description[0]
}
return NewOptions64(
maxBytes,
OptionSetDescription(desc),
OptionSetWriter(io.Discard),
OptionShowBytes(true),
OptionShowTotalBytes(true),
OptionSetWidth(10),
OptionThrottle(65*time.Millisecond),
OptionShowCount(),
OptionSpinnerType(14),
OptionFullWidth(),
)
}
// Default provides a progressbar with recommended defaults.
// Set max to -1 to use as a spinner.
func Default(max int64, description ...string) *ProgressBar {
desc := ""
if len(description) > 0 {
desc = description[0]
}
return NewOptions64(
max,
OptionSetDescription(desc),
OptionSetWriter(os.Stderr),
OptionSetWidth(10),
OptionShowTotalBytes(true),
OptionThrottle(65*time.Millisecond),
OptionShowCount(),
OptionShowIts(),
OptionOnCompletion(func() {
fmt.Fprint(os.Stderr, "\n")
}),
OptionSpinnerType(14),
OptionFullWidth(),
OptionSetRenderBlankState(true),
)
}
// DefaultSilent is the same as Default, but does not output anywhere.
// String() can be used to get the output instead.
func DefaultSilent(max int64, description ...string) *ProgressBar {
// Mostly the same bar as Default
desc := ""
if len(description) > 0 {
desc = description[0]
}
return NewOptions64(
max,
OptionSetDescription(desc),
OptionSetWriter(io.Discard),
OptionSetWidth(10),
OptionShowTotalBytes(true),
OptionThrottle(65*time.Millisecond),
OptionShowCount(),
OptionShowIts(),
OptionSpinnerType(14),
OptionFullWidth(),
)
}
// String returns the current rendered version of the progress bar.
// It will never return an empty string while the progress bar is running.
func (p *ProgressBar) String() string {
return p.state.rendered
}
// RenderBlank renders the current bar state, you can use this to render a 0% state
func (p *ProgressBar) RenderBlank() error {
p.lock.Lock()
defer p.lock.Unlock()
if p.config.invisible {
return nil
}
if p.state.currentNum == 0 {
p.state.lastShown = time.Time{}
}
return p.render()
}
// StartWithoutRender will start the progress bar without rendering it
// this method is created for the use case where you want to start the progress
// but don't want to render it immediately.
// If you want to start the progress and render it immediately, use RenderBlank instead,
// or maybe you can use Add to start it automatically, but it will make the time calculation less precise.
func (p *ProgressBar) StartWithoutRender() {
p.lock.Lock()
defer p.lock.Unlock()
if p.IsStarted() {
return
}
p.state.startTime = time.Now()
// the counterTime should be set to the current time
p.state.counterTime = time.Now()
}
// Reset will reset the clock that is used
// to calculate current time and the time left.
func (p *ProgressBar) Reset() {
p.lock.Lock()
defer p.lock.Unlock()
p.state = getBasicState()
}
// Finish will fill the bar to full
func (p *ProgressBar) Finish() error {
p.lock.Lock()
p.state.currentNum = p.config.max
if !p.config.ignoreLength {
p.state.currentBytes = float64(p.config.max)
}
p.lock.Unlock()
return p.Add(0)
}
// Exit will exit the bar to keep current state
func (p *ProgressBar) Exit() error {
p.lock.Lock()
defer p.lock.Unlock()
p.state.exit = true
if p.config.onCompletion != nil {
p.config.onCompletion()
}
return nil
}
// Add will add the specified amount to the progressbar
func (p *ProgressBar) Add(num int) error {
return p.Add64(int64(num))
}
// Set will set the bar to a current number
func (p *ProgressBar) Set(num int) error {
return p.Set64(int64(num))
}
// Set64 will set the bar to a current number
func (p *ProgressBar) Set64(num int64) error {
p.lock.Lock()
toAdd := num - int64(p.state.currentBytes)
p.lock.Unlock()
return p.Add64(toAdd)
}
// Add64 will add the specified amount to the progressbar
func (p *ProgressBar) Add64(num int64) error {
if p.config.invisible {
return nil
}
p.lock.Lock()
defer p.lock.Unlock()
if p.state.exit {
return nil
}
// error out since OptionSpinnerCustom will always override a manually set spinnerType
if p.config.spinnerTypeOptionUsed && len(p.config.spinner) > 0 {
return errors.New("OptionSpinnerType and OptionSpinnerCustom cannot be used together")
}
if p.config.max == 0 {
return errors.New("max must be greater than 0")
}
if p.state.currentNum < p.config.max {
if p.config.ignoreLength {
p.state.currentNum = (p.state.currentNum + num) % p.config.max
} else {
p.state.currentNum += num
}
}
p.state.currentBytes += float64(num)
if p.state.counterTime.IsZero() {
p.state.counterTime = time.Now()
}
// reset the countdown timer every second to take rolling average
p.state.counterNumSinceLast += num
if time.Since(p.state.counterTime).Seconds() > 0.5 {
p.state.counterLastTenRates = append(p.state.counterLastTenRates, float64(p.state.counterNumSinceLast)/time.Since(p.state.counterTime).Seconds())
if len(p.state.counterLastTenRates) > 10 {
p.state.counterLastTenRates = p.state.counterLastTenRates[1:]
}
p.state.counterTime = time.Now()
p.state.counterNumSinceLast = 0
}
percent := float64(p.state.currentNum) / float64(p.config.max)
p.state.currentSaucerSize = int(percent * float64(p.config.width))
p.state.currentPercent = int(percent * 100)
updateBar := p.state.currentPercent != p.state.lastPercent && p.state.currentPercent > 0
p.state.lastPercent = p.state.currentPercent
if p.state.currentNum > p.config.max {
return errors.New("current number exceeds max")
}
// always update if show bytes/second or its/second
if updateBar || p.config.showIterationsPerSecond || p.config.showIterationsCount {
return p.render()
}
return nil
}
// AddDetail adds a detail to the progress bar. Only used when maxDetailRow is set to a value greater than 0
func (p *ProgressBar) AddDetail(detail string) error {
if p.config.maxDetailRow == 0 {
return errors.New("maxDetailRow is set to 0, cannot add detail")
}
if p.IsFinished() {
return errors.New("cannot add detail to a finished progress bar")
}
p.lock.Lock()
defer p.lock.Unlock()
if p.state.details == nil {
// if we add a detail before the first add, it will be weird that we have detail but don't have the progress bar in the top.
// so when we add the first detail, we will render the progress bar first.
if err := p.render(); err != nil {
return err
}
}
p.state.details = append(p.state.details, detail)
if len(p.state.details) > p.config.maxDetailRow {
p.state.details = p.state.details[1:]
}
if err := p.renderDetails(); err != nil {
return err
}
return nil
}
// renderDetails renders the details of the progress bar
func (p *ProgressBar) renderDetails() error {
if p.config.invisible {
return nil
}
if p.state.finished {
return nil
}
if p.config.maxDetailRow == 0 {
return nil
}
b := strings.Builder{}
b.WriteString("\n")
// render the details row
for _, detail := range p.state.details {
b.WriteString(fmt.Sprintf("\u001B[K\r%s\n", detail))
}
// add empty lines to fill the maxDetailRow
for i := len(p.state.details); i < p.config.maxDetailRow; i++ {
b.WriteString("\u001B[K\n")
}
// move the cursor up to the start of the details row
b.WriteString(fmt.Sprintf("\u001B[%dF", p.config.maxDetailRow+1))
writeString(p.config, b.String())
return nil
}
// Clear erases the progress bar from the current line
func (p *ProgressBar) Clear() error {
return clearProgressBar(p.config, p.state)
}
// Describe will change the description shown before the progress, which
// can be changed on the fly (as for a slow running process).
func (p *ProgressBar) Describe(description string) {
p.lock.Lock()
defer p.lock.Unlock()
p.config.description = description
if p.config.invisible {
return
}
p.render()
}
// New64 returns a new ProgressBar
// with the specified maximum
func New64(max int64) *ProgressBar {
return NewOptions64(max)
}
// GetMax returns the max of a bar
func (p *ProgressBar) GetMax() int {
p.lock.Lock()
defer p.lock.Unlock()
return int(p.config.max)
}
// GetMax64 returns the current max
func (p *ProgressBar) GetMax64() int64 {
p.lock.Lock()
defer p.lock.Unlock()
return p.config.max
}
// ChangeMax takes in a int
// and changes the max value
// of the progress bar
func (p *ProgressBar) ChangeMax(newMax int) {
p.ChangeMax64(int64(newMax))
}
// ChangeMax64 is basically
// the same as ChangeMax,
// but takes in a int64
// to avoid casting
func (p *ProgressBar) ChangeMax64(newMax int64) {
p.lock.Lock()
p.config.max = newMax
if p.config.showBytes {
p.config.maxHumanized, p.config.maxHumanizedSuffix = humanizeBytes(float64(p.config.max),
p.config.useIECUnits)
}
if newMax == -1 {
p.lengthUnknown()
} else {
p.lengthKnown(newMax)
}
p.lock.Unlock() // so p.Add can lock
p.Add(0) // re-render
}
// AddMax takes in a int
// and adds it to the max
// value of the progress bar
func (p *ProgressBar) AddMax(added int) {
p.AddMax64(int64(added))
}
// AddMax64 is basically
// the same as AddMax,
// but takes in a int64
// to avoid casting
func (p *ProgressBar) AddMax64(added int64) {
p.lock.Lock()
p.config.max += added
if p.config.showBytes {
p.config.maxHumanized, p.config.maxHumanizedSuffix = humanizeBytes(float64(p.config.max),
p.config.useIECUnits)
}
if p.config.max == -1 {
p.lengthUnknown()
} else {
p.lengthKnown(p.config.max)
}
p.lock.Unlock() // so p.Add can lock
p.Add(0) // re-render
}
// IsFinished returns true if progress bar is completed
func (p *ProgressBar) IsFinished() bool {
p.lock.Lock()
defer p.lock.Unlock()
return p.state.finished
}
// IsStarted returns true if progress bar is started
func (p *ProgressBar) IsStarted() bool {
return !p.state.startTime.IsZero()
}
// render renders the progress bar, updating the maximum
// rendered line width. this function is not thread-safe,
// so it must be called with an acquired lock.
func (p *ProgressBar) render() error {
// make sure that the rendering is not happening too quickly
// but always show if the currentNum reaches the max
if !p.IsStarted() {
p.state.startTime = time.Now()
} else if time.Since(p.state.lastShown).Nanoseconds() < p.config.throttleDuration.Nanoseconds() &&
p.state.currentNum < p.config.max {
return nil
}
if !p.config.useANSICodes {
// first, clear the existing progress bar, if not yet finished.
if !p.state.finished {
err := clearProgressBar(p.config, p.state)
if err != nil {
return err
}
}
}
// check if the progress bar is finished
if !p.state.finished && p.state.currentNum >= p.config.max {
p.state.finished = true
if !p.config.clearOnFinish {
io.Copy(p.config.writer, &p.config.stdBuffer)
renderProgressBar(p.config, &p.state)
}
if p.config.maxDetailRow > 0 {
p.renderDetails()
// put the cursor back to the last line of the details
writeString(p.config, fmt.Sprintf("\u001B[%dB\r\u001B[%dC", p.config.maxDetailRow, len(p.state.details[len(p.state.details)-1])))
}
if p.config.onCompletion != nil {
p.config.onCompletion()
}
}
if p.state.finished {
// when using ANSI codes we don't pre-clean the current line
if p.config.useANSICodes && p.config.clearOnFinish {
err := clearProgressBar(p.config, p.state)
if err != nil {
return err
}
}
return nil
}
// then, re-render the current progress bar
io.Copy(p.config.writer, &p.config.stdBuffer)
w, err := renderProgressBar(p.config, &p.state)
if err != nil {
return err
}
if w > p.state.maxLineWidth {
p.state.maxLineWidth = w
}
p.state.lastShown = time.Now()
return nil
}
// lengthUnknown sets the progress bar to ignore the length
func (p *ProgressBar) lengthUnknown() {
p.config.ignoreLength = true
p.config.max = int64(p.config.width)
p.config.predictTime = false
}
// lengthKnown sets the progress bar to do not ignore the length
func (p *ProgressBar) lengthKnown(max int64) {
p.config.ignoreLength = false
p.config.max = max
p.config.predictTime = true
}
// State returns the current state
func (p *ProgressBar) State() State {
p.lock.Lock()
defer p.lock.Unlock()
s := State{}
s.CurrentNum = p.state.currentNum
s.Max = p.config.max
if p.config.ignoreLength {
s.Max = -1
}
s.CurrentPercent = float64(p.state.currentNum) / float64(p.config.max)
s.CurrentBytes = p.state.currentBytes