github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/sqlx/gen/sql_func_generator.go (about) 1 package gen 2 3 import ( 4 "go/build" 5 "go/parser" 6 "go/types" 7 "path" 8 9 "golang.org/x/tools/go/loader" 10 11 "github.com/johnnyeven/libtools/codegen" 12 "github.com/johnnyeven/libtools/codegen/loaderx" 13 ) 14 15 type Config struct { 16 StructName string 17 TableName string 18 Database string 19 WithComments bool 20 WithTableInterfaces bool 21 22 FieldPrimaryKey string 23 FieldSoftDelete string 24 FieldCreatedAt string 25 FieldUpdatedAt string 26 27 ConstSoftDeleteTrue string 28 ConstSoftDeleteFalse string 29 } 30 31 func (g *Config) Defaults() { 32 if g.FieldSoftDelete == "" { 33 g.FieldSoftDelete = "Enabled" 34 } 35 36 if g.FieldCreatedAt == "" { 37 g.FieldCreatedAt = "CreateTime" 38 } 39 40 if g.FieldUpdatedAt == "" { 41 g.FieldUpdatedAt = "UpdateTime" 42 } 43 44 if g.ConstSoftDeleteTrue == "" { 45 g.ConstSoftDeleteTrue = "github.com/johnnyeven/libtools/courier/enumeration.BOOL__TRUE" 46 } 47 48 if g.ConstSoftDeleteFalse == "" { 49 g.ConstSoftDeleteFalse = "github.com/johnnyeven/libtools/courier/enumeration.BOOL__FALSE" 50 } 51 52 if g.TableName == "" { 53 g.TableName = toDefaultTableName(g.StructName) 54 } 55 } 56 57 type SqlFuncGenerator struct { 58 Config 59 pkgImportPath string 60 program *loader.Program 61 model *Model 62 } 63 64 func (g *SqlFuncGenerator) Load(cwd string) { 65 ldr := loader.Config{ 66 AllowErrors: true, 67 ParserMode: parser.ParseComments, 68 } 69 70 pkgImportPath := codegen.GetPackageImportPath(cwd) 71 ldr.Import(pkgImportPath) 72 73 p, err := ldr.Load() 74 if err != nil { 75 panic(err) 76 } 77 78 g.pkgImportPath = pkgImportPath 79 g.program = p 80 81 g.Defaults() 82 } 83 84 func (g *SqlFuncGenerator) Pick() { 85 for pkg, pkgInfo := range g.program.AllPackages { 86 if pkg.Path() != g.pkgImportPath { 87 continue 88 } 89 for ident, obj := range pkgInfo.Defs { 90 if typeName, ok := obj.(*types.TypeName); ok { 91 if typeName.Name() == g.StructName { 92 if _, ok := typeName.Type().Underlying().(*types.Struct); ok { 93 comments := loaderx.CommentsOf(g.program.Fset, ident, pkgInfo.Files...) 94 g.model = NewModel(g.program, typeName, comments, &g.Config) 95 } 96 } 97 98 } 99 } 100 } 101 } 102 103 func (g *SqlFuncGenerator) Output(cwd string) codegen.Outputs { 104 outputs := codegen.Outputs{} 105 106 if g.model != nil { 107 pkg, _ := build.Import(g.model.TypeName.Pkg().Path(), "", build.FindOnly) 108 outputs.Add(codegen.GeneratedSuffix(path.Join(pkg.Dir, codegen.ToLowerSnakeCase(g.StructName)+".go")), g.model.Render()) 109 } 110 111 return outputs 112 }