/
printer.go
80 lines (69 loc) · 1.75 KB
/
printer.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
package printer
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/ts"
)
// Table is the table to print.
type Table struct {
Header []string // Column titles
Body [][]string // Rows data
}
// Empty checks if the table is empty.
func (t Table) Empty() bool {
return len(t.Body) == 0
}
// Print prints the table to stdout.
// It pipes to less (or more for windows) if
// height of table is higher than terminal's.
func Print(table Table) error {
var buf bytes.Buffer
Fprint(&buf, table)
// attempt to get terminal size
size, err := ts.GetSize()
// if table height is less than terminal height,
// print normally.
if err != nil || len(table.Body) < size.Row()-2 {
_, err := buf.WriteTo(os.Stdout)
return err
}
// otherwise pipe to less (or more for windows).
command := "less"
if runtime.GOOS == "windows" {
command = "more"
}
// if less (or more) is not found, print normally.
if _, err := exec.LookPath(command); err != nil {
_, err := buf.WriteTo(os.Stdout)
return err
}
cmd := exec.Command(command)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = &buf
return cmd.Run()
}
// Fprint prints the table to a writer.
func Fprint(w io.Writer, table Table) error {
if _, err := fmt.Fprintln(w); err != nil {
return err
}
tWriter := tablewriter.NewWriter(w)
tWriter.SetHeader(table.Header)
tWriter.SetHeaderLine(false)
tWriter.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false})
tWriter.SetCenterSeparator(" ")
tWriter.SetColumnSeparator(" ")
tWriter.SetAlignment(tablewriter.ALIGN_LEFT)
tWriter.AppendBulk(table.Body) // Add Bulk Data
tWriter.Render()
if _, err := fmt.Fprintln(w); err != nil {
return err
}
return nil
}