-
-
Notifications
You must be signed in to change notification settings - Fork 233
/
templatefile.go
193 lines (176 loc) · 4.6 KB
/
templatefile.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
package parser
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"unicode"
"github.com/a-h/lexical/input"
"github.com/a-h/lexical/parse"
)
const maxBufferSize = 1024 * 1024 * 10 // 10MB
func Parse(fileName string) (TemplateFile, error) {
f, err := os.Open(fileName)
if err != nil {
return TemplateFile{}, err
}
fi, err := f.Stat()
if err != nil {
return TemplateFile{}, err
}
bufferSize := maxBufferSize
if fi.Size() < int64(bufferSize) {
bufferSize = int(fi.Size())
}
reader := bufio.NewReader(f)
tfr := NewTemplateFileParser(getDefaultPackageName(fileName)).Parse(input.NewWithBufferSize(reader, bufferSize))
if tfr.Error != nil {
return TemplateFile{}, tfr.Error
}
return tfr.Item.(TemplateFile), nil
}
func getDefaultPackageName(fileName string) (pkg string) {
parent := filepath.Base(filepath.Dir(fileName))
if !isGoIdentifier(parent) {
return "main"
}
return parent
}
func isGoIdentifier(s string) bool {
if len(s) == 0 {
return false
}
for i, r := range s {
if unicode.IsLetter(r) || r == '_' {
continue
}
if i > 0 && unicode.IsDigit(r) {
continue
}
return false
}
return true
}
func ParseString(template string) (TemplateFile, error) {
tfr := NewTemplateFileParser("main").Parse(input.NewFromString(template))
if tfr.Error != nil {
return TemplateFile{}, tfr.Error
}
return tfr.Item.(TemplateFile), nil
}
// NewTemplateFileParser creates a new TemplateFileParser.
func NewTemplateFileParser(pkg string) TemplateFileParser {
return TemplateFileParser{
DefaultPackage: pkg,
}
}
var ErrLegacyFileFormat = errors.New("Legacy file format - run templ migrate")
type TemplateFileParser struct {
DefaultPackage string
}
func (p TemplateFileParser) Parse(pi parse.Input) parse.Result {
var tf TemplateFile
// If we're parsing a legacy file, complain that migration needs to happen.
pr := parse.String("{% package")(pi)
if pr.Success {
return parse.Failure("Legacy file format", ErrLegacyFileFormat)
}
// Required package.
// package name
pr = pkg.Parse(pi)
if pr.Error != nil {
return pr
}
pkg, ok := pr.Item.(Package)
if !ok {
pkg = Package{
Expression: NewExpression("package "+p.DefaultPackage, NewPosition(), NewPosition()),
}
}
tf.Package = pkg
// Optional whitespace.
parse.Optional(parse.WithStringConcatCombiner, whitespaceParser)(pi)
// Optional templates, CSS, and script templates.
// templ Name(p Parameter) {
// css Name() {
// script Name() {
// Anything else is assumed to be Go code.
cssp := newCSSParser()
stp := newScriptTemplateParser()
templateContent := parse.Any(template.Parse, cssp.Parse, stp.Parse)
outer:
for {
pr := templateContent(pi)
if pr.Error != nil && pr.Error != io.EOF {
return pr
}
if pr.Success {
switch pr.Item.(type) {
case HTMLTemplate:
tf.Nodes = append(tf.Nodes, pr.Item.(HTMLTemplate))
case CSSTemplate:
tf.Nodes = append(tf.Nodes, pr.Item.(CSSTemplate))
case ScriptTemplate:
tf.Nodes = append(tf.Nodes, pr.Item.(ScriptTemplate))
default:
return parse.Failure("unknown node type", fmt.Errorf("unknown node type %s", reflect.TypeOf(pr.Item).Name()))
}
// Eat optional whitespace.
parse.Optional(parse.WithStringConcatCombiner, whitespaceParser)(pi)
continue
}
if pr.Error == io.EOF {
break
}
// Anything that isn't template content is Go code.
var code strings.Builder
from := NewPositionFromInput(pi)
for {
// Check to see if this line isn't Go code.
last := NewPositionFromInput(pi)
l, err := readLine(pi)
if err != nil && err != io.EOF {
return parse.Failure("unknown error", err)
}
hasTemplatePrefix := strings.HasPrefix(l, "templ ") || strings.HasPrefix(l, "css ") || strings.HasPrefix(l, "script ")
if hasTemplatePrefix && strings.HasSuffix(l, "{\n") {
// Unread the line.
rewind(pi, last.Index)
// Take the code so far.
if code.Len() > 0 {
expr := NewExpression(strings.TrimSpace(code.String()), from, NewPositionFromInput(pi))
tf.Nodes = append(tf.Nodes, GoExpression{Expression: expr})
}
// Carry on parsing.
break
}
code.WriteString(l)
if err == io.EOF {
if code.Len() > 0 {
expr := NewExpression(strings.TrimSpace(code.String()), from, NewPositionFromInput(pi))
tf.Nodes = append(tf.Nodes, GoExpression{Expression: expr})
}
// Stop parsing.
break outer
}
}
}
return parse.Success("template file", tf, nil)
}
func readLine(pi parse.Input) (string, error) {
var sb strings.Builder
for {
r, err := pi.Advance()
if err != nil {
return sb.String(), err
}
sb.WriteRune(r)
if r == '\n' {
return sb.String(), err
}
}
}