-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabular.go
103 lines (84 loc) · 2.12 KB
/
tabular.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
package goneo
import (
"bytes"
"fmt"
"text/tabwriter"
"github.com/BuJo/goneo/log"
)
// TabularData describes information in a tabular format.
type TabularData struct {
line []map[string]interface{}
}
func (t *TabularData) String() string {
if len(t.line) == 0 {
return ""
}
b := new(bytes.Buffer)
w := new(tabwriter.Writer)
// Format in tab-separated columns with a tab stop of 8.
w.Init(b, 0, 8, 0, '\t', 0)
headers := make([]string, 0)
for header := range t.line[0] {
headers = append(headers, header)
}
for _, header := range headers {
fmt.Fprint(w, header+"\t")
}
fmt.Fprintln(w, "")
for _, line := range t.line {
for _, header := range headers {
if _, ok := line[header]; ok && line[header] != nil {
fmt.Fprintf(w, "%s\t", line[header])
}
}
fmt.Fprintln(w, "")
}
w.Flush()
return b.String()
}
// Len returns the count of lines
func (t *TabularData) Len() int {
return len(t.line)
}
// Columns returns column names
func (t *TabularData) Columns() []string {
cols := make([]string, 0)
for k := range t.line[0] {
cols = append(cols, k)
}
return cols
}
// Get returns a single field
func (t *TabularData) Get(row int, column string) interface{} {
return t.line[row][column]
}
// BUG(Jo): TabularData does not handle tables of different sizes.
// Merge two tables.
func (t *TabularData) Merge(t2 *TabularData) *TabularData {
merged := new(TabularData)
if t.Len() > 0 && t.Len() != t2.Len() {
// TODO: product? unsure how to handle...
log.Println("TODO: ignored differently sized tables: ", t.Len(), t2.Len())
} else if t.Len() == 0 {
merged.line = make([]map[string]interface{}, t2.Len())
for i := 0; i < t2.Len(); i += 1 {
merged.line[i] = make(map[string]interface{})
for k, v := range t2.line[i] {
merged.line[i][k] = v
}
}
} else {
merged.line = make([]map[string]interface{}, t2.Len())
for i := 0; i < t2.Len(); i += 1 {
merged.line[i] = make(map[string]interface{})
for k, v := range t.line[i] {
merged.line[i][k] = v
}
for k, v := range t2.line[i] {
merged.line[i][k] = v
}
}
}
//log.Print("merged tables: ", merged)
return merged
}