/
csv_formatter.go
129 lines (98 loc) 路 2.15 KB
/
csv_formatter.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
package q
import (
"errors"
"fmt"
"github.com/elliotchance/gedcom"
"io"
"reflect"
"sort"
"strings"
"unicode"
)
type CSVFormatter struct {
Writer io.Writer
}
func (f *CSVFormatter) Write(result interface{}) error {
columns, err := f.Header(result)
if err != nil {
return err
}
f.writeLine(columns)
v := reflect.ValueOf(result)
if v.Kind() == reflect.Slice {
for i := 0; i < v.Len(); i++ {
line := []string{}
value := f.prepareLine(v.Index(i).Interface())
for _, name := range columns {
line = append(line, fmt.Sprintf("%v", value[name]))
}
f.writeLine(line)
}
}
return nil
}
func (f *CSVFormatter) writeLine(fields []string) {
for i := 0; i < len(fields); i++ {
if i > 0 {
fmt.Fprintf(f.Writer, ",")
}
f.writeValue(fields[i])
}
fmt.Fprintf(f.Writer, "\n")
}
func (f *CSVFormatter) writeValue(s string) {
s = strings.Replace(s, `"`, `""`, -1)
commaIndex := strings.Index(s, ",")
quoteIndex := strings.Index(s, `"`)
if commaIndex < 0 && quoteIndex < 0 {
fmt.Fprintf(f.Writer, "%s", s)
} else {
fmt.Fprintf(f.Writer, `"%s"`, s)
}
}
func (f *CSVFormatter) prepareLine(line interface{}) map[string]interface{} {
if m, ok := line.(gedcom.ObjectMapper); ok {
return m.ObjectMap()
}
l := reflect.ValueOf(line)
if l.Kind() == reflect.Ptr {
l = l.Elem()
}
if l.Kind() == reflect.Map {
m := map[string]interface{}{}
for _, name := range l.MapKeys() {
m[name.Interface().(string)] = l.MapIndex(name).Interface()
}
return m
}
if l.Kind() == reflect.Struct {
t := l.Type()
m := map[string]interface{}{}
for i := 0; i < t.NumField(); i++ {
name := t.Field(i).Name
// Ignore unexported
if !unicode.IsUpper(rune(name[0])) {
continue
}
m[name] = l.FieldByName(name).Interface()
}
return m
}
return nil
}
func (f *CSVFormatter) Header(result interface{}) ([]string, error) {
v := reflect.ValueOf(result)
if v.Kind() != reflect.Slice {
return nil, errors.New("not a slice")
}
if v.Len() == 0 {
return nil, nil
}
line := f.prepareLine(v.Index(0).Interface())
s := []string{}
for column := range line {
s = append(s, column)
}
sort.Strings(s)
return s, nil
}