-
Notifications
You must be signed in to change notification settings - Fork 1
/
row.go
106 lines (92 loc) · 2.33 KB
/
row.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
package csvd
// Row represents a row in csv file.
type Row struct {
d *Decoder
record []string
rowError *RowError
lastParseError *CellError
}
func (r *Row) check() {
d := r.d
if d == nil {
panic("row without decoder, please get Row from the Decoder")
}
if r.d.header == nil {
panic("row without header, forgot to call ParseHeader()?")
}
}
// Record returns the original data in the row.
func (r *Row) Record() []string {
return r.record
}
func (r *Row) get(key string) (int, string) {
r.check()
idx := r.d.header.Get(key)
var val string
if idx != -1 {
val = r.record[idx]
}
return idx, val
}
// Get gets the value of cell associated with the given key.
// If there are no cell associated with the key, Get returns empty string.
//
// The key is canonicalized by CanonicalHeaderKey.
func (r *Row) Get(key string) string {
_, val := r.get(key)
return val
}
// Has checks if has a cell associated with the given key.
// If there are no cell associated with the key, Has returns false.
//
// The key is canonicalized by CanonicalHeaderKey.
func (r *Row) Has(key string) bool {
r.check()
return r.d.header.Has(key)
}
// LastParseError returns the error that occurred the last time the Parse method was called.
func (r *Row) LastParseError() *CellError {
if r.lastParseError != nil {
return r.lastParseError
}
return nil
}
func (r *Row) addCellError(cellErr *CellError) {
if r.rowError == nil {
r.rowError = &RowError{}
}
r.rowError.Add(cellErr)
}
// Error returns all errors that occurred when Parse was called.
func (r *Row) Error() *RowError {
return r.rowError
}
// Parse gets the value of cell associated with the given key then
// call parse method with that value.
//
// The error returned by the parse method is wrapped as a CellError and
// can be obtained through the LastParseError method.
//
// If you want to get all parse errors, call the Error() method.
func (r *Row) Parse(key string, parse func(val string) error) {
idx, val := r.get(key)
var lastParseError *CellError
err := parse(val)
if err != nil {
line := -1
if idx != -1 {
line, _ = r.d.reader.FieldPos(idx)
idx += 1
}
lastParseError = &CellError{
Key: key,
Val: val,
Row: r.d.rowNumber,
Column: idx,
Line: line,
ParseErr: err,
}
}
r.addCellError(lastParseError)
r.lastParseError = lastParseError
}