github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/modelgen/gen.go (about) 1 package modelgen 2 3 import ( 4 "go/types" 5 "path" 6 "path/filepath" 7 8 "github.com/machinefi/w3bstream/pkg/depends/gen/codegen" 9 "github.com/machinefi/w3bstream/pkg/depends/x/pkgx" 10 "github.com/machinefi/w3bstream/pkg/depends/x/stringsx" 11 ) 12 13 type Generator struct { 14 Config 15 pkg *pkgx.Pkg 16 mod *Model 17 } 18 19 func New(pkg *pkgx.Pkg) *Generator { return &Generator{pkg: pkg} } 20 21 func (g *Generator) Scan() { 22 for ident, obj := range g.pkg.TypesInfo.Defs { 23 if tn, ok := obj.(*types.TypeName); ok && tn.Name() == g.StructName { 24 if _, ok := tn.Type().Underlying().(*types.Struct); ok { 25 g.mod = NewModel(g.pkg, tn, g.pkg.CommentsOf(ident), &g.Config) 26 } 27 } 28 } 29 } 30 31 func (g *Generator) Output(cwd string) { 32 if g.mod == nil { 33 return 34 } 35 dir, _ := filepath.Rel(cwd, filepath.Dir(g.pkg.GoFiles[0])) 36 filename := codegen.GenerateFileSuffix(path.Join(dir, stringsx.LowerSnakeCase(g.StructName)+".go")) 37 f := codegen.NewFile(g.pkg.Name, filename) 38 g.mod.WriteTo(f) 39 _, _ = f.Write() 40 } 41 42 func GetModelByName(g *Generator, name string) *Model { 43 if g.StructName == name { 44 return g.mod 45 } 46 return nil 47 } 48 49 type Config struct { 50 StructName string 51 TableName string 52 Database string 53 54 WithComments bool 55 WithTableName bool 56 WithTableInterfaces bool 57 WithMethods bool 58 59 FieldPrimaryKey string 60 FieldKeyDeletedAt string 61 FieldKeyCreatedAt string 62 FieldKeyUpdatedAt string 63 } 64 65 func (g *Config) SetDefault() { 66 if g.FieldKeyDeletedAt == "" { 67 g.FieldKeyDeletedAt = "DeletedAt" 68 } 69 70 if g.FieldKeyCreatedAt == "" { 71 g.FieldKeyCreatedAt = "CreatedAt" 72 } 73 74 if g.FieldKeyUpdatedAt == "" { 75 g.FieldKeyUpdatedAt = "UpdatedAt" 76 } 77 78 if g.TableName == "" { 79 g.TableName = "t_" + stringsx.LowerSnakeCase(g.StructName) 80 } 81 }