forked from grymoire7/cmakebar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmakebar.go
335 lines (293 loc) · 8.72 KB
/
cmakebar.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* cmakebar - a Cmake progress bar
* This code takes output from 'build_technology make' as input on stdin
* and displays a progress bar in the terminal. This is untested with
* general cmake output.
*
* Usage:
*
* build_technology make 2>&1 | cmakebar
* build_technology make 2>&1 | cmakebar --out cmake.log
* build_technology make 2>&1 | cmakebar -o
* cat cmake.log | cmakebar --replay
*
* Todo:
* [ ] Color/style options
* [ ] Test on OSX, cygwin, DOS
* [ ] Stress test with cmake configuration errors, etc.
*
* Author: Tracy Atteberry
* Date: Spring, 2014
*/
package main
import (
"errors"
"flag"
"fmt"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
"bufio"
)
const (
DEFAULT_WIDTH = 20 // it should never come to this
SMOOTHING_FACTOR = 0.7
)
var logFile string
var logOutput, showEst, showHelp, replay, noStyle bool
var ema float64
var prevPercent int
var prevElapsed time.Duration
var speeds [101]float64
var medianSpeed float64
func init() {
flag.BoolVar(&showHelp, "help", false, "show help")
flag.BoolVar(&logOutput, "o", false, "log output to file [default: cmake.log]")
flag.BoolVar(&replay, "replay", false, "add sleep delays for replay")
flag.BoolVar(&replay, "r", false, "add sleep delays for replay (shortcut)")
flag.BoolVar(&showEst, "est", false, "show estimated time remaining")
flag.BoolVar(&showEst, "e", false, "show estimated time remaining (shortcut")
flag.BoolVar(&noStyle, "no-style", false, "turn off colors and bold")
flag.BoolVar(&noStyle, "ns", false, "turn off colors/bold (shortcut)")
flag.StringVar(&logFile, "out", "", "log to file name")
}
func main() {
var f *os.File
var err error
flag.Parse()
// Bail if nothing on stdin or help is aked for.
if !showHelp && !DescriptorInUse(syscall.Stdin) {
showHelp = true
}
if showHelp {
fmt.Println(`
Cmakebar - a terminal progress bar for cmake
Cmakebar creates a command line progress bar given cmake
build output as input on stdin.
build_technology make 2>&1 | cmakebar
build_technology make 2>&1 | cmakebar --out cmake.log
build_technology make 2>&1 | cmakebar -o
cat cmake.log | cmakebar
If nothing is provided on stdin you will see this message.
Options:
`)
flag.PrintDefaults()
fmt.Print("\n")
os.Exit(2)
}
if len(logFile) > 0 {
logOutput = true
}
if logOutput {
if len(logFile) == 0 {
logFile = "cmake.log"
}
f, err = os.Create(logFile)
if err != nil {
os.Stderr.WriteString("Could not create file: "+logFile)
os.Exit(1)
}
defer f.Close()
}
os.Stdout.Write([]byte("\n"))
percentRe := regexp.MustCompile(`^\[[\s]*([\d]+)%\]`)
failedRe := regexp.MustCompile(`^Failed Modules`)
done := false
cols, _ := TerminalWidth()
start := time.Now()
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
if err != nil {
// check if err == io.EOF
break
}
group := percentRe.FindSubmatch([]byte(line))
if len(group) > 0 {
i, err := strconv.Atoi(string(group[1]))
if err == nil {
if replay {
time.Sleep(time.Millisecond * 30)
}
progress(i, 100, cols, time.Since(start))
}
}
if failedRe.MatchString(line) {
fmt.Print("\n\n")
done = true
}
if done {
fmt.Print(line)
}
if logOutput {
_, err := f.WriteString(line)
if err != nil {
os.Stderr.WriteString("Can't write to log file\n")
os.Exit(1)
}
}
}
os.Stdout.Write([]byte("\n"))
elapsed := time.Since(start)
fmt.Printf("Elpased time: %v\n\n", elapsed)
f.Sync()
}
func Bold(str string) string {
if (noStyle) {
return str
}
return "\033[1m" + str + "\033[0m"
}
func HighlightDone(repeat int) string {
if (noStyle) {
return strings.Repeat("=", repeat)
}
return "\033[46;1m" + strings.Repeat(" ", repeat) + "\033[0m"
}
func HighlightTodo(repeat int) string {
if (noStyle) {
return strings.Repeat("-", repeat)
}
return "\033[47;1m" + strings.Repeat(" ", repeat) + "\033[0m"
}
func durationString(d time.Duration) string {
var f string
n := int(d)
ms := n / int(time.Millisecond) % 1000
s := n / int(time.Second) % 60
m := n / int(time.Minute) % 60
h := n / int(time.Hour)
if n > int(time.Hour) {
f = fmt.Sprintf("%dh %.2dm %.2ds %.3dms", h, m, s, ms)
} else if n > int(time.Minute) {
f = fmt.Sprintf("%.2dm %.2ds %.3dms", m, s, ms)
} else if n > int(time.Second) {
f = fmt.Sprintf("%.2ds %.3dms", s, ms)
} else {
f = fmt.Sprintf("%.3dms", ms)
}
return f
}
func calcLinearAverageSpeed(percent int, elapsed time.Duration) float64 {
return float64(percent) / float64(elapsed)
}
// EMA = Exponential Moving Average
// TODO: This is horrible estimate. It's probably better to keep an array
// of 100 m values and return the median. Or at least weight the EMA against
// the moving median.
func calcEMASpeed(percent int, elapsed time.Duration) float64 {
if percent == prevPercent {
return ema
}
// Exponential Moving Average
// m_e = SF * m_t + (1 - SF) * m_e
// SF : smothing factor where 0 < SF < 1
// m_e : exponential moving average
// m_t : current rate of change or speed
mt := float64(percent - prevPercent) / float64(elapsed - prevElapsed)
ema = SMOOTHING_FACTOR * mt + (1 - SMOOTHING_FACTOR) * ema
return ema
}
func calcMedianSpeed(percent int, elapsed time.Duration) float64 {
if percent == prevPercent {
return medianSpeed
}
mt := float64(percent - prevPercent) / float64(elapsed - prevElapsed)
speeds[percent] = mt
// calc median of mt
speedsorted := speeds // copy, don't sort original array
sort.Float64s(speedsorted[:])
for i, v := range speedsorted {
if v > 0 {
medianSpeed = speedsorted[ i + (len(speedsorted) - i) / 2 ]
break;
}
}
return medianSpeed
}
func progress(current, total, cols int, elapsed time.Duration) string {
var line string
percent := int(100.0 * float64(current) / float64(total))
prefix := fmt.Sprintf(" %d%%", percent)
postfix := durationString(elapsed)
bar_start := " ["
bar_end := "] "
// m := calcLinearAverageSpeed(percent, elapsed)
m := calcMedianSpeed(percent, elapsed)
if percent != prevPercent {
prevPercent = percent
prevElapsed = elapsed
}
if showEst {
if percent > 0 {
estRemaining := time.Duration(100.0 / m) - elapsed
if estRemaining > 0 {
postfix = durationString(estRemaining)
} else {
postfix = ""
}
}
}
bar_size := cols - len(prefix + bar_start + bar_end + postfix)
amount := int(float64(current) / (float64(total) / float64(bar_size)))
remain := bar_size - amount
// try to degrade nicely for small cols
if remain < 0 {
if cols > len(prefix) {
line = prefix
}
} else {
bar := HighlightDone(amount) + HighlightTodo(remain)
line = Bold(prefix) + bar_start + bar + bar_end + postfix
}
os.Stdout.Write([]byte(line + "\r"))
os.Stdout.Sync()
return line
}
func DescriptorInUse(fd int) bool {
_, _, err := TerminalSize(fd)
return err != nil
}
func TerminalSize(fd int) (rows, cols int, err error) {
// Dimensions: Row, Col, XPixel, YPixel
var dimensions [4]uint16
const (
TIOCGWINSZ_OSX = 1074295912
)
tio := syscall.TIOCGWINSZ
if runtime.GOOS == "darwin" {
tio = TIOCGWINSZ_OSX
}
r1, _, err := syscall.Syscall(
syscall.SYS_IOCTL,
uintptr(fd),
uintptr(tio),
uintptr(unsafe.Pointer(&dimensions)),
)
// fmt.Println(fd, dimensions)
if int(r1) == -1 {
return -1, -1, errors.New("TerminalSize error")
}
return int(dimensions[0]), int(dimensions[1]), nil
}
func TerminalWidth() (int, error) {
// check all three standard file descriptors
// just to be safely paranoid (did you hear that?)
_, width, err := TerminalSize(syscall.Stdout)
if err != nil {
_, width, err = TerminalSize(syscall.Stdin)
}
if err != nil {
_, width, err = TerminalSize(syscall.Stderr)
}
if err != nil {
return DEFAULT_WIDTH, errors.New("GetWinsize error")
}
return width, err
}