-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.go
More file actions
68 lines (62 loc) · 1.68 KB
/
Copy pathwriter.go
File metadata and controls
68 lines (62 loc) · 1.68 KB
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
package csv
import (
"encoding/csv"
"io"
"reflect"
"github.com/weisbartb/rcache"
"github.com/weisbartb/stack"
)
// Writer holds the state of the CSV writer
type Writer[Record any] struct {
headerWritten bool
instruction *rcache.FieldCache[csvInstruction]
w *csv.Writer
}
// NewWriter makes a new CSV writer
func NewWriter[Record any](writer io.Writer) *Writer[Record] {
var T Record
return &Writer[Record]{
w: csv.NewWriter(writer),
instruction: fieldCache.GetTypeDataFor(reflect.TypeOf(T)),
}
}
// WriteRecord writes record(s) to the underlying file, a flush is automatically called upon finishing.
func (c *Writer[Record]) WriteRecord(items ...Record) error {
defer func() {
// Flush the buffered IO from the underlying csv-writer
c.w.Flush()
}()
if !c.headerWritten {
if err := c.writeHeader(); err != nil {
return stack.Trace(err)
}
}
for _, item := range items {
vOf := reflect.ValueOf(item)
var row []string
for _, field := range fieldCache.GetTypeDataFor(vOf.Type()).Fields() {
val, err := field.InstructionData().encoder(vOf.Field(field.Idx))
if err != nil {
return stack.Trace(err)
}
row = append(row, val)
}
if err := c.w.Write(row); err != nil {
return stack.Trace(err)
}
}
return nil
}
// writeHeader is a helper method to write out the header to the CSV
func (c *Writer[Record]) writeHeader() error {
var columns []string
var rec Record
for _, field := range fieldCache.GetTypeDataFor(reflect.TypeOf(rec)).Fields() {
columns = append(columns, field.InstructionData().GetCSVHeaderIdentifier())
}
if err := c.w.Write(columns); err != nil {
return stack.Trace(err)
}
c.headerWritten = true
return nil
}