|
Generate Go code using templates
What?
This go application reads in the user supplied definition (or structure) of a CSV file, and generates 'reader.go', a fully working go application that reads that CSV file. It does this using the nifty template feature of Go.
If you want to customize the resulting code, then just change the template reader.tpl . Or for a another CSV file, just change the description.txt .
Prerequisite
To run this aardvark.code example you need to have following software installed on your system:
Go aardvark
Grab this aardvark.code file:
wget http://data.munging.ninja/aardvarkcode/codegen/aardvark.code
Execute
Stage 1
Read a .txt file and turn it into a Go Descriptor object which contains a Col object per column definition.
The structure as defined in the description.txt file
3
4
5
6
7
8
9
10
11
12
13
14
| EntityName:City
0 Geonameid int
1 Name string
2 Asciiname string
4 Lat float64 # latitude
5 Lon float64 # longitude
8 Country string
14 Population int
16 Elevation float64
Filename:/u01/data/20150102_cities/cities1000.txt
Separator:\t
|
.. will look like this Go Descriptor object
{
EntityName:City
Filename:/u01/data/20150102_cities/cities1000.txt
Separator:\t
Numcols:8
Cols:[
{Position:0 Identifier:Geonameid Type:int ConversionFlag:true }
{Position:1 Identifier:Name Type:string ConversionFlag:false}
{Position:2 Identifier:Asciiname Type:string ConversionFlag:false}
{Position:4 Identifier:Lat Type:float64 ConversionFlag:true }
{Position:5 Identifier:Lon Type:float64 ConversionFlag:true }
{Position:8 Identifier:Country Type:string ConversionFlag:false}
{Position:14 Identifier:Population Type:int ConversionFlag:true }
{Position:16 Identifier:Elevation Type:float64 ConversionFlag:true }
]
}
Stage 2
Read in the template 'reader.tpl', apply above data to it, and put the result in the file 'reader.go'.
I'm just going to lift the veil a bit, by showing what the following snippet of the template does, for more information about Go's template feature refer to the documentation: golang.org/pkg/text/template
When you apply the data to this template snipppet ..
type «.EntityName» struct {
«range .Cols» «.Identifier» «.Type»
«end»}
.. this output will be produced:
type City struct {
Geonameid int
Name string
Asciiname string
Lat float64
Lon float64
Country string
Population int
Elevation float64
}
For your own enlightenment, look for other «...» expressions in the 'reader.tpl' file, and see the code it generates in 'reader.go'.
Stage 3
Compile the 'reader.go' file, which reads in the CSV file, and shows a couple of records.
The aardvark.code
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
| ##== tmp/description.txt ========================================
EntityName:City
0 Geonameid int
1 Name string
2 Asciiname string
4 Lat float64 # latitude
5 Lon float64 # longitude
8 Country string
14 Population int
16 Elevation float64
Filename:/u01/data/20150102_cities/cities1000.txt
Separator:\t
##== tmp/reader.tpl ========================================
package main
import (
"os"
"strconv"
"bufio"
"fmt"
"io"
"strings"
)
func main() {
filename:="«.Filename»"
f,err := os.Open(filename)
defer f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "Opening file %q: %s\n", filename,err.Error())
os.Exit(1)
}
r:=bufio.NewReader(f)
repeat:=true
ignoredLines:=0
list:=make([]«.EntityName»,0,0)
for repeat {
line,overflow,err := r.ReadLine()
repeat = (err!=io.EOF) // EOF means stop repeating this loop
if err != nil && err!=io.EOF {
fmt.Fprintf(os.Stderr, "Read error: %s\n", err.Error())
break
}
if overflow {
fmt.Fprintf(os.Stderr, "Overflow error on reading!\n")
break
}
recs:=strings.Split(string(line),"«.Separator»")
if len(recs)>«.Numcols» {
row,err:=extract( strings.Split(string(line),"«.Separator»"))
if err!=nil {
// assume error already reported
break
}
list=append(list,row)
} else {
ignoredLines+=1
}
}
if ignoredLines>0 {
fmt.Fprintf(os.Stderr, "Warning: %v line(s) ignored because of too few fields.\n",ignoredLines)
}
for i,r:=range(list) {
fmt.Printf("%v\n",r)
if i>10 {
break
}
}
}
type «.EntityName» struct {
«range .Cols» «.Identifier» «.Type»
«end»}
func extract(rec []string) (record «.EntityName»,err error) {
«range .Cols»«if .ConversionFlag»«template "convert" .»«else» _«.Identifier» := rec[«.Position»]«end»
«end»
record = «.EntityName»{ «range .Cols»«.Identifier»:_«.Identifier», «end»}
return
}
«define "convert"»«if eq .Type "int"» _«.Identifier»:=0
if len(rec[«.Position»])>0 {
_«.Identifier»,err=strconv.Atoi(rec[«.Position»])
if err != nil {
fmt.Fprintf(os.Stderr, "Error converting «.Identifier»: %v\n", err.Error())
return
}
}«end»«if eq .Type "float64"» _«.Identifier»:=0.0
if len(rec[«.Position»])>0 {
_«.Identifier»,err=strconv.ParseFloat(rec[«.Position»],64)
if err != nil {
fmt.Fprintf(os.Stderr, "Error converting «.Identifier»: %v\n", err.Error())
return
}
}«end»«end»
##== tmp/grok.go ========================================
package main
import (
"fmt"
"bufio"
"os"
"regexp"
"io/ioutil"
"strings"
"strconv"
"text/template"
)
type Descriptor struct {
EntityName string
Filename string
Separator string
Numcols int
Cols []Col
}
type Col struct {
Position int
Identifier string
Type string
ConversionFlag bool
}
func main() {
d,err:=getDescriptor("tmp/description.txt") // read the description
if err != nil {
os.Exit(1)
}
fmt.Printf("%+v\n",d) // DROPME TODO
f,err:=os.Create("tmp/reader.go") // prepare file for output
if err != nil {
fmt.Fprintf(os.Stderr, "File open error: %s\n", err.Error())
os.Exit(1)
}
defer f.Close()
w:=bufio.NewWriter(f)
t:=template.New("reader.tpl") // create template
t.Delims("«","»")
t=template.Must(t.ParseFiles("tmp/reader.tpl"))
err=t.Execute(w,d) // execute the template
if err!=nil {
fmt.Fprintf(os.Stderr, "Template execute error: %s\n", err.Error())
}
w.Flush()
}
func getDescriptor(filename string) (desc Descriptor, err error) {
desc=Descriptor{ EntityName:"x" }
content, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "File read error: %s\n", err.Error())
}
body:=strings.TrimSpace(strings.Replace( string(content), "\n","|",-1) )
// regular expressions matching 1) key:value pair 2) fields line
reKeyValue := regexp.MustCompile(`^\s*(\w+)\s*:\s*(\S+).*`)
reFields := regexp.MustCompile(`^\s*(\d+)\s*(\w+)\s*(\w+).*`)
desc.Cols = make([]Col, 0, 0)
for _,line:= range strings.Split(body,"|") {
if n:=strings.Index(line,"#"); n>-1 { // remove comments
line=line[:n]
}
line=strings.TrimSpace(line) // empty string?
if len(line)<=1 {
continue
}
group:=reKeyValue.FindStringSubmatch(line) // pattern: key:value
if group!=nil {
digestKeyValue(&desc, group)
continue
}
group=reFields.FindStringSubmatch(line) // pattern: num word word
if group!=nil {
err=digestFields(&desc, group)
if err!=nil {
break
}
}
}
desc.Numcols=len(desc.Cols)
return
}
func digestKeyValue(desc *Descriptor, group []string) {
k:= group[1]
v:= group[2]
if (k=="EntityName") {
desc.EntityName=v
} else if (k=="Filename") {
desc.Filename=v
} else if (k=="Separator") {
desc.Separator=v
} else {
fmt.Fprintf(os.Stderr, "WARNING: Key:Value pair %v:%v ignored\n", k,v)
}
}
func digestFields(desc *Descriptor, group []string) (err error) {
p,err:=strconv.Atoi(group[1])
if err != nil {
fmt.Fprintf(os.Stderr, "Conversion error: %s\n", err.Error())
return
}
id:=group[2]
desc.Cols=append(desc.Cols, Col{ Position:p,
Identifier:id,
Type: group[3],
ConversionFlag: group[3]!="string" })
return
}
##== aardvark.sh ========================================
#!/bin/bash
rm grok tmp/reader.go reader # cleanup
go build tmp/grok.go # build the code-generator
if [ -x ./grok ]
then
./grok
fi
if [ -f ./tmp/reader.go ]
then
go build tmp/reader.go # build the generated go code
./reader # and execute
fi
|
| |