-
Notifications
You must be signed in to change notification settings - Fork 5
/
generator.go
67 lines (59 loc) · 1.28 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
65
66
67
//go:build !tinygo.wasm
package sqlla
import (
"bytes"
"embed"
"go/format"
"io"
"log"
"strings"
"text/template"
"github.com/Masterminds/goutils"
"github.com/pkg/errors"
"github.com/serenize/snaker"
)
//go:embed template/*
var templates embed.FS
//go:embed template/table.tmpl
var tableTmpl []byte
var tmpl = template.New("table")
func init() {
tmpl = tmpl.Funcs(
template.FuncMap{
"Title": func(s string) string {
return goutils.Capitalize(s)
},
"Untitle": func(s string) string {
return goutils.Uncapitalize(s)
},
"toLower": strings.ToLower,
"toSnake": snaker.CamelToSnake,
"toCamel": snaker.SnakeToCamel,
},
)
var err error
tmpl, err = tmpl.ParseFS(templates, "template/*.tmpl")
if err != nil {
log.Fatal(err)
}
tmpl, err = tmpl.Parse(string(tableTmpl))
if err != nil {
log.Fatal(err)
}
}
func WriteCode(w io.Writer, table *Table) error {
buf := new(bytes.Buffer)
err := tmpl.Execute(buf, table)
if err != nil {
return errors.Wrapf(err, "fail to render")
}
bs, err := format.Source(buf.Bytes())
if err != nil {
if _, err := w.Write(buf.Bytes()); err != nil {
return errors.Wrapf(err, "fail to write: table=%s", table.Name)
}
return errors.Wrapf(err, "fail to format: table=%s", table.Name)
}
_, err = w.Write(bs)
return err
}