-
Notifications
You must be signed in to change notification settings - Fork 4
/
generator.go
393 lines (329 loc) · 9.73 KB
/
generator.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"fmt"
"github.com/dobyte/mongo-dao-generator/template"
"go/ast"
"go/token"
"golang.org/x/tools/go/packages"
"log"
"os"
"path/filepath"
"reflect"
"strings"
)
const (
symbolBacktick = "`"
)
const (
symbolBacktickKey = "SymbolBacktick"
)
const (
varPackagesKey = "VarPackages"
varModelClassNameKey = "VarModelClassName"
varModelPackageNameKey = "VarModelPackageName"
varModelPackagePathKey = "VarModelPackagePath"
varModelVariableNameKey = "VarModelVariableName"
varModelColumnsDefineKey = "VarModelColumnsDefine"
varModelColumnsInstanceKey = "VarModelColumnsInstance"
varDaoClassNameKey = "VarDaoClassName"
varDaoVariableNameKey = "VarDaoVariableName"
varDaoPackageNameKey = "VarDaoPackageName"
varDaoPackagePathKey = "VarDaoPackagePath"
varDaoPrefixNameKey = "VarDaoPrefixName"
varCollectionNameKey = "VarCollectionName"
varAutofillCodeKey = "VarAutofillCode"
)
const defaultCounterName = "Counter"
type options struct {
modelDir string
modelPkgPath string
modelPkgAlias string
modelNames []string
daoDir string
daoPkgPath string
subPkgEnable bool
subPkgStyle style
counterName string
fileNameStyle style
}
type generator struct {
opts *options
counter *counter
modelNames map[string]struct{}
}
func newGenerator(opts *options) *generator {
modelNames := make(map[string]struct{}, len(opts.modelNames))
for _, modelName := range opts.modelNames {
if isExportable(modelName) {
modelNames[modelName] = struct{}{}
}
}
if len(modelNames) == 0 {
log.Fatalf("error: %d model type names found", len(modelNames))
}
if opts.counterName == "" {
opts.counterName = defaultCounterName
}
return &generator{
opts: opts,
counter: newCounter(opts),
modelNames: modelNames,
}
}
func (g *generator) makeDao() {
models := g.parseModels()
for _, m := range models {
g.makeModelInternalDao(m)
g.makeModelExternalDao(m)
fmt.Printf("%s's dao file generated successfully\n", m.modelName)
if !m.isDependCounter {
continue
}
g.makeCounterInternalDao()
g.makeCounterExternalDao()
}
}
// generate an internal dao file based on model
func (g *generator) makeModelInternalDao(m *model) {
replaces := make(map[string]string)
replaces[varModelClassNameKey] = m.modelClassName
replaces[varModelPackageNameKey] = m.modelPkgName
replaces[varModelPackagePathKey] = m.modelPkgPath
replaces[varModelVariableNameKey] = m.modelVariableName
replaces[varDaoPrefixNameKey] = m.daoPrefixName
replaces[varDaoClassNameKey] = m.daoClassName
replaces[varDaoVariableNameKey] = m.daoVariableName
replaces[varCollectionNameKey] = m.collectionName
replaces[varModelColumnsDefineKey] = m.modelColumnsDefined()
replaces[varModelColumnsInstanceKey] = m.modelColumnsInstance()
replaces[varAutofillCodeKey] = m.autoFillCode()
replaces[varPackagesKey] = m.packages()
file := m.daoOutputDir + "/internal/" + m.daoOutputFile
err := doWrite(file, template.InternalTemplate, replaces)
if err != nil {
log.Fatal(err)
}
}
// generate an external dao file based on model
func (g *generator) makeModelExternalDao(m *model) {
file := m.daoOutputDir + "/" + m.daoOutputFile
_, err := os.Stat(file)
if err != nil {
switch {
case os.IsNotExist(err):
// ignore
case os.IsExist(err):
return
default:
log.Fatal(err)
}
} else {
return
}
replaces := make(map[string]string)
replaces[varDaoClassNameKey] = m.daoClassName
replaces[varDaoPrefixNameKey] = m.daoPrefixName
replaces[varDaoPackageNameKey] = m.daoPkgName
replaces[varDaoPackagePathKey] = m.daoPkgPath
err = doWrite(file, template.ExternalTemplate, replaces)
if err != nil {
log.Fatal(err)
}
}
// generate an internal dao file based on counter model
func (g *generator) makeCounterInternalDao() {
replaces := make(map[string]string)
replaces[varDaoClassNameKey] = g.counter.daoClassName
replaces[varDaoPrefixNameKey] = g.counter.daoPrefixName
replaces[varDaoVariableNameKey] = g.counter.daoVariableName
replaces[varCollectionNameKey] = g.counter.collectionName
replaces[symbolBacktickKey] = symbolBacktick
file := g.counter.daoOutputDir + "/internal/" + g.counter.daoOutputFile
err := doWrite(file, template.CounterInternalTemplate, replaces)
if err != nil {
log.Fatal(err)
}
}
// generate an external dao file based on counter model
func (g *generator) makeCounterExternalDao() {
file := g.counter.daoOutputDir + "/" + g.counter.daoOutputFile
_, err := os.Stat(file)
if err != nil {
switch {
case os.IsNotExist(err):
// ignore
case os.IsExist(err):
return
default:
log.Fatal(err)
}
} else {
return
}
replaces := make(map[string]string)
replaces[varDaoClassNameKey] = g.counter.daoClassName
replaces[varDaoPackageNameKey] = g.counter.daoPkgName
replaces[varDaoPackagePathKey] = g.counter.daoPkgPath
err = doWrite(file, template.CounterExternalTemplate, replaces)
if err != nil {
log.Fatal(err)
}
}
// parse multiple models from the go file
func (g *generator) parseModels() []*model {
var (
pkg = g.loadPackage()
models = make([]*model, 0, len(pkg.Syntax))
daoPkgPath = g.opts.daoPkgPath
modelPkgPath = g.opts.modelPkgPath
modelPkgName = g.opts.modelPkgAlias
)
if g.opts.daoPkgPath == "" && pkg.Module != nil {
outPath, err := filepath.Abs(g.opts.daoDir)
if err != nil {
log.Fatal(err)
}
daoPkgPath = pkg.Module.Path + outPath[len(pkg.Module.Dir):]
}
daoPkgPath = strings.ReplaceAll(daoPkgPath, `\`, `/`)
g.counter.setDaoPkgPath(daoPkgPath)
for _, file := range pkg.Syntax {
if g.opts.modelPkgPath == "" && pkg.Module != nil && pkg.Fset != nil {
filePath := filepath.Dir(pkg.Fset.Position(file.Package).Filename)
modelPkgPath = pkg.Module.Path + filePath[len(pkg.Module.Dir):]
}
modelPkgPath = strings.ReplaceAll(modelPkgPath, `\`, `/`)
modelPkgName = file.Name.Name
ast.Inspect(file, func(node ast.Node) bool {
decl, ok := node.(*ast.GenDecl)
if !ok || decl.Tok != token.TYPE {
return true
}
for _, s := range decl.Specs {
spec, ok := s.(*ast.TypeSpec)
if !ok {
continue
}
_, ok = g.modelNames[spec.Name.Name]
if !ok {
continue
}
st, ok := spec.Type.(*ast.StructType)
if !ok {
continue
}
model := newModel(g.opts)
model.setModelName(spec.Name.Name)
model.setModelPkg(modelPkgName, modelPkgPath)
model.setDaoPkgPath(daoPkgPath)
for _, item := range st.Fields.List {
name := item.Names[0].Name
if !isExportable(name) {
continue
}
field := &field{name: name, column: name}
if item.Tag != nil && len(item.Tag.Value) > 2 {
runes := []rune(item.Tag.Value)
if runes[0] != '`' || runes[len(runes)-1] != '`' {
continue
}
tag := reflect.StructTag(runes[1 : len(runes)-1])
if column := tag.Get("bson"); column != "" {
field.column = column
}
val, ok := tag.Lookup("gen")
if ok {
parts := strings.Split(val, ";")
for _, part := range parts {
if part == "" {
continue
}
switch eles := strings.SplitN(part, ":", 2); eles[0] {
case "autoFill":
expr, ok := item.Type.(*ast.SelectorExpr)
if !ok {
continue
}
switch fmt.Sprintf("%s.%s", expr.X.(*ast.Ident).Name, expr.Sel.Name) {
case "primitive.ObjectID":
field.autoFill = objectID
model.addImport(pkg3)
case "primitive.DateTime":
field.autoFill = dateTime
model.addImport(pkg1)
model.addImport(pkg3)
}
case "autoIncr":
if len(eles) != 2 || eles[1] == "" {
continue
}
expr, ok := item.Type.(*ast.Ident)
if !ok {
continue
}
switch expr.Name {
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64":
field.autoFill = autoIncr
field.autoIncrFieldName = eles[1]
if g.opts.subPkgEnable {
model.addImport(g.counter.daoPkgPath)
}
switch expr.Name {
case "int":
field.autoIncrFieldKind = reflect.Int
case "int8":
field.autoIncrFieldKind = reflect.Int8
case "int16":
field.autoIncrFieldKind = reflect.Int16
case "int32":
field.autoIncrFieldKind = reflect.Int32
case "int64":
field.autoIncrFieldKind = reflect.Int64
case "uint":
field.autoIncrFieldKind = reflect.Uint
case "uint8":
field.autoIncrFieldKind = reflect.Uint8
case "uint16":
field.autoIncrFieldKind = reflect.Uint16
case "uint32":
field.autoIncrFieldKind = reflect.Uint32
case "uint64":
field.autoIncrFieldKind = reflect.Uint64
}
}
}
}
}
}
if item.Doc != nil {
field.documents = make([]string, 0, len(item.Doc.List))
for _, doc := range item.Doc.List {
field.documents = append(field.documents, doc.Text)
}
}
if item.Comment != nil {
field.comment = item.Comment.List[0].Text
}
model.addFields(field)
}
models = append(models, model)
}
return true
})
}
return models
}
func (g *generator) loadPackage() *packages.Package {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedModule,
Tests: false,
}
pkgs, err := packages.Load(cfg, g.opts.modelDir)
if err != nil {
log.Fatal(err)
}
if len(pkgs) != 1 {
log.Fatalf("error: %d packages found", len(pkgs))
}
return pkgs[0]
}