~poldi1405/go-indicators

ref: 6d07ab3d9b7db29be0dd32b12f3e53185cf1539d go-indicators/progress/type.go -rw-r--r-- 1.9 KiB
6d07ab3d — Moritz Poldrack added more spinner styles 1 year, 12 days ago
                                                                                
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
package progress

import (
	"math"
	"strings"
	"sync"
)

// Progress contains the settings of a Progressbar.
type Progress struct {
	style string
	Width int

	prgChars    []string
	prgCharsMtx sync.RWMutex
}

// SetStyle sets the style that should be used with the progressbar
func (p *Progress) SetStyle(style string) {
	if style == p.style && style != "" {
		return
	}
	progressStyleMtx.RLock()
	defer progressStyleMtx.RUnlock()

	prgc, exists := ProgressStyles[style]
	if !exists {
		prgc = ProgressStyles[""]
	}

	p.prgCharsMtx.Lock()
	p.prgChars = prgc
	p.prgCharsMtx.Unlock()
	p.style = style
}

// GetBar returns the string that represents the progressbar in the set style
// for the given progress
func (p *Progress) GetBar(parts, total float64) (result string) {
	p.loadStyleIfEmpty()
	if p.Width <= 0 {
		p.Width = 10
	}
	p.prgCharsMtx.RLock()
	defer p.prgCharsMtx.RUnlock()
	maxIndex := len(p.prgChars) - 1
	if total == 0 {
		result += strings.Repeat(p.prgChars[maxIndex], p.Width)
		return
	}

	percperchar := float64(100) / float64(p.Width)
	percent, _ := GetPercentage(parts, total)
	counter := 0

	if percent > 100 {
		percent = float64(100)
	} else if percent < 0 {
		percent = float64(0)
	}

	for percent > percperchar {
		result += p.prgChars[maxIndex]

		percent -= percperchar
		counter++
	}

	if counter == p.Width {
		return
	}

	charindex := 0
	dingeling := percperchar / float64(maxIndex+1)
	temp := math.Floor(percent / dingeling)
	for percent > dingeling {
		percent -= dingeling
		charindex++
	}
	charindex = int(temp)

	if charindex > 0 {
		if charindex > maxIndex {
			charindex = maxIndex
		}
		result += p.prgChars[charindex]
		counter++
	}

	for counter < p.Width {
		result += p.prgChars[0]
		counter++
	}
	return
}

func (p *Progress) loadStyleIfEmpty() {
	p.prgCharsMtx.RLock()
	if len(p.prgChars) > 0 {
		p.prgCharsMtx.RUnlock()
		return
	}
	p.prgCharsMtx.RUnlock()

	p.SetStyle(p.style)
}