forked from benbjohnson/ego
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate.go
224 lines (191 loc) · 5.42 KB
/
template.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
package egon
import (
"bytes"
"fmt"
"io"
"path/filepath"
"regexp"
"strings"
)
// Template represents an entire Ego template.
// Templates consist of a set of parameters and other block.
// Blocks can be either a TextBlock, a PrintBlock, a RawPrintBlock, or a CodeBlock.
type Template struct {
Path string
Blocks []Block
}
// PackageName returns the name of the package, based on the last non-file
// part of the path.
func (t *Template) PackageName() (string, error) {
path, err := filepath.Abs(t.Path)
if err != nil {
return "", ErrUnidentifiablePackage
}
// split the path by file separator, rip the first one off (it's always blank)
// and then grab the last one
parts := strings.Split(path, string(filepath.Separator))
parts = parts[1:]
if len(parts) < 2 {
return "", ErrUnidentifiablePackage
}
return parts[len(parts)-2], nil
}
// FileName returns the filename of the template, without the path.
func (t *Template) FileName() string {
_, fileName := filepath.Split(t.Path)
return fileName
}
// Name returns a name for the template as a camel cased string based on
// the filename.
func (t *Template) Name() string {
fileName := t.FileName()
// remove the extension
parts := strings.Split(fileName, ".")
name := parts[0]
// Filter out any non-letter and digit runes
re := regexp.MustCompile("[^\\p{L}0-9]")
name = re.ReplaceAllString(name, " ")
// convert to title case and remove spaces
name = strings.Title(name)
name = strings.Replace(name, " ", "", -1)
return name
}
// TemplateFuncName returns the name of the Template func for this template.
func (t *Template) TemplateFuncName() string {
return strings.Join([]string{t.Name(), "Template"}, "")
}
// ViewFuncName returns the name fo the View func for this template.
func (t *Template) ViewFuncName() string {
return strings.Join([]string{t.Name(), "View"}, "")
}
// SourceFile returns the path to the source file that should be
// generated from this template.
func (t *Template) SourceFile() string {
return strings.Join([]string{t.Path, ".go"}, "")
}
// Write writes the template to a writer.
func (t *Template) Write(w io.Writer) error {
var buf bytes.Buffer
params := t.parameterBlocks()
buf.WriteString("\n")
// optionally write the view
if (Config.GenerateView) {
buf.WriteString(fmt.Sprintf("func %s(", t.ViewFuncName()))
t.writeParameters(&buf, params)
buf.WriteString(") *egon.View {\n")
packageName, err := t.PackageName()
if err != nil {
return err
}
buf.WriteString(fmt.Sprintf("\tpackageName := \"%s\"\n", packageName))
buf.WriteString(fmt.Sprintf("\tname := \"%s\"\n", t.Name()))
buf.WriteString(fmt.Sprintf("\ttemplatePath := \"%s\"\n", t.Path))
buf.WriteString("\trenderFunc := func(w io.Writer) error {\n")
paramsAsArgs := []string{}
for _, param := range params {
paramsAsArgs = append(paramsAsArgs, param.ParamName)
}
buf.WriteString(fmt.Sprintf("\t\treturn %s(w, %s)\n", t.TemplateFuncName(),
strings.Join(paramsAsArgs, ", ")))
buf.WriteString("\t}\n")
buf.WriteString("\treturn &egon.View{PackageName: packageName, Name: name, TemplatePath: templatePath, RenderFunc: renderFunc}\n")
buf.WriteString("}\n\n")
}
// render the template func
// add the writer param
ioParam := ParameterBlock{ParamName: "w", ParamType: "io.Writer"}
params = append([]*ParameterBlock{&ioParam}, params...)
buf.WriteString(fmt.Sprintf("func %s(", t.TemplateFuncName()))
t.writeParameters(&buf, params)
buf.WriteString(") error {\n")
// Write non-header blocks.
for _, b := range t.nonHeaderBlocks() {
if err := b.write(&buf); err != nil {
return err
}
}
// Write return and function closing brace.
fmt.Fprint(&buf, "return nil\n")
fmt.Fprint(&buf, "}\n")
// Write code to external writer.
_, err := buf.WriteTo(w)
return err
}
func (t *Template) writeParameters(buf *bytes.Buffer, params []*ParameterBlock) {
maxIndex := len(params) - 1
for i, param := range params {
param.write(buf)
if i < maxIndex {
buf.WriteString(", ")
}
}
}
func (t *Template) parameterBlocks() []*ParameterBlock {
blocks := []*ParameterBlock{}
for _, b := range t.Blocks {
if b, ok := b.(*ParameterBlock); ok {
blocks = append(blocks, b)
}
}
return blocks
}
func (t *Template) headerBlocks() []*HeaderBlock {
var blocks []*HeaderBlock
for _, b := range t.Blocks {
if b, ok := b.(*HeaderBlock); ok {
blocks = append(blocks, b)
}
}
return blocks
}
func (t *Template) nonHeaderBlocks() []Block {
var blocks []Block
for _, b := range t.Blocks {
switch b.(type) {
case *ParameterBlock, *HeaderBlock:
default:
blocks = append(blocks, b)
}
}
return blocks
}
func (t *Template) hasEscapedPrintBlock() bool {
for _, b := range t.Blocks {
if _, ok := b.(*PrintBlock); ok {
return true
}
}
return false
}
func (t *Template) hasItoaPrintBlock() bool {
for _, b := range t.Blocks {
if pBlock, ok := b.(*PrintBlock); ok {
if (pBlock.Type == 'd') {
return true
}
}
}
return false
}
func (t *Template) hasFmtPrintBlock() bool {
for _, b := range t.Blocks {
if pBlock, ok := b.(*PrintBlock); ok {
if (pBlock.Type != 'd' && pBlock.Type != 's') {
return true
}
}
}
return false
}
// normalize joins together adjacent text blocks.
func (t *Template) normalize() {
var a []Block
for _, b := range t.Blocks {
if isTextBlock(b) && len(a) > 0 && isTextBlock(a[len(a)-1]) {
a[len(a)-1].(*TextBlock).Content += b.(*TextBlock).Content
} else {
a = append(a, b)
}
}
t.Blocks = a
}