-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 858afcb
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
<a href="https://engineering.carrot.is/"><p align="center"><img src="https://cloud.githubusercontent.com/assets/2105067/24525319/d3d26516-1567-11e7-9506-7611b3287d53.png" alt="Go Carrot" width="350px" align="center;" /></p></a> | ||
# Sheet |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package sheet | ||
|
||
import ( | ||
"encoding/csv" | ||
"fmt" | ||
"os" | ||
) | ||
|
||
type Handler func(params []string, data *map[string]interface{}) error | ||
|
||
type Operation struct { | ||
Columns []int | ||
Handler Handler | ||
} | ||
|
||
type Row struct { | ||
Data map[string]interface{} | ||
Operations []Operation | ||
} | ||
|
||
type CSV struct { | ||
FilePath string | ||
IgnoreRows []int | ||
Row Row | ||
} | ||
|
||
func Consume(csvDefinition CSV) error { | ||
// Open the CSV file for reading | ||
file, err := os.Open(csvDefinition.FilePath) | ||
if err != nil { | ||
return err | ||
} | ||
defer file.Close() | ||
|
||
// New CSV Reader | ||
reader := csv.NewReader(file) | ||
records, err := reader.ReadAll() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Handle each record | ||
for i, record := range records { | ||
if !rowIgnored(i, csvDefinition.IgnoreRows) { | ||
handleRecord(i, record, csvDefinition.Row) | ||
} | ||
} | ||
|
||
// OK | ||
return nil | ||
} | ||
|
||
func rowIgnored(rowNumber int, ignoredRows []int) bool { | ||
for _, ignoredRow := range ignoredRows { | ||
if ignoredRow == rowNumber { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func handleRecord(index int, record []string, row Row) { | ||
row.Data = make(map[string]interface{}) | ||
for _, model := range row.Operations { | ||
var params = []string{} | ||
for _, columnNumber := range model.Columns { | ||
params = append(params, record[columnNumber]) | ||
} | ||
err := model.Handler(params, &row.Data) | ||
if err != nil { | ||
// If there's an error, break out | ||
fmt.Printf("Skipping row %v\nError: %v\n", index, err) | ||
return | ||
} | ||
} | ||
} |