-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_parser.go
66 lines (60 loc) · 1.24 KB
/
csv_parser.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
package st2
import (
"bufio"
"fmt"
"io"
"strings"
)
// CsvParser is a Parser to parse `.csv` source.
type CsvParser struct {
ctx Context
}
// NewCsvParser create [CsvParser]
func NewCsvParser(ctx Context) *CsvParser {
return &CsvParser{
ctx: ctx,
}
}
// Parse method parse csv source
func (p CsvParser) Parse(reader io.Reader) ([]*Struct, error) {
bufioReader := bufio.NewReader(reader)
str, err := bufioReader.ReadString('\n')
if err != nil {
return nil, err
}
items := strings.Split(str, ",")
rootName := p.ctx.Root
if rootName == "" {
rootName = RootDefault
}
rootName = camel(rootName)
st := &Struct{
Type: &StructLikeType{
Name: rootName,
Source: SLSStruct,
},
}
for i, item := range items {
member := &Member{
Field: p.formatItem(item),
Type: StringVal,
Index: i + 1,
}
member.GoTag = append(member.GoTag, fmt.Sprintf(`csv:"%s"`, member.Field))
st.Members = append(st.Members, member)
}
return []*Struct{st}, nil
}
func (p CsvParser) formatItem(str string) string {
str = strings.TrimSpace(str)
items := strings.Split(str, " ")
last := 0
for i := 0; i < len(items); i++ {
if items[i] != "" {
items[last] = items[i]
last++
}
}
items = items[0:last]
return strings.Join(items, "_")
}