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
package spinner
import (
"strings"
"sync"
"unicode/utf8"
)
// Spinner contains the settings of a spinner
type Spinner struct {
style string
currentIndex int
spinChars []string
spinCharsMtx sync.RWMutex
}
// Next returns the next character for the spinner
func (s *Spinner) Next() string {
s.loadIfUnloaded()
s.spinCharsMtx.RLock()
s.currentIndex++
if s.currentIndex >= len(s.spinChars) {
s.currentIndex = 0
}
s.spinCharsMtx.RUnlock()
return s.Current()
}
// Current returns the current character for the spinner
func (s *Spinner) Current() string {
s.loadIfUnloaded()
s.spinCharsMtx.RLock()
defer s.spinCharsMtx.RUnlock()
// just in case someone changed the style mid-way
if s.currentIndex >= len(s.spinChars) {
s.currentIndex = 0
}
return SpinnerStyles[s.style][s.currentIndex]
}
// SetStyle loads a style into the spinner
func (s *Spinner) SetStyle(style string) {
if style == s.style && style != "" {
return
}
s.spinCharsMtx.Lock()
defer s.spinCharsMtx.Unlock()
s.style = style
spinnerStyleMtx.RLock()
s.spinChars = SpinnerStyles[s.style]
spinnerStyleMtx.RUnlock()
}
// Clear returns the amount of characters for the first spinner-state in spaces
// in order to clear the spinner if required.
func (s *Spinner) Clear() string {
return strings.Repeat(" ", utf8.RuneCountInString(SpinnerStyles[s.style][0]))
}
// loadIfUnloaded makes sure a style is always loaded.
func (s *Spinner) loadIfUnloaded() {
s.spinCharsMtx.Lock()
if len(s.spinChars) > 0 {
s.spinCharsMtx.Unlock()
return
}
spinnerStyleMtx.RLock()
s.spinChars = SpinnerStyles[""]
s.spinCharsMtx.Unlock()
spinnerStyleMtx.RUnlock()
}