forked from volatiletech/sqlboiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
266 lines (216 loc) · 6.96 KB
/
output.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package boilingcore
import (
"bufio"
"bytes"
"fmt"
"go/format"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"text/template"
"github.com/pkg/errors"
)
var noEditDisclaimer = []byte(`// This file is generated by SQLBoiler (https://github.com/vattle/sqlboiler)
// and is meant to be re-generated in place and/or deleted at any time.
// DO NOT EDIT
`)
var (
// templateByteBuffer is re-used by all template construction to avoid
// allocating more memory than is needed. This will later be a problem for
// concurrency, address it then.
templateByteBuffer = &bytes.Buffer{}
rgxRemoveNumberedPrefix = regexp.MustCompile(`[0-9]+_`)
rgxSyntaxError = regexp.MustCompile(`(\d+):\d+: `)
testHarnessWriteFile = ioutil.WriteFile
)
// generateOutput builds the file output and sends it to outHandler for saving
func generateOutput(state *State, data *templateData) error {
return executeTemplates(executeTemplateData{
state: state,
data: data,
templates: state.Templates,
importSet: state.Importer.Standard,
combineImportsOnType: true,
fileSuffix: ".go",
})
}
// generateTestOutput builds the test file output and sends it to outHandler for saving
func generateTestOutput(state *State, data *templateData) error {
return executeTemplates(executeTemplateData{
state: state,
data: data,
templates: state.TestTemplates,
importSet: state.Importer.TestStandard,
combineImportsOnType: false,
fileSuffix: "_test.go",
})
}
// generateSingletonOutput processes the templates that should only be run
// one time.
func generateSingletonOutput(state *State, data *templateData) error {
return executeSingletonTemplates(executeTemplateData{
state: state,
data: data,
templates: state.SingletonTemplates,
importNamedSet: state.Importer.Singleton,
fileSuffix: ".go",
})
}
// generateSingletonTestOutput processes the templates that should only be run
// one time.
func generateSingletonTestOutput(state *State, data *templateData) error {
return executeSingletonTemplates(executeTemplateData{
state: state,
data: data,
templates: state.SingletonTestTemplates,
importNamedSet: state.Importer.TestSingleton,
fileSuffix: ".go",
})
}
type executeTemplateData struct {
state *State
data *templateData
templates *templateList
importSet imports
importNamedSet map[string]imports
combineImportsOnType bool
fileSuffix string
}
func executeTemplates(e executeTemplateData) error {
if e.data.Table.IsJoinTable {
return nil
}
out := templateByteBuffer
out.Reset()
var imps imports
imps.standard = e.importSet.standard
imps.thirdParty = e.importSet.thirdParty
if e.combineImportsOnType {
imps = combineTypeImports(imps, e.state.Importer.BasedOnType, e.data.Table.Columns)
}
writeFileDisclaimer(out)
writePackageName(out, e.state.Config.PkgName)
writeImports(out, imps)
for _, tplName := range e.templates.Templates() {
if err := executeTemplate(out, e.templates.Template, tplName, e.data); err != nil {
return err
}
}
fName := e.data.Table.Name + e.fileSuffix
if err := writeFile(e.state.Config.OutFolder, fName, out); err != nil {
return err
}
return nil
}
func executeSingletonTemplates(e executeTemplateData) error {
if e.data.Table.IsJoinTable {
return nil
}
out := templateByteBuffer
for _, tplName := range e.templates.Templates() {
out.Reset()
fName := tplName
ext := filepath.Ext(fName)
fName = rgxRemoveNumberedPrefix.ReplaceAllString(fName[:len(fName)-len(ext)], "")
imps := imports{
standard: e.importNamedSet[fName].standard,
thirdParty: e.importNamedSet[fName].thirdParty,
}
writeFileDisclaimer(out)
writePackageName(out, e.state.Config.PkgName)
writeImports(out, imps)
if err := executeTemplate(out, e.templates.Template, tplName, e.data); err != nil {
return err
}
if err := writeFile(e.state.Config.OutFolder, fName+e.fileSuffix, out); err != nil {
return err
}
}
return nil
}
func generateTestMainOutput(state *State, data *templateData) error {
if state.TestMainTemplate == nil {
return errors.New("No TestMain template located for generation")
}
out := templateByteBuffer
out.Reset()
var imps imports
imps.standard = state.Importer.TestMain[state.Config.DriverName].standard
imps.thirdParty = state.Importer.TestMain[state.Config.DriverName].thirdParty
writeFileDisclaimer(out)
writePackageName(out, state.Config.PkgName)
writeImports(out, imps)
if err := executeTemplate(out, state.TestMainTemplate, state.TestMainTemplate.Name(), data); err != nil {
return err
}
if err := writeFile(state.Config.OutFolder, "main_test.go", out); err != nil {
return err
}
return nil
}
// writeFileDisclaimer writes the disclaimer at the top with a trailing
// newline so the package name doesn't get attached to it.
func writeFileDisclaimer(out *bytes.Buffer) {
_, _ = out.Write(noEditDisclaimer)
}
// writePackageName writes the package name correctly, ignores errors
// since it's to the concrete buffer type which produces none
func writePackageName(out *bytes.Buffer, pkgName string) {
_, _ = fmt.Fprintf(out, "package %s\n\n", pkgName)
}
// writeImports writes the package imports correctly, ignores errors
// since it's to the concrete buffer type which produces none
func writeImports(out *bytes.Buffer, imps imports) {
if impStr := buildImportString(imps); len(impStr) > 0 {
_, _ = fmt.Fprintf(out, "%s\n", impStr)
}
}
// writeFile writes to the given folder and filename, formatting the buffer
// given.
func writeFile(outFolder string, fileName string, input *bytes.Buffer) error {
byt, err := formatBuffer(input)
if err != nil {
return err
}
path := filepath.Join(outFolder, fileName)
if err = testHarnessWriteFile(path, byt, 0666); err != nil {
return errors.Wrapf(err, "failed to write output file %s", path)
}
return nil
}
// executeTemplate takes a template and returns the output of the template
// execution.
func executeTemplate(buf *bytes.Buffer, t *template.Template, name string, data *templateData) error {
if err := t.ExecuteTemplate(buf, name, data); err != nil {
return errors.Wrapf(err, "failed to execute template: %s", name)
}
return nil
}
func formatBuffer(buf *bytes.Buffer) ([]byte, error) {
output, err := format.Source(buf.Bytes())
if err == nil {
return output, nil
}
matches := rgxSyntaxError.FindStringSubmatch(err.Error())
if matches == nil {
return nil, errors.Wrap(err, "failed to format template")
}
lineNum, _ := strconv.Atoi(matches[1])
scanner := bufio.NewScanner(buf)
errBuf := &bytes.Buffer{}
line := 1
for ; scanner.Scan(); line++ {
if delta := line - lineNum; delta < -5 || delta > 5 {
continue
}
if line == lineNum {
errBuf.WriteString(">>>> ")
} else {
fmt.Fprintf(errBuf, "% 4d ", line)
}
errBuf.Write(scanner.Bytes())
errBuf.WriteByte('\n')
}
return nil, errors.Wrapf(err, "failed to format template\n\n%s\n", errBuf.Bytes())
}