-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv2tpl.go
97 lines (77 loc) · 2.04 KB
/
csv2tpl.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Filename: csv2tpl.go
package main
import (
"encoding/csv"
"flag"
"html/template"
"io"
"log"
"os"
"strings"
)
func init() {
log.SetFlags(0) // hide timestamp in log messages
}
func main() {
var header []string // csv header
var params = make(map[string]string) // go map of csv record
var noempty bool = false // error if csv line has empty records
var verbose bool = false
flag.BoolVar(&verbose, "verbose", false, "Work on log level info")
flag.BoolVar(&noempty, "noempty", false, "Stop if any CSV columns are empty")
flag.Parse()
if len(flag.Args()) != 2 {
log.Fatal("Usage: csv2tpl [-verbose] [-noempty] template-file csv-file")
}
tplFname := flag.Args()[0]
csvFname := flag.Args()[1]
tpl, err := template.ParseFiles(tplFname)
if err != nil {
log.Fatal("ERROR: parsing template: ", err)
}
csvFh, err := os.Open(csvFname)
if err != nil {
log.Fatal(err)
}
defer csvFh.Close()
csvReader := csv.NewReader(csvFh)
header, err = csvReader.Read()
if err != nil {
log.Fatal("ERROR: reading CSV header: ", err)
}
if len(header) == 0 {
log.Fatal("ERROR: no columns found in CSV header, ensure UTF8 BOM is *not* present")
}
for i := range header {
header[i] = strings.TrimSpace((header[i]))
if verbose {
log.Println("Parsed CSV header column:", header[i])
}
}
for line := 1; ; line++ {
// Stop if end of file reached
record, err := csvReader.Read()
if err == io.EOF {
break
}
// Abort on any other errors
if err != nil {
log.Fatal("ERROR: reading CSV line ", line, ": ", err)
}
// Map CSV line into parameters
for i := range record {
params[header[i]] = strings.TrimSpace(record[i])
if noempty && len(params[header[i]]) == 0 {
log.Fatal("ERROR: empty column ", header[i], " in CSV line ", i)
}
if verbose {
log.Println("Parsed CSV line", line, "column:", header[i], " data:", params[header[i]])
}
}
err = tpl.Execute(os.Stdout, params)
if err != nil {
log.Fatal("ERROR: executing template in CSV line ", line, ": ", err)
}
}
return
}