Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
BrandonRomano committed Jun 5, 2017
0 parents commit 858afcb
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
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
76 changes: 76 additions & 0 deletions sheet.go
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
}
}
}

0 comments on commit 858afcb

Please sign in to comment.