-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
csv.go
303 lines (245 loc) · 7.22 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright (c) 2021-2024 Onur Cinar.
// The source code is provided under GNU AGPLv3 License.
// https://github.com/cinar/indicator
package helper
import (
"encoding/csv"
"errors"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"reflect"
"sync"
)
const (
// CsvHeaderTag represents the parameter name for the column header.
CsvHeaderTag = "header"
// CsvFormatTag represents the parameter name for the column format.
CsvFormatTag = "format"
// DefaultDateTimeFormat denotes the default format of a date and time column.
DefaultDateTimeFormat = "2006-01-02 15:04:05"
)
// csvColumn represents the mapping between the CSV column and
// the corresponding struct field.
type csvColumn struct {
Header string
ColumnIndex int
FieldIndex int
Format string
}
// Csv represents the configuration for CSV reader and writer.
type Csv[T any] struct {
// hasHeader indicates whether the CSV contains a header row.
hasHeader bool
// columns are the mappings between the CSV columns and
// the corresponding struct fields.
columns []csvColumn
}
// NewCsv function initializes a new CSV instance. The parameter
// hasHeader indicates whether the CSV contains a header row.
func NewCsv[T any](hasHeader bool) (*Csv[T], error) {
c := &Csv[T]{
hasHeader: hasHeader,
}
// Row type must be a pointer to struct.
structType := reflect.TypeOf((*T)(nil)).Elem()
if structType.Kind() != reflect.Struct {
return nil, errors.New("type not a struct")
}
// Create a mapping linking CSV columns to corresponding struct fields.
c.columns = make([]csvColumn, structType.NumField())
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
header, ok := field.Tag.Lookup(CsvHeaderTag)
if !ok {
header = field.Name
}
format, ok := field.Tag.Lookup(CsvFormatTag)
if !ok {
format = DefaultDateTimeFormat
}
c.columns[i] = csvColumn{
Header: header,
ColumnIndex: i,
FieldIndex: i,
Format: format,
}
}
return c, nil
}
// ReadFromReader parses the CSV data from the provided reader,
// maps the data to corresponding struct fields, and delivers
// the resulting it through the channel.
func (c *Csv[T]) ReadFromReader(reader io.Reader) <-chan *T {
rows := make(chan *T)
go func() {
defer close(rows)
csvReader := csv.NewReader(reader)
// If CSV has headers, align column indices to match the
// order of column headers.
if c.hasHeader {
err := c.updateColumnIndexes(csvReader)
if err != nil {
log.Printf("Update colum index failed with %v", err)
return
}
}
for {
record, err := csvReader.Read()
if err == io.EOF {
break
}
if err != nil {
log.Printf("Read row failed with %v", err)
break
}
row := new(T)
rowValue := reflect.ValueOf(row).Elem()
for _, column := range c.columns {
if column.ColumnIndex == -1 {
continue
}
err := setReflectValue(rowValue.Field(column.FieldIndex),
record[column.ColumnIndex], column.Format)
if err != nil {
log.Printf("set value failed with %v", err)
return
}
}
rows <- row
}
}()
return rows
}
// ReadFromFile parses the CSV data from the provided file name,
// maps the data to corresponding struct fields, and delivers
// the resulting rows through the channel.
func (c *Csv[T]) ReadFromFile(fileName string) (<-chan *T, error) {
file, err := os.Open(filepath.Clean(fileName))
if err != nil {
return nil, err
}
wg := &sync.WaitGroup{}
rows := Waitable[*T](wg, c.ReadFromReader(file))
go func() {
wg.Wait()
err := file.Close()
if err != nil {
log.Printf("file close failed with %v", err)
}
}()
return rows, nil
}
// AppendToFile appends the provided rows of data to the end of the specified file, creating
// the file if it doesn't exist. In append mode, the function assumes that the existing
// file's column order matches the field order of the given row struct to ensure consistent
// data structure.
func (c *Csv[T]) AppendToFile(fileName string, rows <-chan *T) error {
file, err := os.OpenFile(filepath.Clean(fileName), os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return err
}
err = c.writeToWriter(file, false, rows)
if err != nil {
return err
}
return file.Close()
}
// WriteToFile creates a new file with the given name and writes the provided rows
// of data to it, overwriting any existing content.
func (c *Csv[T]) WriteToFile(fileName string, rows <-chan *T) error {
file, err := os.OpenFile(filepath.Clean(fileName), os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
err = c.writeToWriter(file, true, rows)
if err != nil {
return err
}
return file.Close()
}
// updateColumnIndexes aligns column indices to match the order of column headers.
func (c *Csv[T]) updateColumnIndexes(csvReader *csv.Reader) error {
headers, err := csvReader.Read()
if err != nil {
return err
}
headerMap := make(map[string]int)
for i, header := range headers {
headerMap[header] = i
}
for i := range c.columns {
index, ok := headerMap[c.columns[i].Header]
if !ok {
index = -1
}
c.columns[i].ColumnIndex = index
}
return nil
}
// writeToWriter writes the provided rows of data to the specified writer, with the option
// to include or exclude headers for flexibility in data presentation.
func (c *Csv[T]) writeToWriter(writer io.Writer, writeHeader bool, rows <-chan *T) error {
csvWriter := csv.NewWriter(writer)
if writeHeader {
err := c.writeHeaderToCsvWriter(csvWriter)
if err != nil {
return err
}
}
record := make([]string, len(c.columns))
for row := range rows {
rowValue := reflect.ValueOf(row).Elem()
for i, column := range c.columns {
stringValue, err := getReflectValue(rowValue.Field(column.FieldIndex), column.Format)
if err != nil {
return err
}
record[i] = stringValue
}
err := csvWriter.Write(record)
if err != nil {
return err
}
}
csvWriter.Flush()
return csvWriter.Error()
}
// writeHeaderToCsvWriter writes the column headers for the CSV data to the specified CSV writer.
func (c *Csv[T]) writeHeaderToCsvWriter(csvWriter *csv.Writer) error {
header := make([]string, len(c.columns))
for i, column := range c.columns {
header[i] = column.Header
}
return csvWriter.Write(header)
}
// ReadFromCsvFile creates a CSV instance, parses CSV data from the provided filename,
// maps the data to corresponding struct fields, and delivers it through the channel.
func ReadFromCsvFile[T any](fileName string, hasHeader bool) (<-chan *T, error) {
csv, err := NewCsv[T](hasHeader)
if err != nil {
return nil, err
}
return csv.ReadFromFile(fileName)
}
// AppendOrWriteToCsvFile writes the provided rows of data to the specified file, appending to
// the existing file if it exists or creating a new one if it doesn't. In append mode, the
// function assumes that the existing file's column order matches the field order of the
// given row struct to ensure consistent data structure.
func AppendOrWriteToCsvFile[T any](fileName string, hasHeader bool, rows <-chan *T) error {
csv, err := NewCsv[T](hasHeader)
if err != nil {
return err
}
stat, err := os.Stat(filepath.Clean(fileName))
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return err
}
} else if stat.Size() > 0 {
return csv.AppendToFile(fileName, rows)
}
return csv.WriteToFile(fileName, rows)
}