-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch_block.go
57 lines (46 loc) · 1.16 KB
/
switch_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
package gogen
import (
"bytes"
"context"
)
type SwitchBlockBuilder struct {
switchBlock Code
cases []Code
defaultBlock Code
}
func SwitchBlock(switchTemplate string, vars ...string) (r *SwitchBlockBuilder) {
r = &SwitchBlockBuilder{}
r.switchBlock = Snippet(switchTemplate, vars...)
return
}
func (b *SwitchBlockBuilder) Cases(caseBlocks ...Code) (r *SwitchBlockBuilder) {
b.cases = append(b.cases, caseBlocks...)
return b
}
func (b *SwitchBlockBuilder) CasesSnippet(template string, vars ...string) (r *SwitchBlockBuilder) {
b.Cases(Snippet(template, vars...))
return b
}
func (b *SwitchBlockBuilder) Default(defaultTemplate string, vars ...string) (r *SwitchBlockBuilder) {
b.defaultBlock = Snippet(defaultTemplate, vars...)
return b
}
func (b *SwitchBlockBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
err = Fprint(buf, b.switchBlock, ctx)
if err != nil {
return
}
buf.WriteString(" {\n")
err = Fprint(buf, Snippets(b.cases...), ctx)
if err != nil {
panic(err)
}
err = Fprint(buf, b.defaultBlock, ctx)
if err != nil {
panic(err)
}
buf.WriteString("\n}\n")
r = buf.Bytes()
return
}