summaryrefslogtreecommitdiff
path: root/tui/progressbar.go
blob: 73a0c6a40c0e650825fb8cf4c7184ba5db68b190 (plain)
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
package tui

import (
	"fmt"
	"strings"
	"time"
)

type ProgressBar struct {
	title string
	width int
	steps int
	n     int
	start time.Time
}

func NewProgressBar(title string, width, steps int, start time.Time) *ProgressBar {
	pb := &ProgressBar{
		title: title,
		width: width,
		steps: steps,
		start: start,
	}

	pb.Print()

	return pb
}

func (p *ProgressBar) Increment() {
	p.n++
}

func (p *ProgressBar) Update(steps int) {
	p.n = steps
}

func (p *ProgressBar) Print() {
	fmt.Print(p.String())
}

func (p *ProgressBar) Finish() {
	fmt.Println()
}

func (p *ProgressBar) String() string {
	progress := int(float64(p.n) / float64(p.steps) * float64(p.width))
	percentage := int(float64(p.n) / float64(p.steps) * 100)

	lap := time.Since(p.start)

	duration := fmt.Sprintf("%02d:%02d:%02d", int(lap.Hours()), int(lap.Minutes())%60, int(lap.Seconds())%60)

	return fmt.Sprintf(
		"\r[%s] %-20s %3d%% [%s%s] %d/%d",
		duration,
		p.title,
		percentage,
		strings.Repeat("=", min(progress, p.width)),
		strings.Repeat("-", max(0, p.width-progress)),
		p.n,
		p.steps,
	)
}