-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.go
110 lines (97 loc) · 2.21 KB
/
insert.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
package csvutil
import (
"io"
"strconv"
"github.com/pkg/errors"
)
// InsertOption is option holder for Insert.
type InsertOption struct {
// Source file does not have header line. (default false)
NoHeader bool
// Encoding of source file. (default utf8)
Encoding string
// Encoding for output.
OutputEncoding string
// Headers is header list for insert.
Headers []string
// Size is appending column size.
Size int
// Before is insert start column symbol.
Before string
}
func (o InsertOption) before() string {
if o.Before == "" {
return "0"
}
return o.Before
}
func (o InsertOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
func (o InsertOption) validate() error {
if o.Size <= 0 {
return errors.New("negative or zero size")
}
return nil
}
func (o InsertOption) headers() []string {
hdr := make([]string, o.Size)
hl := len(o.Headers)
for i := 0; i < o.Size; i++ {
if hl > i {
hdr[i] = o.Headers[i]
continue
}
hdr[i] = "column" + strconv.Itoa(i-hl+1)
}
return hdr
}
// Insert empty values to CSV
func Insert(r io.Reader, w io.Writer, o InsertOption) error {
if err := o.validate(); err != nil {
return errors.Wrap(err, "invalid option")
}
cr, bom := reader(r, o.Encoding)
cw := writer(w, bom, o.outputEncoding())
defer cw.Flush()
var col *column
vals := make([]string, o.Size)
csvp := NewCSVProcessor(cr, cw)
if o.NoHeader {
csvp.SetPreBodyRead(func() error {
col = newColumnWithIndex(o.before(), nil)
return col.err
})
} else {
csvp.SetHeaderHanlder(func(hdr []string) ([]string, error) {
col = newColumnWithIndex(o.before(), hdr)
if col.err != nil {
return nil, col.err
}
return insertTo(hdr, col, o.Size, o.headers()), nil
})
}
csvp.SetRecordHandler(func(rec []string) ([]string, error) {
return insertTo(rec, col, o.Size, vals), nil
})
return csvp.Process()
}
func insertTo(rec []string, col *column, size int, ss []string) []string {
hdr := make([]string, len(rec)+size)
for i, h := range rec {
if i < col.index {
hdr[i] = h
} else if i == col.index {
for j, s := range ss {
hdr[i+j] = s
}
hdr[col.index+size] = h
} else {
hdr[i+size] = h
}
}
return hdr
}