-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtemplate.go
215 lines (176 loc) · 4.61 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package genus
import (
"bytes"
"errors"
"fmt"
gofmt "go/format"
"io/ioutil"
"log"
"os"
"path/filepath"
"text/template"
goimports "golang.org/x/tools/imports"
)
var defaultHeader = []byte(`package {{ .Package }}
{{ with .Imports }}
import (
{{- range $k, $v := . }}
{{- $v -}} "{{- $k -}}"
{{ end -}}
)
{{ end }}
`)
// Represents single Go file
type Template struct {
Name string // template name
Source string // source path
TargetDir string // target directory
Filename string // filename of generated code
SkipExists bool // skip generation if exist
SkipFormat bool // skip go format
SkipFixImports bool // skip generation if exist
header []byte
rawTemplate []byte // rawTemplate data in bytes
rawResult []byte
}
// Set raw template data
func (tmpl *Template) SetRawTemplate(raw []byte) (data []byte) {
tmpl.rawTemplate = raw
return raw
}
func (tmpl *Template) RenderPartial(data interface{}) (result []byte, err error) {
_, err = tmpl.load()
if err != nil {
return nil, err
}
return tmpl.renderPartial(data)
}
// Render template by context
func (tmpl *Template) renderPartial(context interface{}) (data []byte, err error) {
rawTemplate := fmt.Sprintf("{{ with .Data }}%s{{ end -}}", string(tmpl.rawTemplate))
parsed, parsedErr := template.New(tmpl.Name).Funcs(GoHelperFuncs).Parse(string(rawTemplate))
if parsedErr != nil {
return nil, parsedErr
}
buf := bytes.NewBuffer([]byte{})
if execErr := parsed.Execute(buf, context); execErr != nil {
return nil, execErr
}
data = buf.Bytes()
tmpl.rawResult = data
return
}
// Render template by given data
func (tmpl *Template) Render(data interface{}) (result []byte, err error) {
_, err = tmpl.load()
if err != nil {
return nil, err
}
result, err = tmpl.render(data)
if err != nil {
return
}
result, err = tmpl.format()
if err != nil {
return
}
err = tmpl.write()
if err != nil {
return nil, err
}
result, err = tmpl.fixImports()
if err != nil {
return nil, err
}
return
}
// Fix format of rawResult
func (tmpl *Template) format() (data []byte, err error) {
if tmpl.SkipFormat {
return tmpl.rawResult, nil
}
data, err = gofmt.Source(tmpl.rawResult)
if err != nil {
return nil, err
}
tmpl.rawResult = data
return
}
func (tmpl *Template) fixImports() (data []byte, err error) {
if tmpl.SkipFixImports {
return tmpl.rawResult, nil
}
data, err = goimports.Process(filepath.Join(tmpl.TargetDir, tmpl.Filename), tmpl.rawResult, &goimports.Options{Comments: true})
if err != nil {
return nil, err
}
tmpl.rawResult = data
if err = tmpl.write(); err != nil {
return nil, err
}
return
}
// Load data from file if rawTemplate is not set
func (tmpl *Template) load() (data []byte, err error) {
if len(tmpl.rawTemplate) <= 0 {
log.Printf("raw template %s not set, loading from file %s", tmpl.Name, tmpl.Source)
return tmpl.loadFile()
}
return tmpl.rawTemplate, nil
}
// Load raw template data from file
func (tmpl *Template) loadFile() (data []byte, err error) {
if tmpl.Source == "" {
return nil, errors.New("Empty source path")
}
data, err = ioutil.ReadFile(tmpl.Source)
if err != nil {
return nil, err
}
tmpl.rawTemplate = data
return
}
// Render template by context
func (tmpl *Template) render(context interface{}) (data []byte, err error) {
if len(tmpl.header) <= 0 {
tmpl.header = defaultHeader
}
withHeader := fmt.Sprintf("%s{{ with .Data }}%s{{ end -}}", string(tmpl.header), string(tmpl.rawTemplate))
parsed, parsedErr := template.New(tmpl.Name).Funcs(GoHelperFuncs).Parse(withHeader)
if parsedErr != nil {
return nil, parsedErr
}
buf := bytes.NewBuffer([]byte{})
if execErr := parsed.Execute(buf, context); execErr != nil {
return nil, execErr
}
data = buf.Bytes()
fbuf := bytes.NewBuffer([]byte{})
err = template.Must(template.New("filename").Funcs(GoHelperFuncs).Parse(fmt.Sprintf("{{- with .Data -}} %s {{- end -}}", tmpl.Filename))).Execute(fbuf, context)
if err != nil {
return nil, err
}
if len(fbuf.Bytes()) > 0 {
tmpl.Filename = string(fbuf.Bytes())
}
tmpl.rawResult = data
return
}
// Write rawResult to file
func (tmpl *Template) write() (err error) {
if tmpl.TargetDir == "" {
return
}
path := filepath.Join(tmpl.TargetDir, tmpl.Filename)
log.Printf("Joining filepath = <%s> + <%s>", tmpl.TargetDir, tmpl.Filename)
if _, err := os.Stat(path); err == nil && tmpl.SkipExists {
return nil
}
log.Printf("Creating directory <%s>", tmpl.TargetDir)
err = os.MkdirAll(tmpl.TargetDir, 0777)
if err != nil {
return err
}
log.Printf("Writing to file <%s>", path)
return ioutil.WriteFile(path, tmpl.rawResult, 0666)
}