-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathif_block.go
103 lines (85 loc) · 2.2 KB
/
if_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
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
package gogen
import (
"bytes"
"context"
"fmt"
"strings"
)
type condBlocks struct {
cond Code
blocks []Code
}
type IfBlockBuilder struct {
ifBlock *condBlocks
elseIfBlocks []*condBlocks
elseBlocks []Code
lastCondBlocks *condBlocks
}
func IfBlock(ifTemplate string, vars ...string) (r *IfBlockBuilder) {
r = &IfBlockBuilder{}
if strings.Index(ifTemplate, "if") != 0 {
ifTemplate = fmt.Sprintf("%s %s", "if", ifTemplate)
}
r.ifBlock = &condBlocks{cond: Snippet(ifTemplate, vars...)}
r.lastCondBlocks = r.ifBlock
return
}
func (b *IfBlockBuilder) Then(blocks ...Code) (r *IfBlockBuilder) {
b.lastCondBlocks.blocks = append(b.lastCondBlocks.blocks, blocks...)
return b
}
func (b *IfBlockBuilder) ThenSnippet(template string, vars ...string) (r *IfBlockBuilder) {
b.Then(Snippet(template, vars...))
return b
}
func (b *IfBlockBuilder) ElseIf(elseIfTemplate string, vars ...string) (r *IfBlockBuilder) {
if strings.Index(elseIfTemplate, "else if") != 0 {
elseIfTemplate = fmt.Sprintf("%s %s", "else if", elseIfTemplate)
}
b.lastCondBlocks = &condBlocks{cond: Snippet(elseIfTemplate, vars...)}
b.elseIfBlocks = append(b.elseIfBlocks, b.lastCondBlocks)
return b
}
func (b *IfBlockBuilder) Else(blocks ...Code) (r *IfBlockBuilder) {
b.elseBlocks = append(b.elseBlocks, blocks...)
return b
}
func (b *IfBlockBuilder) ElseSnippet(template string, vars ...string) (r *IfBlockBuilder) {
b.Else(Snippet(template, vars...))
return b
}
func (b *IfBlockBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
err = Fprint(buf, b.ifBlock.cond, ctx)
if err != nil {
return
}
buf.WriteString(" {\n")
err = Fprint(buf, Snippets(b.ifBlock.blocks...), ctx)
if err != nil {
panic(err)
}
buf.WriteString("} ")
for _, elsIf := range b.elseIfBlocks {
err = Fprint(buf, elsIf.cond, ctx)
if err != nil {
return
}
buf.WriteString(" {\n")
err = Fprint(buf, Snippets(elsIf.blocks...), ctx)
if err != nil {
panic(err)
}
buf.WriteString("} ")
}
if len(b.elseBlocks) > 0 {
buf.WriteString(" else {\n")
err = Fprint(buf, Snippets(b.elseBlocks...), ctx)
if err != nil {
panic(err)
}
buf.WriteString("}\n")
}
r = buf.Bytes()
return
}