-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvt.go
109 lines (92 loc) · 1.8 KB
/
csvt.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
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"strings"
"text/template"
)
func processCSVFile(filename string, noHeader bool, t *template.Template) {
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
r := csv.NewReader(f)
r.Comma = ','
r.Comment = '#'
records, err := r.ReadAll()
if err != nil {
panic(err)
}
var header []string
switch len(records) {
case 0:
return
case 1:
if !noHeader {
return
}
t.Execute(os.Stdout, records[0])
default:
if noHeader {
for _, tuple := range records {
t.Execute(os.Stdout, tuple)
}
return
}
header = records[0]
for i, h := range header {
header[i] = strings.Map(func(r rune) rune {
switch r {
case ' ', '\t', '\n', '\r':
return -1
case '/', '\\', '-', '+':
return '_'
default:
return r
}
}, strings.ToLower(h))
}
tupleMap := make(map[string]any, len(header))
data := records[1:]
n := len(data)
for i, tuple := range data {
tupleMap["meta"] = map[string]any {
"index": i,
"first": i == 0,
"last": i >= n-1,
}
for i, h := range header {
tupleMap[h] = tuple[i]
}
t.Execute(os.Stdout, tupleMap)
}
}
}
func main() {
var templ string
var noHeader bool
flag.StringVar(&templ, "t", "", "output template")
flag.BoolVar(&noHeader, "no-header", false, "input has no header line")
flag.Parse()
if templ == "" {
_, _ = fmt.Fprint(os.Stderr, "no template")
os.Exit(1)
}
t := template.Must(template.New("template").Funcs(map[string]any{
"quote_literal": func (c string) string {
return "'" + strings.ReplaceAll(c, "'", "''") + "'"
},
"newline": func () string {
return "\n"
},
"nl": func () string {
return "\n"
},
}).Parse(templ))
for _, f := range flag.Args() {
processCSVFile(f, noHeader, t)
}
}