-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdin.go
More file actions
79 lines (76 loc) · 1.63 KB
/
stdin.go
File metadata and controls
79 lines (76 loc) · 1.63 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
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
"fortio.org/log"
"fortio.org/terminal"
)
func StdinTail(cfg *Config) int {
maxPoll := 100 * time.Millisecond
reader := terminal.NewTimeoutReader(os.Stdin, maxPoll)
var numStr string
ap := cfg.ap
var buf [4096]byte
ap.Out = bufio.NewWriter(os.Stdout)
defer ap.Out.Flush()
blink := false
var prevNow time.Time
prev := ""
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
for {
select {
case <-c:
log.LogVf("Interrupted, exiting")
return 0
default:
}
doDraw := cfg.breath
now := time.Now()
if cfg.countDown {
left := cfg.end.Sub(now).Round(time.Second)
if left < 0 {
ap.WriteString(fmt.Sprintf("\n\n\aTime's up reached at %s\r\n", now.Format(cfg.format)))
return 0
}
numStr = DurationString(left, cfg.seconds)
} else {
numStr = now.Format(cfg.format)
}
if numStr != prev {
doDraw = true
}
prev = numStr
now = now.Truncate(time.Second) // change only when seconds change
if now != prevNow && cfg.blinkEnabled {
blink = !blink
doDraw = true
}
prevNow = now
n, err := reader.Read(buf[:])
if err != nil {
if !errors.Is(err, io.EOF) {
return log.FErrf("Error reading stdin: %v", err)
}
log.Debugf("EOF on stdin")
time.Sleep(maxPoll) // EOF is continuous until there is more in the file, so avoid too tight loop.
}
if doDraw || n > 0 {
cfg.frame++
ap.StartSyncMode()
if n > 0 {
_, _ = ap.Out.Write(buf[:n])
ap.SaveCursorPos()
}
cfg.DrawAt(-1, -1, TimeString(numStr, blink))
ap.RestoreCursorPos()
ap.EndSyncMode()
}
}
}