-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbar.go
282 lines (235 loc) · 5.49 KB
/
pbar.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package pbar
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/term"
)
const (
TTY = "/dev/tty" // Microsoft Windows is not supported
BarLengthDefault = 50
RefreshIntervalDefault = 500 * time.Millisecond
BarLeftDefault = '['
BarRightDefault = ']'
BarUnCompletedDefault = ' '
BarCompletedDefault = '='
)
type PBar struct {
barVisual []rune
barPercent string
currentCount uint64
TargetCount uint64
output io.Writer
terminal *term.Term
cursorPosition CursorPosition
mutex sync.Mutex
refreshInterval time.Duration
barLength int
barLeft rune
barRight rune
barUncompleted rune
barCompleted rune
barLabel string
testing bool
tty string
}
type CursorPosition struct {
row int8
col int8
}
func NewPBar(targetCount uint64, options ...Option) *PBar {
return new(PBar).configure(targetCount, options)
}
// [locks mutex]
func (this *PBar) configure(targetCount uint64, options []Option) *PBar {
this.mutex.Lock()
defer this.mutex.Unlock()
this.TargetCount = targetCount
this.output = os.Stdout
this.barLength = BarLengthDefault
this.refreshInterval = RefreshIntervalDefault
this.barLeft = BarLeftDefault
this.barRight = BarRightDefault
this.barUncompleted = BarUnCompletedDefault
this.barCompleted = BarCompletedDefault
this.tty = TTY
for _, configure := range options {
configure(this)
}
return this
}
func (this *PBar) Start() {
var waiter sync.WaitGroup
waiter.Add(1)
go this.start(&waiter)
waiter.Wait()
}
// [locks mutex]
func (this *PBar) start(waiter *sync.WaitGroup) {
this.saveCursorPosition()
this.initializeBar()
waiter.Done()
for {
this.updateBar()
this.repaint()
this.mutex.Lock()
done := this.currentCount == this.TargetCount
this.mutex.Unlock()
if done {
break
}
time.Sleep(this.refreshInterval)
}
}
// [locks mutex]
func (this *PBar) Finish() {
this.mutex.Lock()
this.currentCount = this.TargetCount
this.mutex.Unlock()
time.Sleep(this.refreshInterval)
this.updateBar()
this.repaint()
}
// [locks mutex]
func (this *PBar) Update(current uint64) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.currentCount = current
}
// [locks mutex]
func (this *PBar) updateBar() {
this.mutex.Lock()
defer this.mutex.Unlock()
percentCompleted := float32(this.currentCount) / float32(this.TargetCount)
completed := int(percentCompleted * float32(this.barLength))
for i := 1; i <= this.barLength; i++ {
if i <= completed {
this.barVisual[i] = this.barCompleted
} else {
this.barVisual[i] = this.barUncompleted
}
}
this.barPercent = fmt.Sprintf("(%s/%s) %d%%",
comma(this.currentCount), comma(this.TargetCount), int(percentCompleted*100.0))
}
// [locks mutex]
func (this *PBar) repaint() {
this.restoreCursorPosition()
this.mutex.Lock()
// go to beginning of the line and print data
_, _ = fmt.Fprintf(this.output, "%c%s%s %s%c", 13, this.barLabel, string(this.barVisual), this.barPercent, 32)
this.mutex.Unlock()
}
// [locks mutex]
func (this *PBar) openTty() (err error) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.terminal, err = term.Open(this.tty)
if err != nil {
this.testing = true // prevent attempts to save and restore cursor position
this.output = io.Discard
return
}
_ = term.RawMode(this.terminal)
return
}
// [locks mutex]
func (this *PBar) closeTty() {
this.mutex.Lock()
defer this.mutex.Unlock()
_ = this.terminal.Restore()
}
// [locks mutex]
func (this *PBar) saveCursorPosition() {
if this.testing {
return
}
if this.openTty() != nil {
return
}
defer this.closeTty()
this.mutex.Lock()
defer this.mutex.Unlock()
out := make([]byte, 6)
_, _ = this.terminal.Write([]byte{13, 27, '[', '6', 'n'})
_, _ = this.terminal.Read(out)
split := strings.Split(string(out[2:]), ";")
if len(split) > 1 {
this.cursorPosition.row = atoi8(split[0])
this.cursorPosition.col = atoi8(split[1])
}
}
// [locks mutex]
func (this *PBar) restoreCursorPosition() {
if this.testing {
return
}
this.mutex.Lock()
defer this.mutex.Unlock()
if this.cursorPosition.row == 0 && this.cursorPosition.col == 0 {
return
}
fmt.Printf("%c%c%d;%dH", 27, '[', this.cursorPosition.row, this.cursorPosition.col)
}
// CountFileLines count newline characters in a file
func CountFileLines(path string) (count int, err error) {
const lineBreak = '\n'
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer func() { _ = file.Close() }()
buf := make([]byte, bufio.MaxScanTokenSize)
for {
bufferSize, err := file.Read(buf)
if err != nil && err != io.EOF {
return 0, err
}
var buffPosition int
for {
i := bytes.IndexByte(buf[buffPosition:], lineBreak)
if i == -1 || bufferSize == buffPosition {
break
}
buffPosition += i + 1
count++
}
if err == io.EOF {
break
}
}
return count, nil
}
// [locks mutex]
func (this *PBar) initializeBar() {
this.mutex.Lock()
this.barVisual = make([]rune, this.barLength+2) // plus beginning and end markers
this.barVisual[0] = this.barLeft
this.barVisual[this.barLength+1] = this.barRight
this.mutex.Unlock()
this.updateBar()
}
func atoi8(val string) int8 {
strVal, _ := strconv.Atoi(val)
return int8(strVal)
}
func comma(n uint64) string {
in := strconv.FormatUint(n, 10)
out := make([]byte, len(in)+(len(in)-2+int(in[0]/'0'))/3)
for i, j, k := len(in)-1, len(out)-1, 0; ; i, j = i-1, j-1 {
out[j] = in[i]
if i == 0 {
return string(out)
}
if k++; k == 3 {
j, k = j-1, 0
out[j] = ','
}
}
}