forked from andreaskoch/togglcsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
47 lines (37 loc) · 1.25 KB
/
export.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
package main
import (
"encoding/csv"
"fmt"
"io"
"time"
"github.com/andreaskoch/togglcsv/toggl"
)
// The CSVExporter interface exports time records from a Toggl account as CSV.
type CSVExporter interface {
// Export prints all time records from the given start date as CSV
Export(startDate, endDate time.Time, writer io.Writer) error
}
// TogglCSVExporter provides import and export functionality Toggl accounts.
type TogglCSVExporter struct {
csvMapper TimeRecordMapper
timeRecordRepository toggl.TimeRecorder
}
// Export prints all time records from the given start date as CSV.
func (exporter *TogglCSVExporter) Export(startDate, endDate time.Time, writer io.Writer) error {
csvWriter := csv.NewWriter(writer)
defer csvWriter.Flush()
// write the header
csvWriter.Write(exporter.csvMapper.GetColumnNames())
csvWriter.Flush()
records, timeRecordsError := exporter.timeRecordRepository.GetTimeRecords(startDate, endDate)
if timeRecordsError != nil {
return fmt.Errorf("Failed to retrieve time records between %q and %q: %s", startDate, endDate, timeRecordsError.Error())
}
// write the records one-by-one
for _, record := range records {
row := exporter.csvMapper.GetRow(record)
csvWriter.Write(row)
csvWriter.Flush()
}
return nil
}