forked from sandia-minimega/minimega
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pager.go
80 lines (63 loc) · 1.35 KB
/
pager.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
// Copyright (2015) Sandia Corporation.
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
package minipager
import (
"fmt"
log "minilog"
"os"
"os/exec"
"strings"
"syscall"
"unsafe"
)
type Pager interface {
Page(output string)
}
// Copy of winsize struct defined by iotctl.h
type winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
var DefaultPager Pager = &defaultPager{}
type defaultPager struct{}
func (_ defaultPager) Page(output string) {
if output == "" {
return
}
size := termSize()
if size == nil {
fmt.Println(output)
return
}
lines := strings.Count(output, "\n")
if lines < 2*int(size.Row) {
fmt.Println(output)
return
}
fmt.Printf("-- sending %v lines to $PAGER --\n", lines)
pager := os.Getenv("PAGER")
if pager == "" {
pager = "less"
}
cmd := exec.Command(pager)
cmd.Stdin = strings.NewReader(output)
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
log.Error("problem paging: %s", err)
}
}
func termSize() *winsize {
ws := &winsize{}
res, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdout),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws)))
if int(res) == -1 {
log.Error("unable to determine terminal size (errno: %d)", errno)
return nil
}
return ws
}