-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtable_print.go
111 lines (95 loc) · 2.08 KB
/
table_print.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
package datatable
import (
"fmt"
"io"
"os"
"strings"
"github.com/olekukonko/tablewriter"
)
// PrintOptions to control the printer
type PrintOptions struct {
ColumnName bool
ColumnType bool
RowNumber bool
MaxRows int
}
type PrintOption func(opts *PrintOptions)
func PrintColumnName(v bool) PrintOption {
return func(opts *PrintOptions) {
opts.ColumnName = v
}
}
func PrintColumnType(v bool) PrintOption {
return func(opts *PrintOptions) {
opts.ColumnType = v
}
}
func PrintRowNumber(v bool) PrintOption {
return func(opts *PrintOptions) {
opts.RowNumber = v
}
}
func PrintMaxRows(v int) PrintOption {
return func(opts *PrintOptions) {
opts.MaxRows = v
}
}
// Print the tables with options
func (t *DataTable) Print(writer io.Writer, opt ...PrintOption) {
options := PrintOptions{
ColumnName: true,
ColumnType: true,
RowNumber: true,
MaxRows: 100,
}
for _, o := range opt {
o(&options)
}
if writer == nil {
writer = os.Stdout
}
tw := tablewriter.NewWriter(writer)
tw.SetAutoWrapText(false)
tw.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
tw.SetAlignment(tablewriter.ALIGN_LEFT)
tw.SetCenterSeparator("")
tw.SetColumnSeparator("")
tw.SetRowSeparator("")
tw.SetHeaderLine(false)
tw.SetBorder(false)
tw.SetTablePadding("\t")
tw.SetNoWhiteSpace(true)
if options.ColumnName || options.ColumnType {
headers := make([]string, 0, len(t.cols))
for _, col := range t.cols {
if !col.IsVisible() {
continue
}
var h []string
if options.ColumnName {
h = append(h, col.Name())
}
if options.ColumnType {
h = append(h, fmt.Sprintf("<%s>", col.serie.Type().Name()))
}
headers = append(headers, strings.Join(h, " "))
}
tw.SetHeader(headers)
}
if options.MaxRows > 1 && options.MaxRows <= t.NumRows() {
mr := options.MaxRows / 2
tw.AppendBulk(t.Head(mr).Records())
seps := make([]string, 0, len(t.cols))
for _, col := range t.cols {
if !col.IsVisible() {
continue
}
seps = append(seps, "...")
}
tw.Append(seps)
tw.AppendBulk(t.Tail(mr).Records())
} else {
tw.AppendBulk(t.Records())
}
tw.Render()
}