/
template.go
77 lines (65 loc) · 1.67 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
"text/template"
)
// Generate template for setters file
func generateTemplateForSettersFile(setters []CldSetter) string {
stringTemplate := "package {{ .PackageName}}\n"
functionTemplate := `
func ({{ .Receiver}} *{{ .StructName}}) <<index .FuncName %d>>(<<index .ParamName %d>> <<index .Type %d>>) *{{ .StructName}} {
{{ .Receiver}}.<<index .ParamName %d>> = <<index .ParamName %d>>
return {{ .Receiver}}
}
`
templateData := struct {
FuncName map[int]string
ParamName map[int]string
Type map[int]string
}{
map[int]string{},
map[int]string{},
map[int]string{},
}
for i, t := range setters {
stringTemplate += fmt.Sprintf(functionTemplate, i, i, i, i, i)
templateData.FuncName[i] = strings.Title(t.Param) + t.Suffix
templateData.Type[i] = t.Type
templateData.ParamName[i] = t.Param
}
buf := new(bytes.Buffer)
w := bufio.NewWriter(buf)
tmpl := template.Must(template.New("test").Delims("<<", ">>").Parse(stringTemplate))
if err := tmpl.Execute(w, templateData); err != nil {
panic(err)
}
if err := w.Flush(); err != nil {
panic(err)
}
return buf.String()
}
// Write template to file filling it with type data
func writeTemplateToFile(file io.Writer, templateString string, t *CldType) error {
tmpl := template.Must(template.New("setters").Parse(templateString))
mixinData := struct {
PackageName string
StructName string
Receiver string
}{
t.packageName,
t.structName,
strings.ToLower(t.structName)[0:1],
}
w := bufio.NewWriter(file)
if err := tmpl.Execute(w, mixinData); err != nil {
return err
}
if err := w.Flush(); err != nil {
return err
}
return nil
}