forked from benbjohnson/ego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
274 lines (232 loc) · 5.84 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
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
package ego
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
)
// Template represents an entire Ego template.
// A template consists of a declaration block followed by zero or more blocks.
// Blocks can be either a TextBlock, a PrintBlock, or a CodeBlock.
type Template struct {
Path string
Blocks []Block
}
// Write writes the template to a writer.
func (t *Template) Write(w io.Writer) error {
var buf bytes.Buffer
decl := t.declarationBlock()
if decl == nil {
return ErrDeclarationRequired
}
// Write function declaration.
decl.write(&buf)
// 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) declarationBlock() *DeclarationBlock {
for _, b := range t.Blocks {
if b, ok := b.(*DeclarationBlock); ok {
return b
}
}
return nil
}
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 *DeclarationBlock, *HeaderBlock:
default:
blocks = append(blocks, b)
}
}
return blocks
}
// 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
}
// Block represents an element of the template.
type Block interface {
block()
write(*bytes.Buffer) error
}
func (b *DeclarationBlock) block() {}
func (b *TextBlock) block() {}
func (b *CodeBlock) block() {}
func (b *HeaderBlock) block() {}
func (b *PrintBlock) block() {}
// DeclarationBlock represents a block that declaration the function signature.
type DeclarationBlock struct {
Pos Pos
Content string
}
func (b *DeclarationBlock) write(buf *bytes.Buffer) error {
b.Pos.write(buf)
fmt.Fprintf(buf, "%s {\n", b.Content)
return nil
}
// TextBlock represents a UTF-8 encoded block of text that is written to the writer as-is.
type TextBlock struct {
Pos Pos
Content string
}
func (b *TextBlock) write(buf *bytes.Buffer) error {
b.Pos.write(buf)
fmt.Fprintf(buf, `_, _ = fmt.Fprintf(w, %q)`+"\n", b.Content)
return nil
}
// isTextBlock returns true if the block is a text block.
func isTextBlock(b Block) bool {
_, ok := b.(*TextBlock)
return ok
}
// CodeBlock represents a Go code block that is printed as-is to the template.
type CodeBlock struct {
Pos Pos
Content string
}
func (b *CodeBlock) write(buf *bytes.Buffer) error {
b.Pos.write(buf)
fmt.Fprintln(buf, b.Content)
return nil
}
// HeaderBlock represents a Go code block that is printed at the top of the template.
type HeaderBlock struct {
Pos Pos
Content string
}
func (b *HeaderBlock) write(buf *bytes.Buffer) error {
b.Pos.write(buf)
fmt.Fprintln(buf, b.Content)
return nil
}
// PrintBlock represents a block of the template that is printed out to the writer.
type PrintBlock struct {
Pos Pos
Content string
}
func (b *PrintBlock) write(buf *bytes.Buffer) error {
b.Pos.write(buf)
fmt.Fprintf(buf, `_, _ = fmt.Fprintf(w, "%%v", %s)`+"\n", b.Content)
return nil
}
// Pos represents a position in a given file.
type Pos struct {
Path string
LineNo int
}
func (p *Pos) write(buf *bytes.Buffer) {
if p != nil && p.Path != "" && p.LineNo > 0 {
fmt.Fprintf(buf, "//line %s:%d\n", filepath.Base(p.Path), p.LineNo)
}
}
// Package represents a collection of ego templates in a single package.
type Package struct {
Name string
Templates []*Template
}
// Write writes out the package header and templates to a writer.
func (p *Package) Write(w io.Writer) error {
if err := p.writeHeader(w); err != nil {
return err
}
for _, t := range p.Templates {
if err := t.Write(w); err != nil {
return fmt.Errorf("template: %s: err", t.Path)
}
}
return nil
}
// Writes the package name and consolidated header blocks.
func (p *Package) writeHeader(w io.Writer) error {
if p.Name == "" {
return errors.New("package name required")
}
// Write naive header first.
var buf bytes.Buffer
fmt.Fprintf(&buf, "package %s\n", p.Name)
for _, t := range p.Templates {
for _, b := range t.headerBlocks() {
b.write(&buf)
}
}
// Parse header into Go AST.
f, err := parser.ParseFile(token.NewFileSet(), "ego.go", buf.String(), parser.ImportsOnly)
if err != nil {
fmt.Println(buf.String())
return fmt.Errorf("writeHeader: %s", err)
}
// Reset buffer.
buf.Reset()
fmt.Fprintf(&buf, "package %s\n", p.Name)
// Write deduped imports.
var decls = map[string]bool{`:"fmt"`: true, `:"io"`: true}
fmt.Fprint(&buf, "import (\n")
fmt.Fprintln(&buf, `"fmt"`)
fmt.Fprintln(&buf, `"io"`)
for _, d := range f.Decls {
d, ok := d.(*ast.GenDecl)
if !ok || d.Tok != token.IMPORT {
continue
}
for _, s := range d.Specs {
s := s.(*ast.ImportSpec)
var id string
if s.Name != nil {
id = s.Name.Name
}
id += ":" + s.Path.Value
// Ignore any imports which have already been imported.
if decls[id] {
continue
}
decls[id] = true
// Otherwise write it.
if s.Name == nil {
fmt.Fprintf(&buf, "%s\n", s.Path.Value)
} else {
fmt.Fprintf(&buf, "%s %s\n", s.Name.Name, s.Path.Value)
}
}
}
fmt.Fprint(&buf, ")\n")
// Write out to writer.
buf.WriteTo(w)
return nil
}
func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) }