-
Notifications
You must be signed in to change notification settings - Fork 16
/
rev_templates.go
116 lines (105 loc) · 2.44 KB
/
rev_templates.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
//+lbuild experiment
// ! EXPERIMENTAL
package main
import (
"errors"
"regexp"
)
type Mango struct {
tagFinder *regexp.Regexp
}
func (m *Mango) Init() {
m.tagFinder = regexp.MustCompile(`(?s)\{\{(.*)\}\}`)
}
func (m *Mango) Parse(tmpl string) (out string, err error) {
tagIndices := m.tagFinder.FindAllStringIndex(tmpl, -1)
if len(tagIndices) > 0 {
if tagIndices[0][0] == 0 {
return "", errors.New("We don't support tags in the outermost layer yet")
}
var lastTag = 0
var lastID = 0
for _, tagIndex := range tagIndices {
var nestingLayer = 0
for i := tagIndex[0]; i > 0; i-- {
switch tmpl[i] {
case '>':
ii, closeTag, err := m.tasteTagToLeft(tmpl, i)
if err != nil {
return "", err
}
if closeTag {
nestingLayer++
} else {
_, tagID := m.parseTag(tmpl, ii, i)
if tagID == "" {
out += tmpl[lastTag:ii] + m.injectID(ii, i)
lastID++
} else {
out += tmpl[lastTag:i]
}
}
case '<':
}
}
}
}
return "", nil
}
func (m *Mango) injectID(start int, end int) string {
return ""
}
func (m *Mango) parseTag(tmpl string, start int, end int) (tagType string, tagID string) {
var i = start
for ; i < end; i++ {
if tmpl[i] == ' ' {
break
}
}
tagType = tmpl[start:i]
i = start
for ; i < (end - 4); i++ {
if tmpl[i] == ' ' && tmpl[i+1] == 'i' && tmpl[i+2] == 'd' && tmpl[i+3] == '=' {
tagID = m.extractAttributeContents(tmpl, i+4, end)
}
}
return tagType, tagID
}
func (m *Mango) extractAttributeContents(tmpl string, i int, end int) (contents string) {
var start = i
var quoteChar byte = 0 // nolint
if m.isHTMLQuoteChar(tmpl[i]) {
i++
quoteChar = tmpl[i]
}
i += 3
for ; i < end; i++ {
if quoteChar != 0 {
if tmpl[i] == quoteChar {
break
}
} else if tmpl[i] == ' ' {
break
}
}
return tmpl[start:i]
}
func (m *Mango) isHTMLQuoteChar(char byte) bool {
return char == '\'' || char == '"'
}
func (m *Mango) tasteTagToLeft(tmpl string, index int) (indexOut int, closeTag bool, err error) {
var foundLeftBrace = false
for ; index > 0; index-- {
// What if the / isn't adjacent to the < but has a space instead? Is that even valid?
if index >= 1 && tmpl[index] == '/' && tmpl[index-1] == '<' {
closeTag = true
break
} else if tmpl[index] == '<' {
foundLeftBrace = true
}
}
if !foundLeftBrace {
return index, closeTag, errors.New("The left portion of the tag is missing")
}
return index, closeTag, nil
}