-
Notifications
You must be signed in to change notification settings - Fork 0
/
const.go
99 lines (81 loc) · 2.04 KB
/
const.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
package gogen
import (
"bytes"
"context"
"fmt"
)
type ConstBlockBuilder struct {
name string
consts []Code
constType string
toType string
namePrefixType bool
}
func ConstBlock() (r *ConstBlockBuilder) {
r = &ConstBlockBuilder{}
return
}
func (b *ConstBlockBuilder) Type(constType string, toType string) (r *ConstBlockBuilder) {
b.constType = constType
b.toType = toType
b.NamePrefixType(true)
return b
}
func (b *ConstBlockBuilder) NamePrefixType(v bool) (r *ConstBlockBuilder) {
b.namePrefixType = v
return b
}
func (b *ConstBlockBuilder) ConstSnippet(template string, vars ...string) (r *ConstBlockBuilder) {
b.Consts(Snippet(template, vars...))
return b
}
func (b *ConstBlockBuilder) Consts(cs ...Code) (r *ConstBlockBuilder) {
b.consts = append(b.consts, cs...)
return b
}
func (b *ConstBlockBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
for _, c := range b.consts {
if ci, ok := c.(*ConstItemBuilder); ok {
ci.SetConstType(b.constType, b.namePrefixType)
}
}
buf := bytes.NewBuffer(nil)
if len(b.constType) > 0 {
buf.WriteString(fmt.Sprintf("type %s %s\n", b.constType, b.toType))
}
buf.WriteString("const (\n")
err = Fprint(buf, Snippets(b.consts...), ctx)
if err != nil {
return
}
buf.WriteString(")\n")
r = buf.Bytes()
return
}
type ConstItemBuilder struct {
name string
val interface{}
constType string
namePrefixType bool
}
func Const(name string, val interface{}) (r *ConstItemBuilder) {
r = &ConstItemBuilder{
name: name,
val: val,
}
return
}
func (b *ConstItemBuilder) SetConstType(constType string, namePrefixType bool) {
b.constType = constType
b.namePrefixType = namePrefixType
}
func (b *ConstItemBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
if len(b.constType) == 0 {
panic("To use Const, Parent must set Type")
}
var name = b.name
if b.namePrefixType {
name = fmt.Sprintf("%s%s", b.constType, name)
}
return Raw(fmt.Sprintf("%s %s = %#+v", name, b.constType, b.val)).MarshalCode(ctx)
}