-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
csv.go
213 lines (189 loc) · 4.77 KB
/
csv.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package storage
import (
"bytes"
"encoding/csv"
"fmt"
"sort"
)
func init() {
registerReadParser([]string{"csv"}, []string{".csv"}, &CSVParser{})
registerWriteParser([]string{"csv"}, []string{".csv"}, &CSVParser{})
}
// CSVParser is a Parser implementation to handle csv files.
type CSVParser struct {
}
// CSVDocument represents a CSV file.
// This is required to keep headers in the expected order.
type CSVDocument struct {
originalRequired
Value []map[string]interface{}
Headers []string
}
// RealValue returns the real value that dasel should use when processing data.
func (d *CSVDocument) RealValue() interface{} {
return d.Value
}
// Documents returns the documents that should be written to output.
func (d *CSVDocument) Documents() []interface{} {
res := make([]interface{}, len(d.Value))
for i := range d.Value {
res[i] = d.Value[i]
}
return res
}
// FromBytes returns some data that is represented by the given bytes.
func (p *CSVParser) FromBytes(byteData []byte) (interface{}, error) {
if byteData == nil {
return nil, fmt.Errorf("could not read csv file: no data")
}
reader := csv.NewReader(bytes.NewBuffer(byteData))
res := make([]map[string]interface{}, 0)
records, err := reader.ReadAll()
if err != nil {
return nil, fmt.Errorf("could not read csv file: %w", err)
}
if len(records) == 0 {
return nil, nil
}
var headers []string
for i, row := range records {
if i == 0 {
headers = row
continue
}
rowRes := make(map[string]interface{})
allEmpty := true
for index, val := range row {
if val != "" {
allEmpty = false
}
rowRes[headers[index]] = val
}
if !allEmpty {
res = append(res, rowRes)
}
}
return &CSVDocument{
Value: res,
Headers: headers,
}, nil
}
func interfaceToCSVDocument(val interface{}) (*CSVDocument, error) {
switch v := val.(type) {
case map[string]interface{}:
headers := make([]string, 0)
for k := range v {
headers = append(headers, k)
}
sort.Strings(headers)
return &CSVDocument{
Value: []map[string]interface{}{v},
Headers: headers,
}, nil
case []interface{}:
mapVals := make([]map[string]interface{}, 0)
headers := make([]string, 0)
for _, val := range v {
if x, ok := val.(map[string]interface{}); ok {
mapVals = append(mapVals, x)
for objectKey := range x {
found := false
for _, existingHeader := range headers {
if existingHeader == objectKey {
found = true
break
}
}
if !found {
headers = append(headers, objectKey)
}
}
}
}
sort.Strings(headers)
return &CSVDocument{
Value: mapVals,
Headers: headers,
}, nil
default:
return nil, fmt.Errorf("CSVParser.toBytes cannot handle type %T", val)
}
}
// ToBytes returns a slice of bytes that represents the given value.
func (p *CSVParser) ToBytes(value interface{}, options ...ReadWriteOption) ([]byte, error) {
buffer := new(bytes.Buffer)
writer := csv.NewWriter(buffer)
// Allow for multi document output by just appending documents on the end of each other.
// This is really only supported so as we have nicer output when converting to CSV from
// other multi-document formats.
docs := make([]*CSVDocument, 0)
switch d := value.(type) {
case *CSVDocument:
docs = append(docs, d)
case SingleDocument:
doc, err := interfaceToCSVDocument(d.Document())
if err != nil {
return nil, err
}
docs = append(docs, doc)
case MultiDocument:
for _, dd := range d.Documents() {
doc, err := interfaceToCSVDocument(dd)
if err != nil {
return nil, err
}
docs = append(docs, doc)
}
default:
return []byte(fmt.Sprintf("%v\n", value)), nil
}
for _, doc := range docs {
if err := p.toBytesHandleDoc(writer, doc); err != nil {
return nil, err
}
}
return append(buffer.Bytes()), nil
}
func (p *CSVParser) toBytesHandleDoc(writer *csv.Writer, doc *CSVDocument) error {
// Iterate through the rows and detect any new headers.
for _, r := range doc.Value {
for k := range r {
headerExists := false
for _, header := range doc.Headers {
if k == header {
headerExists = true
break
}
}
if !headerExists {
doc.Headers = append(doc.Headers, k)
}
}
}
// Iterate through the rows and write the output.
for i, r := range doc.Value {
if i == 0 {
if err := writer.Write(doc.Headers); err != nil {
return fmt.Errorf("could not write headers: %w", err)
}
}
values := make([]string, 0)
for _, header := range doc.Headers {
val, ok := r[header]
if !ok {
val = ""
}
switch val.(type) {
case float32, float64:
values = append(values, fmt.Sprintf("%f", val))
default:
values = append(values, fmt.Sprint(val))
}
}
if err := writer.Write(values); err != nil {
return fmt.Errorf("could not write values: %w", err)
}
writer.Flush()
}
return nil
}