This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
121 lines (95 loc) · 1.86 KB
/
table.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
package main
import (
"fmt"
"os"
"strings"
"time"
)
type Table struct {
Header []string
Rows [][]interface{}
}
func NewTable(header []string) *Table {
return &Table{
Header: header,
Rows: make([][]interface{}, 0),
}
}
func (t *Table) AddRow(row []interface{}) {
t.Rows = append(t.Rows, row)
}
func (t *Table) Write() {
rows := t.Render()
widths := t.ColumnWidths(rows)
for i, label := range t.Header {
if i > 0 {
fmt.Fprintf(os.Stderr, " ")
}
label = fmt.Sprintf("%-*s", widths[i], strings.ToUpper(label))
fmt.Fprintf(os.Stderr, Colorize(ColorYellow, label))
}
fmt.Fprintln(os.Stderr, "")
for _, row := range rows {
for j, s := range row {
if j > 0 {
fmt.Printf(" ")
}
fmt.Printf("%-*s", widths[j], s)
}
fmt.Println("")
}
}
func (t *Table) Render() [][]string {
rows := make([][]string, len(t.Rows))
for i, row := range t.Rows {
rows[i] = make([]string, len(row))
for j, value := range row {
rows[i][j] = t.RenderValue(value)
}
}
return rows
}
func (t *Table) RenderValue(value interface{}) string {
switch v := value.(type) {
case time.Time:
return v.Format(time.RFC3339)
case *time.Time:
if v == nil {
return ""
} else {
return v.Format(time.RFC3339)
}
case *time.Duration:
if v == nil {
return ""
} else {
return FormatDuration(*v)
}
}
return fmt.Sprintf("%v", value)
}
func (t *Table) ColumnWidths(rows [][]string) []int {
widths := make([]int, len(t.Header))
for i, label := range t.Header {
widths[i] = len(label)
}
for _, row := range rows {
for j, value := range row {
if len(value) > widths[j] {
widths[j] = len(value)
}
}
}
return widths
}
func FormatDuration(d time.Duration) string {
s := int(d.Seconds())
if s == 0 {
return ""
}
h := s / 3600
s = s - h*3600
m := s / 60
s = s - m*60
return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
}