-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
168 lines (140 loc) · 2.49 KB
/
reader.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package table
import (
"bufio"
"io"
"strings"
"unicode"
)
type Reader struct {
h Header
s *bufio.Scanner
}
func NewReader(rd io.Reader) *Reader {
s := bufio.NewScanner(rd)
h := ""
for h == "" && s.Scan() {
h = strings.TrimSpace(s.Text())
}
if h == "" {
return &Reader{s: s}
}
return &Reader{
h: parseHeader(tabToSpace(h)),
s: s,
}
}
func (r *Reader) Next() bool {
if r.s.Scan() {
if strings.TrimSpace(r.s.Text()) == "" {
return r.Next()
}
return true
}
return false
}
func (r *Reader) Row() Row {
return parseRow(tabToSpace(r.s.Text()), r.h)
}
func (r *Reader) Header() Header {
return r.h
}
func ReadAll(s string) *Table {
items := strings.Split(tabToSpace(s), "\n")
var rows []string
for _, item := range items {
if strings.TrimSpace(item) != "" {
rows = append(rows, item)
}
}
rl := len(rows)
if rl <= 1 {
t := &Table{Rows: make([]Row, 0)}
if rl == 1 {
t.Header = parseHeader(rows[0])
}
return t
}
table := &Table{
Header: parseHeader(rows[0]),
Rows: make([]Row, 0, rl-1),
}
for _, row := range rows[1:] {
table.Rows = append(table.Rows, parseRow(row, table.Header))
}
return table
}
func parseHeader(h string) Header {
h = strings.TrimSpace(h)
var (
newc bool
space = -1
index int
header = Header{
Text: h,
Cells: []HeaderCell{},
}
)
runes := []rune(h)
for i, ru := range runes {
if i == len(runes)-1 {
header.append(HeaderCell{
Key: string(runes[index:]),
Index: index,
})
continue
}
if unicode.IsSpace(ru) {
if space > 0 {
if newc {
header.append(HeaderCell{
Key: string(runes[index : i-1]),
Index: index,
})
space = -1
newc = false
}
} else {
space++
}
} else {
if !newc && space > 0 {
space = -1
}
switch space {
case -1:
index = i
space = 0
newc = true
default:
space = 0
}
}
}
return header
}
func parseRow(s string, header Header) Row {
cells := header.Cells
if strings.TrimSpace(s) == "" {
row := Row{}
for _, cell := range cells {
row.append(RowCell{Relation: cell.Key})
}
return row
}
row := Row{Text: strings.TrimSpace(s), Cells: make([]RowCell, 0, len(cells))}
for i, h := range cells {
curr := h.Index
next := len(s)
if i+1 != len(cells) {
next = cells[i+1].Index
}
row.append(RowCell{
Relation: h.Key,
Value: strings.TrimSpace(s[curr:next]),
})
}
return row
}
func tabToSpace(s string) string {
return strings.ReplaceAll(s, "\t", " ")
}