-
Notifications
You must be signed in to change notification settings - Fork 0
/
building.go
93 lines (82 loc) · 2.01 KB
/
building.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
package csvutil
import (
"io"
"github.com/pkg/errors"
)
// BuildingOption is option holder for Building.
type BuildingOption 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
// Target column symbol
Column string
// Rate of office output
OfficeRate int
// BlockNumber width(1 or 2)
NumberWidth int
// Append to source value
Append bool
}
func (o BuildingOption) validate() error {
if o.Column == "" {
return errors.New("no column")
}
if o.NoHeader {
if !isDigit(o.Column) {
return errors.New("not number column symbol")
}
}
if o.OfficeRate < 0 || 100 < o.OfficeRate {
return errors.New("invalid office rate (0 <= rate <= 100)")
}
if o.NumberWidth != 1 && o.NumberWidth != 2 {
return errors.New("invalid number width (1 or 2)")
}
return nil
}
func (o BuildingOption) isFullWidth() bool {
return o.NumberWidth == 2
}
func (o BuildingOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
// Building overwrite value of given column by dummy office or apartment.
func Building(r io.Reader, w io.Writer, o BuildingOption) 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
csvp := NewCSVProcessor(cr, cw)
if o.NoHeader {
csvp.SetPreBodyRead(func() error {
col = newColumnWithIndex(o.Column, nil)
return col.err
})
} else {
csvp.SetHeaderHanlder(func(hdr []string) ([]string, error) {
col = newColumnWithIndex(o.Column, hdr)
return hdr, col.err
})
}
csvp.SetRecordHandler(func(rec []string) ([]string, error) {
if !o.Append {
rec[col.index] = ""
}
if lot(o.OfficeRate) {
rec[col.index] += fakeOffice(o.isFullWidth())
} else {
rec[col.index] += fakeApartment(o.isFullWidth())
}
return rec, nil
})
return csvp.Process()
}