-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
105 lines (88 loc) · 1.94 KB
/
struct.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
package gogen
import (
"bytes"
"context"
"fmt"
"strings"
)
type StructBuilder struct {
name string
fields []Code
funcs []Code
funcsReceiverVar string
pointer bool
}
func Struct(name string) (r *StructBuilder) {
r = &StructBuilder{}
r.name = name
r.pointer = true
return
}
func (b *StructBuilder) FieldsSnippet(template string, vars ...string) (r *StructBuilder) {
b.Fields(Snippet(template, vars...))
return b
}
func (b *StructBuilder) Fields(imps ...Code) (r *StructBuilder) {
b.fields = append(b.fields, imps...)
return b
}
func (b *StructBuilder) Funcs(funcs ...Code) (r *StructBuilder) {
b.funcs = append(b.funcs, funcs...)
return b
}
func (b *StructBuilder) FuncsSnippet(template string, vars ...string) (r *StructBuilder) {
b.Funcs(Snippet(template, vars...))
return b
}
func (b *StructBuilder) ReceiverVar(varName string) (r *StructBuilder) {
b.funcsReceiverVar = varName
return b
}
func (b *StructBuilder) Pointer(v bool) (r *StructBuilder) {
b.pointer = v
return b
}
func (b *StructBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
buf.WriteString(fmt.Sprintf("type %s struct {\n", b.name))
err = Fprint(buf, Snippets(b.fields...), ctx)
if err != nil {
return
}
buf.WriteString("}\n")
for _, f := range b.funcs {
if fb, ok := f.(*FuncBuilder); ok {
varName := b.funcsReceiverVar
if len(varName) == 0 {
varName = "this"
}
tp := b.name
if b.pointer {
tp = "*" + b.name
}
fb.Receiver(varName, tp)
}
}
err = Fprint(buf, Snippets(b.funcs...), ctx)
if err != nil {
return
}
r = buf.Bytes()
return
}
func Tag(key string, val string) (r string) {
r = fmt.Sprintf(`%s "%s"`, key, val)
return
}
func Field(name, typ string, tags ...string) (r Code) {
theTags := ""
if len(tags) > 0 {
theTags = " `" + strings.Join(tags, " ") + "`"
}
r = Raw(fmt.Sprintf("%s %s%s",
name,
typ,
theTags,
))
return
}