-
Notifications
You must be signed in to change notification settings - Fork 0
/
templator.go
executable file
·355 lines (284 loc) · 8.06 KB
/
templator.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
//Templator is alternative view on html templates for go!
//is the generator go code returned html
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/sg3des/argum"
"golang.org/x/tools/imports"
)
var args struct {
Verbose bool `argum:"-v,--verbose" help:"verbose mode"`
Ext string `argum:"-e,--ext" help:"file extension of templates" default:".gtm"`
Path string `argum:"pos,req" help:"path to directory with templates or file template"`
}
func init() {
argum.Version = "v1.1.7-180729"
argum.MustParse(&args)
}
func main() {
files, err := getFiles(args.Path, args.Ext)
if err != nil {
log.Fatalln(err)
}
for _, gtmfilename := range files {
if args.Verbose {
fmt.Println(gtmfilename)
}
w := bytes.NewBuffer([]byte{})
err := Parse(gtmfilename, w)
if err != nil {
log.Fatalln(err)
}
if args.Verbose {
displayGeneratedCode(w.Bytes())
}
filedata := w.Bytes()
filename := strings.TrimSuffix(gtmfilename, filepath.Ext(gtmfilename)) + ".go"
opt := &imports.Options{AllErrors: true}
importsData, err := imports.Process(filename, filedata, opt)
if err != nil {
displayGeneratedCode(filedata)
log.Println(err)
return
}
ioutil.WriteFile(filename, importsData, 0755)
}
}
func getFiles(dir, ext string) ([]string, error) {
fi, err := os.Stat(dir)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return []string{dir}, nil
}
return filepath.Glob(path.Join(dir, "*"+ext))
}
func displayGeneratedCode(data []byte) {
lines := bytes.Split(data, []byte("\n"))
for i, line := range lines {
fmt.Printf("%d: %s\n", i, string(line))
}
}
//Parse is parser for .gtm file and return go code
func Parse(filename string, w io.Writer) error {
f, err := os.OpenFile(filename, os.O_RDONLY, 0755)
if err != nil {
return err
}
p := &Parser{}
var packageExist bool
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
if regexp.MustCompile("^\\|\\| ?package ").Match(line) {
packageExist = true
}
golines := p.Scan(line)
// golines := Scan(line, &htmlLines, &writerExist)
if !packageExist {
w.Write(p.addPackageLine(filename))
packageExist = true
}
if len(golines) > 0 {
for _, l := range golines {
w.Write(l)
w.Write([]byte{'\n'})
}
}
}
for i, s := range p.rawhtml {
w.Write(p.printRawHTML(i, s))
// lines = append(lines, )
}
return nil
}
var (
reComment = regexp.MustCompile("^[ ]*//")
reGoLine = regexp.MustCompile("^[ ]*\\|\\|.+")
)
type Parser struct {
HTML [][]byte
rawhtml [][]byte
ioWriter bool
}
func (p *Parser) Scan(line []byte) (lines [][]byte) {
//ignore empty line
if len(bytes.Trim(line, " ")) == 0 {
return
}
//ignore comment line
if reComment.Match(line) {
return
}
//go code
if reGoLine.Match(line) {
if len(p.HTML) != 0 {
lines = append(lines, p.printHTML(p.HTML...))
p.HTML = p.HTML[:0] //[][]byte{}
}
lines = append(lines, p.parseGoLine(line, &p.ioWriter)...)
return
}
for {
n0 := bytes.Index(line, []byte("{{"))
n1 := bytes.Index(line, []byte("}}"))
// log.Println(string(line), n0, n1)
if n0 < 0 && n1 < 0 || n0 >= n1 {
break
}
if len(p.HTML) != 0 {
lines = append(lines, p.printHTML(p.HTML...))
p.HTML = p.HTML[:0]
}
prefixHTML := line[:n0]
operator := line[n0+2 : n0+3][0]
gocode := line[n0+3 : n1]
line = line[n1+2:]
prefixHTML = bytes.Replace(prefixHTML, []byte(`%`), []byte(`%%`), -1)
line = bytes.Replace(line, []byte(`%`), []byte(`%%`), -1)
switch operator {
case '?':
lines = append(lines, p.printHTML(prefixHTML))
lines = append(lines, p.parseTernary(gocode)...)
case '=':
var suffixHTML []byte
if !bytes.Contains(line, []byte("{{")) && !bytes.Contains(line, []byte("}}")) {
suffixHTML = line
line = nil
}
lines = append(lines, p.printGocode(prefixHTML, gocode, suffixHTML))
default:
var suffixHTML []byte
if !bytes.Contains(line, []byte("{{")) && !bytes.Contains(line, []byte("}}")) {
suffixHTML = line
line = nil
}
lines = append(lines, p.printHTML(prefixHTML))
lines = append(lines, append([]byte{operator}, gocode...))
lines = append(lines, p.printHTML(suffixHTML))
// log.Fatalf("unknown inline operator '%s' in line '%s'", string(operator), string(line))
}
}
if len(line) > 0 {
p.HTML = append(p.HTML, line)
}
return
}
func (p *Parser) printRawHTML(i int, rawhtml []byte) []byte {
return []byte(fmt.Sprintf("var html%d = []byte(`%s`)\n", i, rawhtml))
}
func (p *Parser) addPackageLine(filename string) []byte {
filename, _ = filepath.Abs(filename)
packagename := filepath.Base(filepath.Dir(filename))
return []byte(fmt.Sprintf("package %s\n", packagename))
}
func (p *Parser) addFuncBegin(line []byte) (lines [][]byte, writerExist bool) {
lines = append(lines, []byte{})
line = bytes.Replace(line, []byte("template"), []byte("func"), 1)
if bytes.Contains(line, []byte("w io.Writer")) {
writerExist = true
lines = append(lines, append(line, []byte(" {")...))
} else {
line = regexp.MustCompile("\\) *\\{* *$").ReplaceAll(line, []byte(") []byte {"))
writer := []byte("w := new(bytes.Buffer)")
lines = append(lines, line)
lines = append(lines, writer)
}
return
}
func (p *Parser) addFuncEnd(line []byte, writerExist bool) [][]byte {
if writerExist {
return [][]byte{[]byte{'}'}}
}
return [][]byte{[]byte("return w.Bytes()"), []byte("}")}
}
func (p *Parser) addFuncHandler(line []byte) (lines [][]byte) {
f := regexp.MustCompile("=(.*)").FindAllSubmatch(line, -1)
if len(f) == 0 || len(f[0]) != 2 {
log.Fatal(fmt.Errorf("called function not found check your template at string %s", string(line)))
}
return [][]byte{[]byte(fmt.Sprintf("w.Write(%s)", f[0][1]))}
}
func (p *Parser) parseGoLine(line []byte, writerExist *bool) (lines [][]byte) {
line = bytes.Trim(line, " ||")
var morelines [][]byte
switch {
case line[0] == '=': //print other template
morelines = p.addFuncHandler(line)
case regexp.MustCompile("^ *template ").Match(line):
morelines, *writerExist = p.addFuncBegin(line)
case regexp.MustCompile("^ *end *$").Match(line):
morelines = p.addFuncEnd(line, *writerExist)
default:
morelines = append(morelines, line)
}
lines = append(lines, morelines...)
return
}
func (p *Parser) parseTernary(gocode []byte) (lines [][]byte) {
nq := bytes.Index(gocode, []byte("?"))
nc := bytes.Index(gocode, []byte(":"))
if nq <= 0 {
log.Fatalln("failed parse ternary operator", string(gocode))
}
_if := fmt.Sprintf("if %s {", string(gocode[:nq]))
var _then string
if nc == -1 {
_then = fmt.Sprintf(" fmt.Fprintf(w, \"%%v\", %s)", gocode[nq+1:])
} else {
_then = fmt.Sprintf(" fmt.Fprintf(w, \"%%v\", %s)", gocode[nq+1:nc])
}
lines = append(lines, []byte(_if))
lines = append(lines, []byte(_then))
lines = append(lines, []byte("}"))
if nc > 0 {
lines[2] = []byte("} else {")
_else := fmt.Sprintf(" fmt.Fprintf(w, \"%%v\", %s)", gocode[nc+1:])
lines = append(lines, []byte(_else))
lines = append(lines, []byte("}"))
}
p.validateFragment(gocode, lines...)
return
}
func (p *Parser) printGocode(prefixHTML, gocode, suffixHTML []byte) []byte {
s := []byte(fmt.Sprintf("fmt.Fprintf(w, `%s%%v%s`, %s)", prefixHTML, suffixHTML, gocode))
p.validateFragment(gocode, s)
return s
}
//PrintHTML return write command for html code
func (p *Parser) printHTML(htmlLines ...[]byte) []byte {
if len(htmlLines) == 0 {
return []byte{}
}
rawhtml := bytes.TrimLeft(bytes.Join(htmlLines, []byte("\n")), "\r\n")
if len(rawhtml) == 0 {
return []byte{}
}
s := fmt.Sprintf("w.Write(html%d)", len(p.rawhtml))
p.rawhtml = append(p.rawhtml, rawhtml)
p.validateFragment(rawhtml, []byte(s))
return []byte(s)
}
func (p *Parser) validateFragment(original []byte, lines ...[]byte) {
opt := &imports.Options{FormatOnly: true, AllErrors: true, Fragment: true}
_, err := imports.Process("fragment", bytes.Join(lines, []byte("\n")), opt)
if err != nil {
fmt.Printf("error in fragment: '%s'\n", string(original))
fmt.Println(string(bytes.Join(lines, []byte("\n"))))
log.Fatalln(err)
}
}