-
Notifications
You must be signed in to change notification settings - Fork 0
/
snippet.go
50 lines (41 loc) · 990 Bytes
/
snippet.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
package gogen
import (
"context"
"strings"
)
type SnippetBuilder struct {
template string
vars []string
varSnippets map[string]Code
}
func Snippet(template string, vars ...string) (r *SnippetBuilder) {
r = &SnippetBuilder{
template: template,
vars: vars,
varSnippets: make(map[string]Code),
}
return
}
func (b *SnippetBuilder) Var(varName string, val string) (r *SnippetBuilder) {
b.vars = append(b.vars, varName, val)
return b
}
func (b *SnippetBuilder) VarCode(varName string, c Code) (r *SnippetBuilder) {
b.varSnippets[varName] = c
return b
}
func (b *SnippetBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
vars := b.vars
if len(vars)%2 != 0 {
vars = append(vars, "")
}
val := b.template
for i := 0; i < len(vars); i = i + 2 {
val = strings.ReplaceAll(val, vars[i], vars[i+1])
}
for varName, c := range b.varSnippets {
val = strings.ReplaceAll(val, varName, MustString(c, ctx))
}
r = []byte(val)
return
}