-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgotmpl.go
67 lines (62 loc) · 1.56 KB
/
gotmpl.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
package generator
import (
"bytes"
"go/format"
"io/ioutil"
"text/template"
"unicode"
"github.com/dyweb/gommon/errors"
"github.com/dyweb/gommon/util/fsutil"
"github.com/dyweb/gommon/util/genutil"
)
type GoTemplateConfig struct {
Src string `yaml:"src"`
Dst string `yaml:"dst"`
Go bool `yaml:"go"`
Data interface{} `yaml:"data"`
}
func (c *GoTemplateConfig) Render(root string) error {
var (
b []byte
buf bytes.Buffer
err error
t *template.Template
)
//log.Infof("data is %v", c.Data)
if b, err = ioutil.ReadFile(join(root, c.Src)); err != nil {
return errors.Wrap(err, "can't read template file")
}
if t, err = template.New(c.Src).
Funcs(template.FuncMap{
"UcFirst": UcFirst,
}).
Parse(string(b)); err != nil {
return errors.Wrap(err, "can't parse template")
}
buf.WriteString(genutil.DefaultHeader(join(root, c.Src)))
if err = t.Execute(&buf, c.Data); err != nil {
return errors.Wrap(err, "can't render template")
}
if c.Go {
if b, err = format.Source(buf.Bytes()); err != nil {
return errors.Wrap(err, "can't format as go code")
}
} else {
b = buf.Bytes()
}
if err = fsutil.WriteFile(join(root, c.Dst), b); err != nil {
return err
}
log.Debugf("rendered go tmpl %s to %s", join(root, c.Src), join(root, c.Dst))
return nil
}
// UcFirst change first character to upper case.
// It is based on https://github.com/99designs/gqlgen/blob/master/codegen/templates/templates.go#L205
func UcFirst(s string) string {
if s == "" {
return ""
}
r := []rune(s)
r[0] = unicode.ToUpper(r[0])
return string(r)
}