-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
64 lines (57 loc) · 1.3 KB
/
generator.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
package h24w17
import (
"os"
"path"
"strings"
"text/template"
)
type Generator struct {
driverTmpl *template.Template
stmtTmpl *template.Template
data data
}
type data struct {
PackageName string
CachePlanRaw string
TableSchemaRaw string
}
func NewGenerator(cachePlanRaw string, tableSchemaRaw string) *Generator {
return &Generator{
driverTmpl: template.Must(template.ParseFiles("template/driver.tmpl")),
stmtTmpl: template.Must(template.ParseFiles("template/stmt.tmpl")),
data: data{CachePlanRaw: escapeGoString(cachePlanRaw), TableSchemaRaw: escapeGoString(tableSchemaRaw)},
}
}
func (g *Generator) Generate(destDir string) {
g.data.PackageName = path.Base(destDir)
driver, err := os.Create(path.Join(destDir, "driver.go"))
if err != nil {
panic(err)
}
defer driver.Close()
stmt, err := os.Create(path.Join(destDir, "stmt.go"))
if err != nil {
panic(err)
}
err = g.driverTmpl.Execute(driver, g.data)
if err != nil {
panic(err)
}
err = g.stmtTmpl.Execute(stmt, g.data)
if err != nil {
panic(err)
}
}
func escapeGoString(s string) string {
split := strings.Split(s, "`")
var b strings.Builder
b.WriteByte('`')
for i, v := range split {
b.WriteString(v)
if i != len(split)-1 {
b.WriteString("` + \"`\" + `")
}
}
b.WriteByte('`')
return b.String()
}