-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspinner.go
More file actions
95 lines (84 loc) · 1.86 KB
/
spinner.go
File metadata and controls
95 lines (84 loc) · 1.86 KB
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
package main
import (
"fmt"
"io"
"os"
"sync/atomic"
"time"
)
const (
ClearLine = "\r\033[K" // ANSI escape sequence
HideCursor = "\033[?25l" // ANSI escape sequence
ShowCursor = "\033[?25h" // ANSI escape sequence
)
// Spinner main type
type Spinner struct {
frames []rune
pos int
active uint64
text string
tpf time.Duration
writer io.Writer
}
// Option describes an option to override a default
// when creating a new Spinner.
type SpinnerOption func(s *Spinner)
// New creates a Spinner object with the provided
// text. By default, the line frames are used, and
// new frames are rendered every 100 milliseconds.
func NewSpinner(text string, opts ...SpinnerOption) *Spinner {
s := &Spinner{
text: ClearLine + text,
frames: []rune(`|/-\`),
tpf: 100 * time.Millisecond,
writer: os.Stdout,
}
for _, o := range opts {
o(s)
}
return s
}
// WithFrames sets the frames string.
func WithFrames(frames string) SpinnerOption {
return func(s *Spinner) {
s.Set(frames)
}
}
// WithWriter sets the io.Writer.
func WithWriter(writer io.Writer) SpinnerOption {
return func(s *Spinner) {
s.writer = writer
}
}
// Set frames to the given string which must not use spaces.
func (s *Spinner) Set(frames string) {
s.frames = []rune(frames)
}
// Start shows the spinner.
func (s *Spinner) Start() *Spinner {
if atomic.LoadUint64(&s.active) > 0 {
return s
}
atomic.StoreUint64(&s.active, 1)
fmt.Fprint(s.writer, HideCursor)
go func() {
for atomic.LoadUint64(&s.active) > 0 {
fmt.Fprintf(s.writer, s.text, s.next())
time.Sleep(s.tpf)
}
}()
return s
}
// Stop hides the spinner.
func (s *Spinner) Stop() bool {
if x := atomic.SwapUint64(&s.active, 0); x > 0 {
fmt.Fprint(s.writer, ClearLine, ShowCursor)
return true
}
return false
}
func (s *Spinner) next() string {
r := s.frames[s.pos%len(s.frames)]
s.pos++
return string(r)
}