forked from Khan/genqlient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
59 lines (53 loc) · 1.34 KB
/
template.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
package generate
import (
"io"
"path/filepath"
"runtime"
"strings"
"text/template"
)
var (
// TODO(benkraft): Embed templates into the binary, see
// https://github.com/suhabe/genqlient/issues/9.
_, thisFilename, _, _ = runtime.Caller(0)
thisDir = filepath.Dir(thisFilename)
)
func repeat(n int, s string) string {
var builder strings.Builder
for i := 0; i < n; i++ {
builder.WriteString(s)
}
return builder.String()
}
func intRange(n int) []int {
ret := make([]int, n)
for i := 0; i < n; i++ {
ret[i] = i
}
return ret
}
func sub(x, y int) int { return x - y }
// render executes the given template with the funcs from this generator.
func (g *generator) render(tmplRelFilename string, w io.Writer, data interface{}) error {
tmpl := g.templateCache[tmplRelFilename]
if tmpl == nil {
absFilename := filepath.Join(thisDir, tmplRelFilename)
funcMap := template.FuncMap{
"ref": g.ref,
"repeat": repeat,
"intRange": intRange,
"sub": sub,
}
var err error
tmpl, err = template.New(tmplRelFilename).Funcs(funcMap).ParseFiles(absFilename)
if err != nil {
return errorf(nil, "could not load template %v: %v", absFilename, err)
}
g.templateCache[tmplRelFilename] = tmpl
}
err := tmpl.Execute(w, data)
if err != nil {
return errorf(nil, "could not render template: %v", err)
}
return nil
}