-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
97 lines (74 loc) · 1.77 KB
/
main.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
package main
import (
"encoding/csv"
"fmt"
"os"
"text/template"
"github.com/spf13/cobra"
)
var templateFile string
func main() {
var rootCmd = &cobra.Command{
Use: "tmplgen",
Run: run,
}
rootCmd.Flags().StringVarP(&templateFile, "template-file", "t", "", "template in text/template format")
rootCmd.Execute()
}
func exitWithError(msg string, err error) {
fmt.Fprintf(os.Stderr, "%v: %v\n", msg, err)
os.Exit(1)
}
func run(cmd *cobra.Command, args []string) {
if templateFile == "" {
exitWithError("parameter error", fmt.Errorf("template-file not specified"))
}
var data csvData
var funcs = template.FuncMap{
"field": data.lookupValue,
}
t, err := template.New("main").Funcs(funcs).ParseFiles(templateFile)
if err != nil {
exitWithError("error parsing template", err)
}
rdr := csv.NewReader(os.Stdin)
rdr.Comment = '#'
rdr.LazyQuotes = true
rdr.TrimLeadingSpace = true
records, err := rdr.ReadAll()
if err != nil {
exitWithError("error reading csv input", err)
}
err = data.init(records)
if err != nil {
exitWithError("error processing input data", err)
}
err = t.Templates()[0].Execute(os.Stdout, data)
if err != nil {
exitWithError("error executing template", err)
}
}
type csvData struct {
Fields []string
Records [][]string
fieldMap map[string]int
}
func (d *csvData) init(records [][]string) error {
if len(records) == 0 {
return fmt.Errorf("no records provided")
}
d.Fields = records[0]
d.Records = records[1:]
d.fieldMap = make(map[string]int)
for i, f := range d.Fields {
d.fieldMap[f] = i
}
return nil
}
func (d *csvData) lookupValue(record []string, field string) (string, error) {
if idx, ok := d.fieldMap[field]; ok {
return record[idx], nil
} else {
return "", fmt.Errorf("could not find field %q", field)
}
}