/
dot_progress.go
99 lines (87 loc) · 1.99 KB
/
dot_progress.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
94
95
96
97
98
99
package ui
import (
"fmt"
"sync"
"time"
"github.com/fatih/color"
)
// This file implements the DotProgress form of the Progress
// interface. This encapsulates the new indicator to use.
// It prints a series of dots as time goes by.
type DotProgress struct {
ui *UI
mu *sync.RWMutex //
Delay time.Duration // Delay is the speed of the indicator
active bool // active holds the state of the spinner
stopChan chan struct{} // stopChan is a channel used to stop the indicator
}
// Standard values for the current dot-based progress
const dotTime = 1 * time.Second
func NewDotProgress(ui *UI, message string) *DotProgress {
message = mfinal(message)
p := &DotProgress{
ui: ui,
Delay: dotTime,
mu: &sync.RWMutex{},
active: false,
stopChan: make(chan struct{}, 1),
}
p.ui.ProgressNote().KeepLine().Msg(message)
p.Start()
return p
}
func (p *DotProgress) Start() {
p.mu.Lock()
if p.active {
p.mu.Unlock()
return
}
p.active = true
p.mu.Unlock()
go func() {
for {
select {
case <-p.stopChan:
return
default:
p.mu.Lock()
if !p.active {
p.mu.Unlock()
return
}
p.ui.Normal().
Compact().
KeepLine().
Msg(color.MagentaString("."))
delay := p.Delay
p.mu.Unlock()
time.Sleep(delay)
}
}
}()
}
func (p *DotProgress) Stop() {
p.mu.Lock()
defer p.mu.Unlock()
if p.active {
p.active = false
p.ui.Normal().Compact().Msg("")
p.stopChan <- struct{}{}
}
}
// ChangeMessagef extends the dot-based progress with the ability to
// change the message mid-flight
func (p *DotProgress) ChangeMessagef(message string, a ...interface{}) {
p.ChangeMessage(fmt.Sprintf(message, a...))
}
// ChangeMessage extends the dot-based progress with the ability to
// change the message mid-flight
func (p *DotProgress) ChangeMessage(message string) {
message = mfinal(message)
p.Stop()
p.ui.ProgressNote().KeepLine().Msg(message)
p.Start()
}
func mfinal(message string) string {
return message + " "
}