-
Notifications
You must be signed in to change notification settings - Fork 0
/
for_block.go
51 lines (42 loc) · 975 Bytes
/
for_block.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
package gogen
import (
"bytes"
"context"
"fmt"
"strings"
)
type ForBlockBuilder struct {
cond Code
blocks []Code
}
func ForBlock(forTemplate string, vars ...string) (r *ForBlockBuilder) {
r = &ForBlockBuilder{}
if strings.Index(forTemplate, "for") != 0 {
forTemplate = fmt.Sprintf("%s %s", "for", forTemplate)
}
r.cond = Snippet(forTemplate, vars...)
return
}
func (b *ForBlockBuilder) Body(blocks ...Code) (r *ForBlockBuilder) {
b.blocks = append(b.blocks, blocks...)
return b
}
func (b *ForBlockBuilder) BodySnippet(template string, vars ...string) (r *ForBlockBuilder) {
b.Body(Snippet(template, vars...))
return b
}
func (b *ForBlockBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
err = Fprint(buf, b.cond, ctx)
if err != nil {
return
}
buf.WriteString(" {\n")
err = Fprint(buf, Snippets(b.blocks...), ctx)
if err != nil {
panic(err)
}
buf.WriteString("}")
r = buf.Bytes()
return
}