-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
chin.go
93 lines (81 loc) · 1.62 KB
/
chin.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
package chin
import (
"fmt"
"os"
"os/exec"
"sync"
"time"
)
// Default set
var Default = Set{50 * time.Millisecond, []string{"+", "\\", "|", "!", "/", "-", "x"}}
// Arrows set
var Arrows = Set{100 * time.Millisecond, []string{"⇢", "⇨", "⇒", "⇉", "⇶"}}
// Dots set
var Dots = Set{100 * time.Millisecond, []string{".", "·", "•", "¤", "°", "¤", "•", "·"}}
// Chin is the spinner struct
type Chin struct {
stch chan bool
stop bool
set Set
wg *sync.WaitGroup
}
// Set defines animation chars and delay
type Set struct {
Delay time.Duration
Chars []string
}
// New gets a new spinner
func New(sets ...Set) *Chin {
sets = append(sets, Default)
return &Chin{stch: make(chan bool), set: sets[0]}
}
// WithWait attaches a wait group
func (s *Chin) WithWait(wg *sync.WaitGroup) *Chin {
wg.Add(1)
s.wg = wg
return s
}
// Start starts the spinner
func (s *Chin) Start() {
if err := tput("civis"); err != nil {
fmt.Print("\033[?25l")
}
s.doSpin()
}
// Stop stops the spinner
func (s *Chin) Stop() {
if s.wg != nil {
defer s.wg.Done()
}
s.stop = true
if err := tput("cvvis"); err != nil {
fmt.Print("\033[?25h")
}
}
func (s *Chin) doSpin() {
for {
outer:
select {
case _, ok := <-s.stch:
if ok {
fmt.Print("\010")
break outer
}
default:
for _, c := range s.set.Chars {
if s.stop {
s.stch <- true
} else if len(c) > 0 {
fmt.Print(c, "\010")
time.Sleep(s.set.Delay)
}
}
}
}
}
// https://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
func tput(arg string) error {
cmd := exec.Command("tput", arg)
cmd.Stdout = os.Stdout
return cmd.Run()
}