forked from tkrajina/ftmpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
458 lines (391 loc) · 12.7 KB
/
main.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package ftmplting
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"sort"
"strings"
)
const (
cmdPrefix = "!#"
cmdNocompile = "!#nocompile"
cmdArg = "!#arg"
cmdEscape = "!#escape"
cmdImport = "!#import"
cmdErrorif = "!#errif"
cmdReturn = "!#return"
cmdSub = "!#sub"
cmdExtends = "!#extends"
cmdInclude = "!#include"
cmdInsert = "!#insert"
cmdGlobal = "!#global"
)
type Params struct {
SourceDir string
TargetDir string
TargetGoFile string
FuncPrefix string
FuncPrefixErr string
}
type compiledTemplate struct {
imports []string
originalFile string
functionCode string
}
var exclamationMarkFixRegex = regexp.MustCompile("{{.*?}}\\!")
var templateReplacementRegex = regexp.MustCompile("{{.*?}}")
var fmtFormatRegex = regexp.MustCompile("\\%.*?\\w\\s+")
func Do(ap Params) {
var compiledTemplates []compiledTemplate
fileInfos, err := ioutil.ReadDir(ap.SourceDir)
HandleError(err, "Error listing directory")
var files []string
for _, fileInfo := range fileInfos {
files = append(files, fileInfo.Name())
}
sort.Strings(files)
for _, fileName := range files {
if strings.HasSuffix(fileName, ".tmpl") {
params := convertTemplateParams{
NoerrFuncPrefix: ap.FuncPrefix,
ErrFuncPrefix: ap.FuncPrefixErr,
}
compiled := convertTemplate(ap.SourceDir, fileName, params)
if len(ap.TargetDir) > 0 {
_, fileName := getLastPathElements(fileName)
fileName = strings.Replace(fileName, ".tmpl", ".go", -1)
fileName = path.Join(ap.TargetDir, fileName)
if len(compiled.functionCode) > 0 {
saveTemplates(fileName, compiled)
}
} else {
compiledTemplates = append(compiledTemplates, compiled)
}
}
}
if len(ap.TargetGoFile) > 0 {
saveTemplates(ap.TargetGoFile, compiledTemplates...)
}
}
func printfWarning(str string, args ...interface{}) {
if !strings.HasSuffix(str, "\n") {
str += "\n"
}
fmt.Fprintln(os.Stderr, "----------------------------------------------------------------------------------------------------")
fmt.Fprintf(os.Stderr, str, args...)
fmt.Fprintln(os.Stderr, "----------------------------------------------------------------------------------------------------")
}
func saveTemplates(destination string, compiled ...compiledTemplate) {
fmt.Sprintln("destination=", destination)
if f, err := os.Open(destination); err == nil {
var bytes = make([]byte, 200)
_, _ = f.Read(bytes)
previousVersion := regexp.MustCompile("{{{.*?}}}").Find(bytes)
if len(previousVersion) == 0 {
printfWarning("Previous version not found in %s!\n", destination)
} else {
prev := strings.Replace(string(previousVersion), "{{{", "", 1)
prev = strings.Replace(prev, "}}}", "", 1)
if prev != VERSION {
printfWarning("%s was previously compiled with %s, new version is %s!\n", destination, prev, VERSION)
}
}
}
var imports []string
for _, c := range compiled {
imports = append(imports, c.imports...)
}
imports = append(imports, "\"fmt\"", "\"os\"")
imports = rmDoubleImports(imports)
pathElem1, pathElem2 := getLastPathElements(destination)
packageName := pathElem2
if strings.Contains(pathElem2, ".go") {
packageName = pathElem1
}
fOut, err := os.Create(destination)
HandleError(err, "Error creating file")
defer func() { _ = fOut.Close() }()
_, _ = fOut.WriteString("// Package " + packageName + " is generated with ftmpl {{{" + VERSION + "}}}, do not edit!!!! */\n")
_, _ = fOut.WriteString("package " + packageName + "\n\n")
_, _ = fOut.WriteString("import (\n")
for _, i := range imports {
_, _ = fOut.WriteString(i + "\n")
}
_, _ = fOut.WriteString(")\n\n")
_, _ = fOut.WriteString(initFunctionTemplate)
_, _ = fOut.WriteString("\n\n")
for _, c := range compiled {
_, _ = fOut.WriteString("\n\n")
_, _ = fOut.WriteString(c.functionCode)
fmt.Printf("%-15s -> %-15s\n", c.originalFile, destination)
}
cmd := exec.Command("go", "fmt", destination)
bytes, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(os.Stderr, strings.Join(cmd.Args, " "))
fmt.Fprintf(os.Stderr, "Cannot format %s: %s\n\n", destination, err.Error())
parseGoFmtErrorOutput(bytes)
}
}
func processExtending(pckg string, chunks []string) []string {
extendingTemplate := ""
for _, chunk := range chunks {
if strings.HasPrefix(chunk, cmdExtends) {
extendingTemplate = strings.TrimSpace(chunk[len(cmdExtends):])
}
}
if len(extendingTemplate) == 0 {
return chunks
}
// Load base template:
mainTemplateLines := loadTemplateAndGetChunks(path.Join(pckg, extendingTemplate)+".tmpl", false)
// Parse sub template chunks:
subTemplateCode, subTemplateChunks := loadTemplateSubChunks(chunks)
var usedSubtemplateChunks = map[string]bool{}
for k := range subTemplateChunks {
usedSubtemplateChunks[k] = false
}
// Merge them together:
var result []string
var subTemplateArgsCode []string
for _, chunk := range subTemplateCode {
if strings.HasPrefix(chunk, cmdArg) {
subTemplateArgsCode = append(subTemplateArgsCode, chunk)
} else {
result = append(result, chunk)
}
}
for _, chunk := range mainTemplateLines {
if strings.HasPrefix(chunk, cmdInclude) {
subName := strings.TrimSpace(chunk[len(cmdInclude):])
if subLines, found := subTemplateChunks[subName]; found {
usedSubtemplateChunks[subName] = true
for _, subChunk := range subLines {
result = append(result, subChunk)
}
}
} else {
result = append(result, chunk)
}
}
// This is because we want the subtemplate args to be after the base template args in the function definition:
for _, chunk := range subTemplateArgsCode {
result = append(result, chunk)
}
for name, used := range usedSubtemplateChunks {
if !used {
printfWarning("Sub %s is declared but never used", name)
}
}
return result
}
func loadTemplateSubChunks(lines []string) (general []string, subsections map[string][]string) {
subReached := false
currentSubName := ""
general = make([]string, 0)
subsections = make(map[string][]string)
for _, chunk := range lines {
if strings.Contains(chunk, cmdSub) {
subReached = true
currentSubName = strings.TrimSpace(chunk[len(cmdSub):])
} else if subReached {
if _, found := subsections[currentSubName]; !found {
subsections[currentSubName] = make([]string, 0)
}
subsections[currentSubName] = append(subsections[currentSubName], chunk)
} else {
general = append(general, chunk)
}
}
return general, subsections
}
func getChunks(str string) []string {
delimiter := "<<<" + getRandomString(15) + ">>>"
res := ""
chunks := strings.Split(str, "\n")
for n, chunk := range chunks {
if n < len(chunks)-1 {
chunk += "\n"
}
//fmt.Printf("line=%s\n", line)
if len(chunk) == 0 {
} else if strings.HasPrefix(chunk, "!!") {
res += chunk
} else if chunk[0] == '!' {
res += delimiter + chunk + delimiter
} else {
chunk = exclamationMarkFixRegex.ReplaceAllStringFunc(chunk, func(s string) string {
return s + "!"
})
res += templateReplacementRegex.ReplaceAllStringFunc(chunk, func(s string) string {
s = strings.TrimSpace(s[2 : len(s)-2])
if len(s) == 0 {
return ""
}
if s[0] == '!' {
return delimiter + s + delimiter
}
forceUnquoted := false
if s[0] == '=' {
forceUnquoted = true
s = s[1:]
}
placeholder := "%v"
var valueExpr string
if len(s) > 0 && s[0] == '%' {
placeholders := fmtFormatRegex.FindAllString(s, -1)
if len(placeholders) == 0 {
panic("Cannot find valid fmt format in:" + s)
}
placeholder = placeholders[0]
valueExpr = s[len(placeholder):]
} else if len(s) > 1 && s[1] == ' ' {
valueExpr = s[1:]
placeholder = "%" + string(s[0])
} else {
valueExpr = s
}
placeholder = strings.TrimSpace(placeholder)
valueExpr = strings.TrimSpace(valueExpr)
if !forceUnquoted && strings.HasSuffix(placeholder, "s") {
valueExpr = "_escape(" + valueExpr + ")"
}
if strings.HasPrefix(s, "/*") && strings.HasSuffix(s, "*/") {
return ""
}
return fmt.Sprintf("%s!_w(fmt.Sprintf(`%s`, %s))%s", delimiter, placeholder, valueExpr, delimiter)
})
}
}
return strings.Split(res, delimiter)
}
// Loads the file and process it to get chunks.
//
// Note that "line" is not always a chunk from the template it is part of the template which will be converted to a line of code.
func loadTemplateAndGetChunks(fileName string, keepNoCompile bool) []string {
str, err := loadFile(fileName)
HandleError(err, "Error reading "+fileName)
chunks := getChunks(str)
// Process inserted templates:
var expandedChunks []string
for _, chunk := range chunks {
if !keepNoCompile && strings.HasPrefix(chunk, cmdNocompile) {
// Nothing
} else if strings.HasPrefix(chunk, cmdInsert) {
dir, _ := path.Split(fileName)
fileToInsert := chunk[len(cmdInsert):]
fileToInsert = strings.Trim(strings.TrimSpace(fileToInsert), "\"")
fileToInsert = path.Join(dir, fileToInsert)
expandedChunks = append(expandedChunks, loadTemplateAndGetChunks(fileToInsert, false)...)
} else {
expandedChunks = append(expandedChunks, chunk)
}
}
return expandedChunks
}
type convertTemplateParams struct {
ErrFuncPrefix, NoerrFuncPrefix string
}
func convertTemplate(packageDir, file string, params convertTemplateParams) compiledTemplate {
chunks := loadTemplateAndGetChunks(path.Join(packageDir, file), true)
// Some templates don't need to be "compiled" (for example base templates)
for _, chunk := range chunks {
if strings.HasPrefix(chunk, cmdNocompile) {
return compiledTemplate{}
}
}
result := compiledTemplate{}
result.originalFile = file
chunks = processExtending(packageDir, chunks)
if len(params.ErrFuncPrefix) == 0 {
params.ErrFuncPrefix = "TEMPLATEERR"
}
if len(params.NoerrFuncPrefix) == 0 {
params.NoerrFuncPrefix = "TEMPLATE"
}
funcName := strings.Replace(file, ".tmpl", "", -1)
tmplParams := templateParams{
ErrFuncPrefix: params.ErrFuncPrefix,
NoerrFuncPrefix: params.NoerrFuncPrefix,
FuncName: funcName,
TemplateFile: file,
EscapeFunc: "html.EscapeString",
}
for _, chunk := range chunks {
if strings.HasPrefix(chunk, cmdPrefix) {
// Remove spaces after !#
chunk = cmdPrefix + strings.TrimSpace(chunk[len(cmdPrefix):])
}
if strings.HasPrefix(chunk, cmdArg) {
tmplParams.Args = append(tmplParams.Args, strings.TrimSpace(chunk[len(cmdArg):]))
} else if strings.HasPrefix(chunk, cmdGlobal) {
tmplParams.GlobalCode += strings.TrimSpace(chunk[len(cmdEscape):]) + "\n"
} else if strings.HasPrefix(chunk, cmdEscape) {
tmplParams.EscapeFunc = strings.TrimSpace(chunk[len(cmdEscape):])
} else if strings.HasPrefix(chunk, cmdImport) {
result.imports = append(result.imports, strings.TrimSpace(chunk[len(cmdImport):]))
} else if strings.HasPrefix(chunk, cmdReturn) {
tmplParams.Lines = append(tmplParams.Lines, "return _ftmpl.String(), nil")
} else if strings.HasPrefix(chunk, cmdErrorif) {
parts := strings.Split(chunk[len(cmdErrorif):], "???")
expression := parts[0]
message := fmt.Sprintf("Error checking %s", expression)
if len(parts) > 1 {
message = strings.TrimSpace(parts[1])
}
var errBuffer bytes.Buffer
err := errorTemplate.Execute(&errBuffer, errParams{Expression: expression, Message: message})
handleLineError(err, chunk)
tmplParams.Lines = append(tmplParams.Lines, errBuffer.String())
} else if strings.HasPrefix(chunk, "!#") {
// Ignore
} else if strings.HasPrefix(chunk, "!!") {
chunk = chunk[1:]
if l, ok := handleTemplateLine(chunk); ok {
tmplParams.Lines = append(tmplParams.Lines, l)
}
} else if strings.HasPrefix(chunk, "!") {
tmplParams.Lines = append(tmplParams.Lines, prepareCommandLine(chunk[1:]))
} else {
if l, ok := handleTemplateLine(chunk); ok {
tmplParams.Lines = append(tmplParams.Lines, l)
}
}
}
if len(tmplParams.EscapeFunc) == 0 {
tmplParams.EscapeFunc = defaultQuoteTemplate
}
result.imports = append(result.imports, "\"bytes\"", "\"errors\"", "\"html\"", "\"fmt\"")
tmplParams.Args = rmDoubleImports(tmplParams.Args)
var buf bytes.Buffer
err := generatorTemplate.Execute(&buf, tmplParams)
HandleError(err, "Error executing template")
result.functionCode = buf.String()
return result
}
func prepareCommandLine(chunk string) string {
chunk = strings.TrimSpace(chunk)
if (strings.HasPrefix(chunk, "if ") || strings.HasPrefix(chunk, "for ")) && !strings.HasSuffix(chunk, "{") {
chunk += "{"
}
if chunk == "else" {
chunk = "} else {"
}
if chunk == "end" {
chunk = "}"
}
if matches, _ := regexp.Match("else\\s+if.*", []byte(chunk)); matches && !strings.HasSuffix(chunk, "{") {
chunk = fmt.Sprintf("} %s {", chunk)
}
return chunk
}
func handleTemplateLine(chunk string) (string, bool) {
var buf bytes.Buffer
err := stringTemplate.Execute(&buf, quote(chunk))
handleLineError(err, chunk)
return buf.String(), len(chunk) > 0
}