-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathselect.go
48 lines (39 loc) · 1.21 KB
/
select.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
package csv
import (
"github.com/wildducktheories/go-csv/utils"
)
// Given a header-prefixed input stream of CSV records select the fields that match the specified key (Key).
// If PermuteOnly is is specified, all the fields of the input stream are preserved, but the output stream
// is permuted so that the key fields occupy the left-most fields of the output stream. The remaining fields
// are preserved in their original order.
type SelectProcess struct {
Keys []string
PermuteOnly bool
}
func (p *SelectProcess) Run(reader Reader, builder WriterBuilder, errCh chan<- error) {
errCh <- func() (err error) {
defer reader.Close()
keys := p.Keys
permuteOnly := p.PermuteOnly
// get the data header
dataHeader := reader.Header()
_, _, b := utils.Intersect(keys, dataHeader)
if len(b) > 0 && permuteOnly {
extend := make([]string, len(keys)+len(b))
copy(extend, keys)
copy(extend[len(keys):], b)
keys = extend
}
// create a new output stream
writer := builder(keys)
defer writer.Close(err)
for data := range reader.C() {
outputData := writer.Blank()
outputData.PutAll(data)
if err = writer.Write(outputData); err != nil {
return err
}
}
return reader.Error()
}()
}