forked from gocarina/gocsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
147 lines (138 loc) · 4.29 KB
/
encode.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
package gocsv
import (
"fmt"
"io"
"reflect"
)
type encoder struct {
out io.Writer
}
func newEncoder(out io.Writer) *encoder {
return &encoder{out}
}
func writeFromChan(writer CSVWriter, c <-chan interface{}) error {
// Get the first value. It wil determine the header structure.
firstValue, ok := <-c
if !ok {
return fmt.Errorf("channel is closed")
}
inValue, inType := getConcreteReflectValueAndType(firstValue) // Get the concrete type
if err := ensureStructOrPtr(inType); err != nil {
return err
}
inInnerWasPointer := inType.Kind() == reflect.Ptr
inInnerStructInfo := getStructInfo(inType) // Get the inner struct info to get CSV annotations
csvHeadersLabels := make([]string, len(inInnerStructInfo.Fields))
for i, fieldInfo := range inInnerStructInfo.Fields { // Used to write the header (first line) in CSV
csvHeadersLabels[i] = fieldInfo.getFirstKey()
}
if err := writer.Write(csvHeadersLabels); err != nil {
return err
}
write := func(val reflect.Value) error {
for j, fieldInfo := range inInnerStructInfo.Fields {
csvHeadersLabels[j] = ""
inInnerFieldValue, err := getInnerField(val, inInnerWasPointer, fieldInfo.IndexChain) // Get the correct field header <-> position
if err != nil {
return err
}
csvHeadersLabels[j] = inInnerFieldValue
}
if err := writer.Write(csvHeadersLabels); err != nil {
return err
}
return nil
}
if err := write(inValue); err != nil {
return err
}
for v := range c {
val, _ := getConcreteReflectValueAndType(v) // Get the concrete type (not pointer) (Slice<?> or Array<?>)
if err := ensureStructOrPtr(inType); err != nil {
return err
}
if err := write(val); err != nil {
return err
}
}
writer.Flush()
return writer.Error()
}
func writeTo(writer CSVWriter, in interface{}, omitHeaders bool) error {
inValue, inType := getConcreteReflectValueAndType(in) // Get the concrete type (not pointer) (Slice<?> or Array<?>)
if err := ensureInType(inType); err != nil {
return err
}
inInnerWasPointer, inInnerType := getConcreteContainerInnerType(inType) // Get the concrete inner type (not pointer) (Container<"?">)
if err := ensureInInnerType(inInnerType); err != nil {
return err
}
inInnerStructInfo := getStructInfo(inInnerType) // Get the inner struct info to get CSV annotations
csvHeadersLabels := make([]string, len(inInnerStructInfo.Fields))
for i, fieldInfo := range inInnerStructInfo.Fields { // Used to write the header (first line) in CSV
csvHeadersLabels[i] = fieldInfo.getFirstKey()
}
if !omitHeaders {
if err := writer.Write(csvHeadersLabels); err != nil {
return err
}
}
inLen := inValue.Len()
for i := 0; i < inLen; i++ { // Iterate over container rows
for j, fieldInfo := range inInnerStructInfo.Fields {
csvHeadersLabels[j] = ""
inInnerFieldValue, err := getInnerField(inValue.Index(i), inInnerWasPointer, fieldInfo.IndexChain) // Get the correct field header <-> position
if err != nil {
return err
}
csvHeadersLabels[j] = inInnerFieldValue
}
if err := writer.Write(csvHeadersLabels); err != nil {
return err
}
}
writer.Flush()
return writer.Error()
}
func ensureStructOrPtr(t reflect.Type) error {
switch t.Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
return nil
}
return fmt.Errorf("cannot use " + t.String() + ", only slice or array supported")
}
// Check if the inType is an array or a slice
func ensureInType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
}
// Check if the inInnerType is of type struct
func ensureInInnerType(outInnerType reflect.Type) error {
switch outInnerType.Kind() {
case reflect.Struct:
return nil
}
return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
}
func getInnerField(outInner reflect.Value, outInnerWasPointer bool, index []int) (string, error) {
oi := outInner
if outInnerWasPointer {
if oi.IsNil() {
return "", nil
}
oi = outInner.Elem()
}
// because pointers can be nil need to recurse one index at a time and perform nil check
if len(index) > 1 {
nextField := oi.Field(index[0])
return getInnerField(nextField, nextField.Kind() == reflect.Ptr, index[1:])
}
return getFieldAsString(oi.FieldByIndex(index))
}