-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegen.go
240 lines (224 loc) · 6.32 KB
/
codegen.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package ens
import (
"bytes"
"fmt"
"strings"
"github.com/things-go/ens/matcher"
"github.com/things-go/ens/utils"
"golang.org/x/tools/imports"
)
var mustEscapeNames = []string{"TableName"}
type CodeGen struct {
buf bytes.Buffer
Entities []*EntityDescriptor
ByName string
Version string
PackageName string
DisableDocComment bool
Option
}
// Bytes returns the CodeBuf's buffer.
func (g *CodeGen) Bytes() []byte {
return g.buf.Bytes()
}
// FormatSource return formats and adjusts imports contents of the CodeGen's buffer.
func (g *CodeGen) FormatSource() ([]byte, error) {
data := g.buf.Bytes()
if len(data) == 0 {
return data, nil
}
// return format.Source(data)
// 格式化时, 如果需要插入或删除包是非常耗时的
return imports.Process("", data, &imports.Options{
Fragment: false,
AllErrors: false,
Comments: true,
TabIndent: true,
TabWidth: 4,
FormatOnly: false,
})
}
// Write appends the contents of p to the buffer,
func (g *CodeGen) Write(b []byte) (n int, err error) {
return g.buf.Write(b)
}
// Print formats using the default formats for its operands and writes to the generated output.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func (g *CodeGen) Print(a ...any) (n int, err error) {
return fmt.Fprint(&g.buf, a...)
}
// Printf formats according to a format specifier for its operands and writes to the generated output.
// It returns the number of bytes written and any write error encountered.
func (g *CodeGen) Printf(format string, a ...any) (n int, err error) {
return fmt.Fprintf(&g.buf, format, a...)
}
// Fprintln formats using the default formats to the generated output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func (g *CodeGen) Println(a ...any) (n int, err error) {
return fmt.Fprintln(&g.buf, a...)
}
func (g *CodeGen) Gen() *CodeGen {
if !g.DisableDocComment {
g.Printf("// Code generated by %s. DO NOT EDIT.\n", g.ByName)
g.Printf("// version: %s\n", g.Version)
g.Println()
}
g.Printf("package %s\n", g.PackageName)
g.Println()
//* 先处理转义, 主要是一些需要导入的包, 各种选项. 避免格式化耗时.
for _, et := range g.Entities {
et.fixEntityField(&g.Option)
}
//* import
imports := make(map[string]struct{})
for _, st := range g.Entities {
for _, field := range st.Fields {
if field.Type.PkgPath != "" {
imports[field.Type.PkgPath] = struct{}{}
}
}
}
if len(imports) > 0 {
g.Println("import (")
for k := range imports {
g.Printf("\"%s\"\n", k)
}
g.Println(")")
}
//* struct
for _, et := range g.Entities {
structName := utils.PascalCase(et.Name)
tableName := et.Name
g.Printf("// %s %s\n", structName, strings.ReplaceAll(strings.TrimSpace(et.Comment), "\n", "\n// "))
g.Printf("type %s struct {\n", structName)
for _, field := range et.Fields {
g.Println(g.genModelStructField(field))
}
g.Println("}")
g.Println()
g.Println("// TableName implement schema.Tabler interface")
g.Printf("func (*%s) TableName() string {\n", structName)
g.Printf("return \"%s\"\n", tableName)
g.Println("}")
g.Println()
}
return g
}
func (g *CodeGen) genModelStructField(field *FieldDescriptor) string {
b := strings.Builder{}
b.Grow(128)
ident := field.Type.Ident
if field.GoPointer && !field.Type.NonPointer {
ident = "*" + field.Type.Ident
}
// field
b.WriteString(field.GoName)
b.WriteString(" ")
b.WriteString(ident)
if len(field.Tags) > 0 {
b.WriteString(" `")
b.WriteString(strings.Join(field.Tags, " "))
b.WriteString("`")
}
if field.Comment != "" {
b.WriteString(" // ")
b.WriteString(field.Comment)
}
return b.String()
}
func (et *EntityDescriptor) fixEntityField(opt *Option) {
if opt == nil {
opt = defaultOption()
}
escapeNames := make(map[string]struct{}, len(mustEscapeNames)+len(opt.EscapeName)+len(et.Fields))
for _, v := range mustEscapeNames {
escapeNames[v] = struct{}{}
}
for _, k := range opt.EscapeName {
escapeNames[k] = struct{}{}
}
allFieldName := make(map[string]struct{}, len(et.Fields))
for _, field := range et.Fields {
allFieldName[field.GoName] = struct{}{}
}
for _, field := range et.Fields {
field.fixField(allFieldName, escapeNames, opt)
}
}
// 根据规则转义一些数据
func (field *FieldDescriptor) fixField(allFieldName, escapeFieldNames map[string]struct{}, opt *Option) {
if field.ColumnName == "deleted_at" {
if field.Type.IsInteger() {
field.GoPointer = false
field.Type = SoftDeleteType().WithNewType(field.Type.Type)
} else if field.Type.IsInteger() {
field.GoPointer = false
field.Type = GormDeletedAtType().WithNewType(field.Type.Type)
}
}
if opt == nil {
opt = defaultOption()
}
if opt.EnableInt {
switch field.Type.Type {
case TypeInt8, TypeInt16, TypeInt32:
field.Type = IntType().WithNewType(field.Type.Type)
case TypeUint8, TypeUint16, TypeUint32:
field.Type = UintType().WithNewType(field.Type.Type)
}
}
if opt.EnableBoolInt && field.Type.IsBool() {
field.Type = IntType().WithNewType(field.Type.Type)
}
if field.Nullable && opt.DisableNullToPoint {
gt, ok := getSQLNullValueGoType(field.Type.Type)
if ok {
field.Type = gt
field.GoPointer = false
}
}
for tag, kind := range opt.Tags {
if tag == "json" {
if vv := matcher.JsonTag(field.Comment); vv != "" {
field.Tags = append(field.Tags, fmt.Sprintf(`%s:"%s"`, tag, vv))
continue
}
}
vv := utils.StyleName(kind, field.ColumnName)
if vv == "" {
continue
}
format := ""
if tag == "json" && matcher.HasAffixJSONTag(field.Comment) {
if opt.IgnoreOmitempty {
format = `%s:"%s,string"`
} else {
format = `%s:"%s,omitempty,string"`
}
} else if opt.IgnoreOmitempty {
format = `%s:"%s"`
} else {
format = `%s:"%s,omitempty"`
}
field.Tags = append(field.Tags, fmt.Sprintf(format, tag, vv))
}
goName := field.GoName
for {
_, ok := escapeFieldNames[goName]
if !ok { // need to escape
break
}
goName = "X" + goName
// 和当前字段存在的重复, 再追加一个
_, ok = allFieldName[goName]
if ok {
goName = "X" + goName
}
}
if field.GoName != goName {
field.GoName = goName
escapeFieldNames[goName] = struct{}{} // 添加为必须转义
}
}