-
Notifications
You must be signed in to change notification settings - Fork 10
/
option.go
82 lines (76 loc) · 1.89 KB
/
option.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
package easycsv
import (
"errors"
"reflect"
)
// Option specifies the spec of Reader.
type Option struct {
// Comma is the field delimiter.
// For exampoe, if '\t' is set to Comma, Reader reads files as TSV files.
Comma rune
// Comment, if not 0, is the comment character. Lines beginning with the character without preceding whitespace are ignored.
Comment rune
// Allow lazy parsing of quotes, default to false
LazyQuotes bool
// If negative, Reader does not check the number of fields per record
// If 0, this option does not update Reader
// If positive, Reader requires all records to have this number of fields
FieldsPerRecord int
// Decoders is the map to define custom encodings.
Decoders map[string]interface{}
// Custom decoders to parse specific types.
TypeDecoders map[reflect.Type]interface{}
// TODO: Support AutoIndex
AutoIndex bool
// TODO: Support AutoName
AutoName bool
}
func (a *Option) mergeOption(b Option) {
if b.Comma != 0 {
a.Comma = b.Comma
}
if b.Comment != 0 {
a.Comment = b.Comment
}
if b.AutoIndex {
a.AutoIndex = true
}
if b.AutoName {
a.AutoName = true
}
if b.LazyQuotes {
a.LazyQuotes = b.LazyQuotes
}
if b.FieldsPerRecord != 0 {
a.FieldsPerRecord = b.FieldsPerRecord
}
if b.Decoders != nil {
if a.Decoders == nil {
a.Decoders = make(map[string]interface{})
}
for name, dec := range b.Decoders {
a.Decoders[name] = dec
}
}
if b.TypeDecoders != nil {
if a.TypeDecoders == nil {
a.TypeDecoders = make(map[reflect.Type]interface{})
}
for t, dec := range b.TypeDecoders {
a.TypeDecoders[t] = dec
}
}
}
func (a *Option) validate() error {
if a.AutoIndex && a.AutoName {
return errors.New("You can not set both AutoIndex and AutoName to easycsv.Reader.")
}
return nil
}
func mergeOptions(opts []Option) (Option, error) {
var opt Option
for _, o := range opts {
opt.mergeOption(o)
}
return opt, opt.validate()
}