/
Read.go
64 lines (55 loc) · 1.75 KB
/
Read.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
// =================================================================
//
// Copyright (C) 2019 Spatial Current, Inc. - All Rights Reserved
// Released as open source under the MIT License. See LICENSE file.
//
// =================================================================
package sv
import (
"io"
"reflect"
"github.com/pkg/errors"
"github.com/spatialcurrent/go-pipe/pkg/pipe"
)
// ReadInput provides the input for the Read function.
type ReadInput struct {
Type reflect.Type // the output type
Reader io.Reader
Separator rune // the values separator
Header []interface{}
SkipLines int
Comment string
LazyQuotes bool
Limit int
}
// Read reads the separated values from the input reader into a slice.
func Read(input *ReadInput) (interface{}, error) {
// If input.Type is nil, then use []map[string]string{}.
inputType := reflect.TypeOf([]map[string]string{})
if input.Type != nil {
inputType = input.Type
}
// The iterator requires the type to return for each element,
// rather than the type of the array itself.
iteratorType := inputType.Elem()
if iteratorType.Kind() == reflect.Interface {
iteratorType = reflect.TypeOf(map[string]string{})
}
it, errorIterator := NewIterator(&NewIteratorInput{
Reader: input.Reader,
Type: iteratorType,
Separator: input.Separator,
Header: input.Header,
Comment: input.Comment,
SkipLines: input.SkipLines,
LazyQuotes: input.LazyQuotes,
Limit: input.Limit,
})
if errorIterator != nil {
return nil, errors.Wrap(errorIterator, "error creating iterator")
}
output := reflect.MakeSlice(inputType, 0, 0).Interface()
w := pipe.NewSliceWriterWithValues(output)
errorRun := pipe.NewBuilder().Input(it).Output(w).Run()
return w.Values(), errorRun
}