-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappend.go
More file actions
77 lines (67 loc) · 1.56 KB
/
append.go
File metadata and controls
77 lines (67 loc) · 1.56 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
69
70
71
72
73
74
75
76
77
package csvutil
import (
"io"
"strconv"
"github.com/pkg/errors"
)
// AppendOption is option holder for Append.
type AppendOption 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 appending header list.
Headers []string
// Size is appending column size.
Size int
}
func (o AppendOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
func (o AppendOption) validate() error {
if o.Size <= 0 {
return errors.New("negative or zero size")
}
return nil
}
func (o AppendOption) 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
}
// Append empty values to end of each lines.
func Append(r io.Reader, w io.Writer, o AppendOption) 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()
csvp := NewCSVProcessor(cr, cw)
if !o.NoHeader {
csvp.SetHeaderHanlder(func(hdr []string) ([]string, error) {
for _, h := range o.headers() {
hdr = append(hdr, h)
}
return hdr, nil
})
}
csvp.SetRecordHandler(func(rec []string) ([]string, error) {
newRec := make([]string, len(rec)+o.Size)
copy(newRec, rec)
return newRec, nil
})
return csvp.Process()
}