-
Notifications
You must be signed in to change notification settings - Fork 0
/
transpiler.go
61 lines (55 loc) · 1.31 KB
/
transpiler.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
package why
import (
"bufio"
"bytes"
"errors"
"io"
)
// Transpile will convert a html document that contains
// script tags <!? ... ?!> into a fully working tengo script.
// Html will be wrapped into http.write("...") calls.
func Transpile(in io.Reader, out io.Writer) error {
iteration := 0
tagCount := []int{0, 0}
tags := [][]byte{[]byte("<!?"), []byte("?!>")}
scanner := bufio.NewScanner(in)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, tags[iteration%2]); i >= 0 {
tagCount[iteration%2]++
return i + 3, data[0:i], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
})
writer := bufio.NewWriter(out)
for scanner.Scan() {
if len(scanner.Bytes()) > 0 {
switch iteration % 2 {
case 0:
if _, err := writer.WriteString("; http.write(`"); err != nil {
return err
}
if _, err := writer.Write(scanner.Bytes()); err != nil {
return err
}
if _, err := writer.WriteString("`);"); err != nil {
return err
}
case 1:
if _, err := writer.Write(scanner.Bytes()); err != nil {
return err
}
}
}
iteration++
}
if tagCount[0] != tagCount[1] {
return errors.New("missing closing tags")
}
return writer.Flush()
}