Skip to content

Commit 7e02fca

Browse files
committed
Initial files. Read rows from file is added.
0 parents  commit 7e02fca

6 files changed

Lines changed: 411 additions & 0 deletions

File tree

LICENSE.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright © 2021 Onur Cinar
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
[![GoDoc](https://godoc.org/github.com/cinar/csv2?status.svg)](https://godoc.org/github.com/cinar/csv2)
2+
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
3+
[![Build Status](https://travis-ci.com/cinar/csv2.svg?branch=master)](https://travis-ci.com/cinar/csv2)
4+
5+
# Csv2 Go
6+
7+
Csv2 is a lightweight Golang module for reading CSV files as individual rows or as a table.
8+
9+
## Usage
10+
11+
Install package.
12+
13+
```bash
14+
go get github.com/cinar/csv2
15+
```
16+
17+
Import Csv2.
18+
19+
```Golang
20+
import (
21+
"github.com/cinar/csv2"
22+
)
23+
```
24+
25+
### Reading as individual rows
26+
27+
Given that the CSV file contains the following columns.
28+
29+
```CSV
30+
date,close,high,low,open,volume,adjClose,adjHigh,adjLow,adjOpen,adjVolume,divCash,splitFactor
31+
2015-09-18 00:00:00+00:00,43.48,43.99,43.33,43.5,63143684,39.5167038561,39.9802162518,39.3803766809,39.534880812800004,63143684,0.0,1.0
32+
```
33+
34+
Define a structure for each individual row.
35+
36+
```Golang
37+
// Daily price structure for each row.
38+
type dailyPrice struct {
39+
Date time.Time `format:"2006-01-02 15:04:05-07:00"`
40+
Close float64
41+
High float64
42+
Low float64
43+
Open float64
44+
Volume int64
45+
AdjClose float64
46+
AdjHigh float64
47+
AdjLow float64
48+
AdjOpen float64
49+
AdjVolume int64
50+
DivCash float64
51+
SplitFactor float64
52+
}
53+
```
54+
55+
Csv2 allows you to associate additional information about the colums through the tags. The following additional information is currently supported.
56+
57+
Tag | Description | Example
58+
--- | --- | ---
59+
header | Column header for the field. | `header:"Date"`
60+
format | Date format for parsing. | `format:"2006-01-02 15:04:05-07:00"`
61+
62+
Define an instance of a slice of row structure.
63+
64+
```Golang
65+
var prices []dailyPrice
66+
```
67+
68+
Use the [ReadRowsFromFile](https://pkg.go.dev/github.com/cinar/csv2#ReadRowsFromFile) function to read the CSV file into the slice.
69+
70+
```Golang
71+
err := ReadRowsFromFile(testFile, true, &prices)
72+
if err != nil {
73+
return err
74+
}
75+
```
76+
## License
77+
78+
The source code is provided under MIT License.

csv2.go

Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
package csv2
2+
3+
import (
4+
"encoding/csv"
5+
"errors"
6+
"fmt"
7+
"io"
8+
"math/bits"
9+
"os"
10+
"reflect"
11+
"strconv"
12+
"strings"
13+
"time"
14+
)
15+
16+
const (
17+
// Header name
18+
TagHeader = "header"
19+
20+
// Format name
21+
TagFormat = "format"
22+
)
23+
24+
const (
25+
timeFormat = "2006-01-02 15:04:05"
26+
)
27+
28+
type columnInfo struct {
29+
Header string
30+
ColumnIndex int
31+
FieldIndex int
32+
Format string
33+
}
34+
35+
func setBoolFieldValue(fieldValue reflect.Value, stringValue string) error {
36+
value, err := strconv.ParseBool(stringValue)
37+
if err == nil {
38+
fieldValue.SetBool(value)
39+
}
40+
41+
return err
42+
}
43+
44+
func setIntFieldValue(fieldValue reflect.Value, stringValue string, bitSize int) error {
45+
value, err := strconv.ParseInt(stringValue, 10, bitSize)
46+
if err == nil {
47+
fieldValue.SetInt(value)
48+
}
49+
50+
return err
51+
}
52+
53+
func setUintFieldValue(fieldValue reflect.Value, stringValue string, bitSize int) error {
54+
value, err := strconv.ParseUint(stringValue, 10, bitSize)
55+
if err == nil {
56+
fieldValue.SetUint(value)
57+
}
58+
59+
return err
60+
}
61+
62+
func setFloatFieldValue(fieldValue reflect.Value, stringValue string, bitSize int) error {
63+
value, err := strconv.ParseFloat(stringValue, bitSize)
64+
if err == nil {
65+
fieldValue.SetFloat(value)
66+
}
67+
68+
return err
69+
}
70+
71+
func setTimeFieldValue(fieldValue reflect.Value, stringValue string, format string) error {
72+
value, err := time.Parse(format, stringValue)
73+
if err == nil {
74+
fieldValue.Set(reflect.ValueOf(value))
75+
}
76+
77+
return err
78+
}
79+
80+
func setFieldValue(fieldValue reflect.Value, stringValue string, format string) error {
81+
fieldKind := fieldValue.Kind()
82+
83+
switch fieldKind {
84+
case reflect.String:
85+
fieldValue.SetString(stringValue)
86+
return nil
87+
88+
case reflect.Bool:
89+
return setBoolFieldValue(fieldValue, stringValue)
90+
91+
case reflect.Int:
92+
return setIntFieldValue(fieldValue, stringValue, bits.UintSize)
93+
94+
case reflect.Int8:
95+
return setIntFieldValue(fieldValue, stringValue, 8)
96+
97+
case reflect.Int16:
98+
return setIntFieldValue(fieldValue, stringValue, 16)
99+
100+
case reflect.Int32:
101+
return setIntFieldValue(fieldValue, stringValue, 32)
102+
103+
case reflect.Int64:
104+
return setIntFieldValue(fieldValue, stringValue, 64)
105+
106+
case reflect.Uint:
107+
return setUintFieldValue(fieldValue, stringValue, bits.UintSize)
108+
109+
case reflect.Uint8:
110+
return setUintFieldValue(fieldValue, stringValue, 8)
111+
112+
case reflect.Uint16:
113+
return setUintFieldValue(fieldValue, stringValue, 16)
114+
115+
case reflect.Uint32:
116+
return setUintFieldValue(fieldValue, stringValue, 32)
117+
118+
case reflect.Uint64:
119+
return setUintFieldValue(fieldValue, stringValue, 64)
120+
121+
case reflect.Float32:
122+
return setFloatFieldValue(fieldValue, stringValue, 32)
123+
124+
case reflect.Float64:
125+
return setFloatFieldValue(fieldValue, stringValue, 64)
126+
127+
case reflect.Struct:
128+
fieldTypeString := fieldValue.Type().String()
129+
130+
switch fieldTypeString {
131+
case "time.Time":
132+
return setTimeFieldValue(fieldValue, stringValue, format)
133+
134+
default:
135+
return fmt.Errorf("unsupported struct type %s", fieldTypeString)
136+
}
137+
138+
default:
139+
return fmt.Errorf("unsupported field kind %s", fieldKind)
140+
}
141+
}
142+
143+
func getStructFieldsAsColumns(structType reflect.Type) []columnInfo {
144+
columns := make([]columnInfo, structType.NumField())
145+
for i := 0; i < structType.NumField(); i++ {
146+
field := structType.Field(i)
147+
148+
header, ok := field.Tag.Lookup(TagHeader)
149+
if !ok {
150+
header = field.Name
151+
}
152+
153+
format, ok := field.Tag.Lookup(TagFormat)
154+
if !ok {
155+
format = timeFormat
156+
}
157+
158+
columns[i] = columnInfo{
159+
Header: header,
160+
ColumnIndex: i,
161+
FieldIndex: i,
162+
Format: format,
163+
}
164+
}
165+
166+
return columns
167+
}
168+
169+
func readHeader(csvReader csv.Reader, columns []columnInfo) error {
170+
headers, err := csvReader.Read()
171+
if err != nil {
172+
return err
173+
}
174+
175+
for _, column := range columns {
176+
for i, header := range headers {
177+
if strings.EqualFold(column.Header, header) {
178+
column.ColumnIndex = i
179+
break
180+
}
181+
}
182+
}
183+
184+
return nil
185+
}
186+
187+
// Read rows from reader.
188+
func ReadRowsFromReader(reader io.Reader, hasHeader bool, rows interface{}) error {
189+
rowsPtrType := reflect.TypeOf(rows)
190+
if rowsPtrType.Kind() != reflect.Ptr {
191+
return errors.New("rows not a pointer")
192+
}
193+
194+
rowsSliceType := rowsPtrType.Elem()
195+
if rowsSliceType.Kind() != reflect.Slice {
196+
return errors.New("rows not a pointer to slice")
197+
}
198+
199+
rowType := rowsSliceType.Elem()
200+
if rowType.Kind() != reflect.Struct {
201+
return errors.New("rows not a pointer to slice of struct")
202+
}
203+
204+
rowsPtr := reflect.ValueOf(rows)
205+
rowsSlice := rowsPtr.Elem()
206+
207+
columns := getStructFieldsAsColumns(rowType)
208+
209+
csvReader := csv.NewReader(reader)
210+
211+
if hasHeader {
212+
if err := readHeader(*csvReader, columns); err != nil {
213+
return err
214+
}
215+
}
216+
217+
for {
218+
record, err := csvReader.Read()
219+
if err == io.EOF {
220+
break
221+
}
222+
223+
if err != nil {
224+
return err
225+
}
226+
227+
row := reflect.New(rowType).Elem()
228+
229+
for _, column := range columns {
230+
if err = setFieldValue(row.Field(column.FieldIndex), record[column.ColumnIndex], column.Format); err != nil {
231+
return err
232+
}
233+
}
234+
235+
rowsSlice = reflect.Append(rowsSlice, row)
236+
}
237+
238+
rowsPtr.Elem().Set(rowsSlice)
239+
240+
return nil
241+
}
242+
243+
// Read rows from file.
244+
func ReadRowsFromFile(fileName string, hasHeader bool, rows interface{}) error {
245+
file, err := os.Open(fileName)
246+
if err != nil {
247+
return err
248+
}
249+
250+
defer file.Close()
251+
252+
return ReadRowsFromReader(file, hasHeader, rows)
253+
}

0 commit comments

Comments
 (0)