forked from smallnest/gen
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
1210 lines (1014 loc) · 37.5 KB
/
main.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"go/build"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
schema "github.com/cresta/jimsmart-schema"
_ "github.com/denisenkom/go-mssqldb"
"github.com/droundy/goopt"
"github.com/gobuffalo/packd"
"github.com/gobuffalo/packr/v2"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/lib/pq"
"github.com/logrusorgru/aurora"
_ "github.com/mattn/go-sqlite3"
"github.com/cresta/smallnest-gen/dbmeta"
)
var (
sqlType = goopt.String([]string{"--sqltype"}, "mysql", "sql database type such as [ mysql, mssql, postgres, sqlite, etc. ]")
sqlConnStr = goopt.String([]string{"-c", "--connstr"}, "nil", "database connection string")
sqlDatabase = goopt.String([]string{"-d", "--database"}, "nil", "Database to for connection")
sqlSchemas = goopt.String([]string{"-s", "--schemas"}, "nil", "Filter on tables of given schemas (one or more komma separated)")
sqlTable = goopt.String([]string{"-t", "--table"}, "", "Table to build struct from")
excludeSQLTables = goopt.String([]string{"-x", "--exclude"}, "", "Table(s) to exclude")
templateDir = goopt.String([]string{"--templateDir"}, "", "Template Dir")
fragmentsDir = goopt.String([]string{"--fragmentsDir"}, "", "Code fragments Dir")
saveTemplateDir = goopt.String([]string{"--save"}, "", "Save templates to dir")
modelPackageName = goopt.String([]string{"--model"}, "model", "name to set for model package")
modelNamingTemplate = goopt.String([]string{"--model_naming"}, "{{FmtFieldName .}}", "model naming template to name structs")
fieldNamingTemplate = goopt.String([]string{"--field_naming"}, "{{FmtFieldName (stringifyFirstChar .) }}", "field naming template to name structs")
fileNamingTemplate = goopt.String([]string{"--file_naming"}, "{{.}}", "file_naming template to name files")
daoPackageName = goopt.String([]string{"--dao"}, "dao", "name to set for dao package")
apiPackageName = goopt.String([]string{"--api"}, "api", "name to set for api package")
grpcPackageName = goopt.String([]string{"--grpc"}, "grpc", "name to set for grpc package")
outDir = goopt.String([]string{"--out"}, ".", "output dir")
module = goopt.String([]string{"--module"}, "example.com/example", "module path")
overwrite = goopt.Flag([]string{"--overwrite"}, []string{"--no-overwrite"}, "Overwrite existing files (default)", "disable overwriting files")
windows = goopt.Flag([]string{"--windows"}, []string{}, "use windows line endings in generated files", "")
noColorOutput = goopt.Flag([]string{"--no-color"}, []string{}, "disable color output", "")
contextFileName = goopt.String([]string{"--context"}, "", "context file (json) to populate context with")
mappingFileName = goopt.String([]string{"--mapping"}, "", "mapping file (json) to map sql types to golang/protobuf etc")
execCustomScript = goopt.String([]string{"--exec"}, "", "execute script for custom code generation")
addJSONAnnotation = goopt.Flag([]string{"--json"}, []string{"--no-json"}, "Add json annotations (default)", "Disable json annotations")
jsonNameFormat = goopt.String([]string{"--json-fmt"}, "snake", "json name format [snake | camel | lower_camel | none]")
addXMLAnnotation = goopt.Flag([]string{"--xml"}, []string{"--no-xml"}, "Add xml annotations (default)", "Disable xml annotations")
xmlNameFormat = goopt.String([]string{"--xml-fmt"}, "snake", "xml name format [snake | camel | lower_camel | none]")
addGormAnnotation = goopt.Flag([]string{"--gorm"}, []string{}, "Add gorm annotations (tags)", "")
addProtobufAnnotation = goopt.Flag([]string{"--protobuf"}, []string{}, "Add protobuf annotations (tags)", "")
protoNameFormat = goopt.String([]string{"--proto-fmt"}, "snake", "proto name format [snake | camel | lower_camel | none]")
gogoProtoImport = goopt.String([]string{"--gogo-proto"}, "", "location of gogo import ")
addDBAnnotation = goopt.Flag([]string{"--db"}, []string{}, "Add db annotations (tags)", "")
useGureguTypes = goopt.Flag([]string{"--guregu"}, []string{}, "Add guregu null types", "")
copyTemplates = goopt.Flag([]string{"--copy-templates"}, []string{}, "Copy regeneration templates to project directory", "")
modGenerate = goopt.Flag([]string{"--mod"}, []string{}, "Generate go.mod in output dir", "")
makefileGenerate = goopt.Flag([]string{"--makefile"}, []string{}, "Generate Makefile in output dir", "")
serverGenerate = goopt.Flag([]string{"--server"}, []string{}, "Generate server app output dir", "")
daoGenerate = goopt.Flag([]string{"--generate-dao"}, []string{}, "Generate dao functions", "")
projectGenerate = goopt.Flag([]string{"--generate-proj"}, []string{}, "Generate project readme and gitignore", "")
restAPIGenerate = goopt.Flag([]string{"--rest"}, []string{}, "Enable generating RESTful api", "")
runGoFmt = goopt.Flag([]string{"--run-gofmt"}, []string{}, "run gofmt on output dir", "")
serverListen = goopt.String([]string{"--listen"}, "", "listen address e.g. :8080")
serverScheme = goopt.String([]string{"--scheme"}, "http", "scheme for server url")
serverHost = goopt.String([]string{"--host"}, "localhost", "host for server")
serverPort = goopt.Int([]string{"--port"}, 8080, "port for server")
swaggerVersion = goopt.String([]string{"--swagger_version"}, "1.0", "swagger version")
swaggerBasePath = goopt.String([]string{"--swagger_path"}, "/", "swagger base path")
swaggerTos = goopt.String([]string{"--swagger_tos"}, "", "swagger tos url")
swaggerContactName = goopt.String([]string{"--swagger_contact_name"}, "Me", "swagger contact name")
swaggerContactURL = goopt.String([]string{"--swagger_contact_url"}, "http://me.com/terms.html", "swagger contact url")
swaggerContactEmail = goopt.String([]string{"--swagger_contact_email"}, "[email protected]", "swagger contact email")
verbose = goopt.Flag([]string{"-v", "--verbose"}, []string{}, "Enable verbose output", "")
nameTest = goopt.String([]string{"--name_test"}, "", "perform name test using the --model_naming or --file_naming options")
baseTemplates *packr.Box
tableInfos map[string]*dbmeta.ModelInfo
au aurora.Aurora
)
func init() {
// Setup goopts
goopt.Description = func() string {
return "ORM and RESTful API generator for SQl databases"
}
goopt.Version = "v0.9.27 (08/04/2020)"
goopt.Summary = `gen [-v] --sqltype=mysql --connstr "user:password@/dbname" --database <databaseName> --module=example.com/example [--json] [--gorm] [--guregu] [--generate-dao] [--generate-proj]
git fetch up
sqltype - sql database type such as [ mysql, mssql, postgres, sqlite, etc. ]
`
// Parse options
goopt.Parse(nil)
}
func saveTemplates() {
fmt.Printf("Saving templates to %s\n", *saveTemplateDir)
err := SaveAssets(*saveTemplateDir, baseTemplates)
if err != nil {
fmt.Printf("Error saving: %v\n", err)
}
}
func listTemplates() {
for i, file := range baseTemplates.List() {
fmt.Printf(" [%d] [%s]\n", i, file)
}
}
func loadContextMapping(conf *dbmeta.Config) error {
contextFile, err := os.Open(*contextFileName)
if err != nil {
return err
}
defer contextFile.Close()
jsonParser := json.NewDecoder(contextFile)
err = jsonParser.Decode(&conf.ContextMap)
if err != nil {
return err
}
fmt.Printf("Loaded Context from %s with %d defaults\n", *contextFileName, len(conf.ContextMap))
for key, value := range conf.ContextMap {
fmt.Printf(" Context:%s -> %v\n", key, value)
}
return nil
}
func main() {
//for i, arg := range os.Args {
// fmt.Printf("[%2d] %s\n", i, arg)
//}
au = aurora.NewAurora(!*noColorOutput)
dbmeta.InitColorOutput(au)
baseTemplates = packr.New("gen", "./template")
if *saveTemplateDir != "" {
saveTemplates()
return
}
if *serverListen == "" {
*serverListen = fmt.Sprintf(":%d", *serverPort)
}
if *serverScheme != "http" && *serverScheme != "https" {
*serverScheme = "http"
}
if *nameTest != "" {
fmt.Printf("Running name test\n")
fmt.Printf("table name: %s\n", *nameTest)
fmt.Printf("modelNamingTemplate: %s\n", *modelNamingTemplate)
result := dbmeta.Replace(*modelNamingTemplate, *nameTest)
fmt.Printf("model: %s\n", result)
fmt.Printf("fileNamingTemplate: %s\n", *fileNamingTemplate)
result = dbmeta.Replace(*modelNamingTemplate, *nameTest)
fmt.Printf("file: %s\n", result)
fmt.Printf("fieldNamingTemplate: %s\n", *fieldNamingTemplate)
result = dbmeta.Replace(*fieldNamingTemplate, *nameTest)
fmt.Printf("field: %s\n", result)
os.Exit(0)
return
}
// fmt.Printf("fieldNamingTemplate: %s\n", *fieldNamingTemplate)
// fmt.Printf("fileNamingTemplate: %s\n", *fileNamingTemplate)
// fmt.Printf("modelNamingTemplate: %s\n", *modelNamingTemplate)
// Username is required
if sqlConnStr == nil || *sqlConnStr == "" || *sqlConnStr == "nil" {
fmt.Print(au.Red("sql connection string is required! Add it with --connstr=s\n\n"))
fmt.Println(goopt.Usage())
return
}
if sqlDatabase == nil || *sqlDatabase == "" || *sqlDatabase == "nil" {
fmt.Print(au.Red("Database can not be null\n\n"))
fmt.Println(goopt.Usage())
return
}
db, err := initializeDB()
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in initializing db %v\n", err)))
os.Exit(1)
return
}
defer db.Close()
var dbTables []dbmeta.TableSchemaAndName
// parse or read tables
if *sqlTable != "" {
tableNames := strings.Split(*sqlTable, ",")
dbTables = make([]dbmeta.TableSchemaAndName, len(tableNames))
for i, tableName := range tableNames {
dbTables[i] = dbmeta.TableSchemaAndName{
TableName: tableName,
}
}
} else {
schemaTables, err := schema.TableNames(db)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in fetching tables information from %s information schema from %s\n", *sqlType, *sqlConnStr)))
os.Exit(1)
return
}
schemaViews, err := schema.ViewNames(db)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in fetching view information from %s information schema from %s\n", *sqlType, *sqlConnStr)))
os.Exit(1)
return
}
schemaMaterializedViews, err := schema.MaterializedViewNames(db)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in fetching materialized view information from %s information schema from %s\n", *sqlType, *sqlConnStr)))
os.Exit(1)
return
}
for _, st := range schemaTables {
dbTables = append(dbTables, dbmeta.TableSchemaAndName{
TableSchema: st[0],
TableName: st[1],
})
}
for _, st := range schemaViews {
dbTables = append(dbTables, dbmeta.TableSchemaAndName{
TableSchema: st[0],
TableName: st[1],
})
}
for _, st := range schemaMaterializedViews {
dbTables = append(dbTables, dbmeta.TableSchemaAndName{
TableSchema: st[0],
TableName: st[1],
})
}
}
if strings.HasPrefix(*modelNamingTemplate, "'") && strings.HasSuffix(*modelNamingTemplate, "'") {
*modelNamingTemplate = strings.TrimSuffix(*modelNamingTemplate, "'")
*modelNamingTemplate = strings.TrimPrefix(*modelNamingTemplate, "'")
}
var excludeDbTables []string
if *excludeSQLTables != "" {
excludeDbTables = strings.Split(*excludeSQLTables, ",")
}
conf := dbmeta.NewConfig(LoadTemplate)
initialize(conf)
err = loadDefaultDBMappings(conf)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error processing default mapping file error: %v\n", err)))
os.Exit(1)
return
}
if *mappingFileName != "" {
err := dbmeta.LoadMappings(*mappingFileName, *verbose)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading mappings file %s error: %v\n", *mappingFileName, err)))
os.Exit(1)
return
}
}
if *contextFileName != "" {
err = loadContextMapping(conf)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading context file %s error: %v\n", *contextFileName, err)))
os.Exit(1)
return
}
}
// Filter on schemas when provided
var schemas map[string]bool
if len(*sqlSchemas) > 0 && *sqlSchemas != "nil" {
schemas = make(map[string]bool, 0)
for _, schema := range strings.Split(*sqlSchemas, ",") {
schemas[schema] = true
}
}
tableInfos = dbmeta.LoadTableInfo(db, &schemas, dbTables, excludeDbTables, conf)
if len(tableInfos) == 0 {
fmt.Print(au.Red(fmt.Sprintf("No tables loaded\n")))
os.Exit(1)
}
fmt.Printf("Generating code for the following tables (%d)\n", len(tableInfos))
i := 0
for _, tableInfo := range tableInfos {
fmt.Printf("[%d] %v\n", i, tableInfo.TableSchemaAndName)
i++
}
conf.TableInfos = tableInfos
conf.ContextMap["tableInfos"] = tableInfos
if *execCustomScript != "" {
err = executeCustomScript(conf)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in executing custom script %v\n", err)))
os.Exit(1)
}
os.Exit(0)
return
}
if *verbose {
listTemplates()
}
err = generate(conf)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in executing generate %v\n", err)))
os.Exit(1)
}
os.Exit(0)
}
func initializeDB() (db *sql.DB, err error) {
db, err = sql.Open(*sqlType, *sqlConnStr)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in open database: %v\n\n", err.Error())))
return nil, err
}
err = db.Ping()
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error pinging database: %v\n\n", err.Error())))
return
}
return
}
func initialize(conf *dbmeta.Config) {
if outDir == nil || *outDir == "" {
*outDir = "."
}
// load fragments if specified
if fragmentsDir != nil && *fragmentsDir != "" {
conf.LoadFragments(*fragmentsDir)
}
// if packageName is not set we need to default it
if modelPackageName == nil || *modelPackageName == "" {
*modelPackageName = "model"
}
if daoPackageName == nil || *daoPackageName == "" {
*daoPackageName = "dao"
}
if apiPackageName == nil || *apiPackageName == "" {
*apiPackageName = "api"
}
conf.SQLType = *sqlType
conf.SQLDatabase = *sqlDatabase
conf.AddJSONAnnotation = *addJSONAnnotation
conf.AddXMLAnnotation = *addXMLAnnotation
conf.AddGormAnnotation = *addGormAnnotation
conf.AddProtobufAnnotation = *addProtobufAnnotation
conf.AddDBAnnotation = *addDBAnnotation
conf.UseGureguTypes = *useGureguTypes
conf.JSONNameFormat = *jsonNameFormat
conf.XMLNameFormat = *xmlNameFormat
conf.ProtobufNameFormat = *protoNameFormat
conf.Verbose = *verbose
conf.OutDir = *outDir
conf.Overwrite = *overwrite
conf.LineEndingCRLF = *windows
conf.SQLConnStr = *sqlConnStr
conf.ServerPort = *serverPort
conf.ServerHost = *serverHost
conf.ServerScheme = *serverScheme
conf.ServerListen = *serverListen
conf.Module = *module
conf.ModelPackageName = *modelPackageName
conf.ModelFQPN = *module + "/" + *modelPackageName
conf.DaoPackageName = *daoPackageName
conf.DaoFQPN = *module + "/" + *daoPackageName
conf.APIPackageName = *apiPackageName
conf.APIFQPN = *module + "/" + *apiPackageName
conf.GrpcPackageName = *grpcPackageName
conf.GrpcFQPN = *module + "/" + *grpcPackageName
conf.FileNamingTemplate = *fileNamingTemplate
conf.ModelNamingTemplate = *modelNamingTemplate
conf.FieldNamingTemplate = *fieldNamingTemplate
conf.Swagger.Version = *swaggerVersion
conf.Swagger.BasePath = *swaggerBasePath
conf.Swagger.Title = fmt.Sprintf("Sample CRUD api for %s db", *sqlDatabase)
conf.Swagger.Description = fmt.Sprintf("Sample CRUD api for %s db", *sqlDatabase)
conf.Swagger.TOS = *swaggerTos
conf.Swagger.ContactName = *swaggerContactName
conf.Swagger.ContactURL = *swaggerContactURL
conf.Swagger.ContactEmail = *swaggerContactEmail
if *serverPort == 80 {
conf.Swagger.Host = *serverHost
} else {
conf.Swagger.Host = fmt.Sprintf("%s:%d", *serverHost, *serverPort)
}
conf.JSONNameFormat = strings.ToLower(conf.JSONNameFormat)
conf.XMLNameFormat = strings.ToLower(conf.XMLNameFormat)
conf.ProtobufNameFormat = strings.ToLower(conf.ProtobufNameFormat)
}
func loadDefaultDBMappings(conf *dbmeta.Config) error {
var err error
var content []byte
content, err = baseTemplates.Find("mapping.json")
if err != nil {
return err
}
err = dbmeta.ProcessMappings("internal", content, conf.Verbose)
if err != nil {
return err
}
return nil
}
func executeCustomScript(conf *dbmeta.Config) error {
fmt.Printf("Executing script %s\n", *execCustomScript)
b, err := ioutil.ReadFile(*execCustomScript)
if err != nil {
fmt.Printf("Error Loading exec script: %s, error: %v\n", *execCustomScript, err)
return err
}
data := map[string]interface{}{}
absPath, err := filepath.Abs(*execCustomScript)
if err != nil {
absPath = *execCustomScript
}
tpl := &dbmeta.GenTemplate{Name: absPath, Content: string(b)}
err = execTemplate(conf, tpl, data)
if err != nil {
fmt.Printf("Error Loading exec script: %s, error: %v\n", *execCustomScript, err)
return err
}
return nil
}
func execTemplate(conf *dbmeta.Config, genTemplate *dbmeta.GenTemplate, data map[string]interface{}) error {
data["DatabaseName"] = *sqlDatabase
data["module"] = *module
data["modelFQPN"] = conf.ModelFQPN
data["daoFQPN"] = conf.DaoFQPN
data["apiFQPN"] = conf.APIFQPN
data["modelPackageName"] = *modelPackageName
data["daoPackageName"] = *daoPackageName
data["apiPackageName"] = *apiPackageName
data["sqlType"] = *sqlType
data["sqlConnStr"] = *sqlConnStr
data["serverPort"] = *serverPort
data["serverHost"] = *serverHost
data["serverListen"] = *serverListen
data["SwaggerInfo"] = conf.Swagger
data["tableInfos"] = tableInfos
data["CommandLine"] = conf.CmdLine
data["outDir"] = *outDir
data["Config"] = conf
tables := make([]string, 0, len(tableInfos))
for k := range tableInfos {
tables = append(tables, k)
}
data["tables"] = tables
rt, err := conf.GetTemplate(genTemplate)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error in loading %s template, error: %v\n", genTemplate.Name, err)))
return err
}
var buf bytes.Buffer
err = rt.Execute(&buf, data)
if err != nil {
fmt.Printf("Error in rendering %s: %s\n", genTemplate.Name, err.Error())
return err
}
fmt.Printf("%s\n", buf.String())
return nil
}
func generate(conf *dbmeta.Config) error {
var err error
*jsonNameFormat = strings.ToLower(*jsonNameFormat)
*xmlNameFormat = strings.ToLower(*xmlNameFormat)
modelDir := filepath.Join(*outDir, *modelPackageName)
apiDir := filepath.Join(*outDir, *apiPackageName)
daoDir := filepath.Join(*outDir, *daoPackageName)
err = os.MkdirAll(*outDir, 0777)
if err != nil && !*overwrite {
fmt.Print(au.Red(fmt.Sprintf("unable to create outDir: %s error: %v\n", *outDir, err)))
return err
}
err = os.MkdirAll(modelDir, 0777)
if err != nil && !*overwrite {
fmt.Print(au.Red(fmt.Sprintf("unable to create modelDir: %s error: %v\n", modelDir, err)))
return err
}
if *daoGenerate {
err = os.MkdirAll(daoDir, 0777)
if err != nil && !*overwrite {
fmt.Print(au.Red(fmt.Sprintf("unable to create daoDir: %s error: %v\n", daoDir, err)))
return err
}
}
if *restAPIGenerate {
err = os.MkdirAll(apiDir, 0777)
if err != nil && !*overwrite {
fmt.Print(au.Red(fmt.Sprintf("unable to create apiDir: %s error: %v\n", apiDir, err)))
return err
}
}
var ModelTmpl *dbmeta.GenTemplate
var ModelBaseTmpl *dbmeta.GenTemplate
var ControllerTmpl *dbmeta.GenTemplate
var DaoTmpl *dbmeta.GenTemplate
var DaoInitTmpl *dbmeta.GenTemplate
var GoModuleTmpl *dbmeta.GenTemplate
if ControllerTmpl, err = LoadTemplate("api.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
if *addGormAnnotation {
if DaoTmpl, err = LoadTemplate("dao_gorm.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
if DaoInitTmpl, err = LoadTemplate("dao_gorm_init.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
} else {
if DaoTmpl, err = LoadTemplate("dao_sqlx.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
if DaoInitTmpl, err = LoadTemplate("dao_sqlx_init.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
}
if GoModuleTmpl, err = LoadTemplate("gomod.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
if ModelTmpl, err = LoadTemplate("model.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
if ModelBaseTmpl, err = LoadTemplate("model_base.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
*jsonNameFormat = strings.ToLower(*jsonNameFormat)
*xmlNameFormat = strings.ToLower(*xmlNameFormat)
// generate go files for each table
for tableName, tableInfo := range tableInfos {
if len(tableInfo.Fields) == 0 {
if *verbose {
fmt.Printf("[%d] Table: %v - No Fields Available\n", tableInfo.Index, tableInfo.TableSchemaAndName)
}
continue
}
modelInfo := conf.CreateContextForTableFile(tableInfo)
modelFile := filepath.Join(modelDir, CreateGoSrcFileName(tableName))
err = conf.WriteTemplate(ModelTmpl, modelInfo, modelFile)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
if *restAPIGenerate {
restFile := filepath.Join(apiDir, CreateGoSrcFileName(tableName))
err = conf.WriteTemplate(ControllerTmpl, modelInfo, restFile)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
}
if *daoGenerate {
// write dao
outputFile := filepath.Join(daoDir, CreateGoSrcFileName(tableName))
err = conf.WriteTemplate(DaoTmpl, modelInfo, outputFile)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
}
}
data := map[string]interface{}{}
if *restAPIGenerate {
if err = generateRestBaseFiles(conf, apiDir); err != nil {
return err
}
}
if *daoGenerate {
err = conf.WriteTemplate(DaoInitTmpl, data, filepath.Join(daoDir, "dao_base.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
}
err = conf.WriteTemplate(ModelBaseTmpl, data, filepath.Join(modelDir, "model_base.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
if *modGenerate {
err = conf.WriteTemplate(GoModuleTmpl, data, filepath.Join(*outDir, "go.mod"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
}
if *makefileGenerate {
if err = generateMakefile(conf); err != nil {
return err
}
}
if *addProtobufAnnotation {
if err = generateProtobufDefinitionFile(conf, data); err != nil {
return err
}
}
data = map[string]interface{}{
"deps": "go list -f '{{ join .Deps \"\\n\"}}' .",
"CommandLine": conf.CmdLine,
"Config": conf,
}
if *projectGenerate {
if err = generateProjectFiles(conf, data); err != nil {
return err
}
}
if *serverGenerate {
if err = generateServerCode(conf); err != nil {
return err
}
}
if *copyTemplates {
if err = copyTemplatesToTarget(); err != nil {
return err
}
}
if *runGoFmt {
GoFmt(conf.OutDir)
}
return nil
}
func generateRestBaseFiles(conf *dbmeta.Config, apiDir string) (err error) {
data := map[string]interface{}{}
var RouterTmpl *dbmeta.GenTemplate
var HTTPUtilsTmpl *dbmeta.GenTemplate
if HTTPUtilsTmpl, err = LoadTemplate("http_utils.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
if RouterTmpl, err = LoadTemplate("router.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
err = conf.WriteTemplate(RouterTmpl, data, filepath.Join(apiDir, "router.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
err = conf.WriteTemplate(HTTPUtilsTmpl, data, filepath.Join(apiDir, "http_utils.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
return nil
}
func generateMakefile(conf *dbmeta.Config) (err error) {
var MakefileTmpl *dbmeta.GenTemplate
if MakefileTmpl, err = LoadTemplate("Makefile.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
data := map[string]interface{}{
"deps": "go list -f '{{ join .Deps \"\\n\"}}' .",
"RegenCmdLineArgs": regenCmdLine(),
"RegenCmdLine": strings.Join(regenCmdLine(), " \\\n "),
}
if *addProtobufAnnotation {
populateProtoCinContext(conf, data)
}
err = conf.WriteTemplate(MakefileTmpl, data, filepath.Join(*outDir, "Makefile"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
return nil
}
func generateProtobufDefinitionFile(conf *dbmeta.Config, data map[string]interface{}) (err error) {
moduleDir := filepath.Join(*outDir, conf.ModelPackageName)
serverDir := filepath.Join(*outDir, conf.GrpcPackageName)
err = os.MkdirAll(serverDir, 0777)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("unable to create serverDir: %s error: %v\n", serverDir, err)))
return
}
var ProtobufTmpl *dbmeta.GenTemplate
if ProtobufTmpl, err = LoadTemplate("protobuf.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
protofile := fmt.Sprintf("%s.proto", *sqlDatabase)
err = conf.WriteTemplate(ProtobufTmpl, data, filepath.Join(*outDir, protofile))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
compileOutput, err := CompileProtoC(*outDir, moduleDir, filepath.Join(*outDir, protofile))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error compiling proto file %v\n", err)))
return err
}
fmt.Printf("----------------------------\n")
fmt.Printf("protoc: %s\n", compileOutput)
fmt.Printf("----------------------------\n")
// protoc -I./ --go_out=plugins=grpc:./ ./dvdrental.proto
if ProtobufTmpl, err = LoadTemplate("protomain.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
err = conf.WriteTemplate(ProtobufTmpl, data, filepath.Join(serverDir, "main.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
if ProtobufTmpl, err = LoadTemplate("protoserver.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return err
}
err = conf.WriteTemplate(ProtobufTmpl, data, filepath.Join(serverDir, "protoserver.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
return nil
}
func createProtocCmdLine(protoBufDir, protoBufOutDir, protoBufFile string) ([]string, error) {
if *gogoProtoImport != "" {
if !dbmeta.Exists(*gogoProtoImport) {
fmt.Print(au.Red(fmt.Sprintf("%s does not exist on path - install with\ngo get -u github.com/gogo/protobuf/proto\n\n", *gogoProtoImport)))
return nil, fmt.Errorf("supplied gogo proto location does not exist")
}
}
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = build.Default.GOPATH
}
srcPath := filepath.Join(gopath, "src")
gogoPath := filepath.Join(gopath, "src/github.com/gogo/protobuf/gogoproto/gogo.proto")
gogoImportExists := dbmeta.Exists(gogoPath)
// fmt.Printf("path : %s srcDirExists: %t\n", srcPath, srcDirExists)
// fmt.Printf("gogoPath: %s gogoImportExists: %t\n", gogoPath, gogoImportExists)
if !gogoImportExists {
fmt.Print(au.Red("github.com/gogo/protobuf/gogoproto/gogo.proto does not exist on path - install with\ngo get -u github.com/gogo/protobuf/proto\n\n"))
return nil, fmt.Errorf("github.com/gogo/protobuf/gogoproto/gogo.proto does not exist")
}
*gogoProtoImport = srcPath
fmt.Printf("----------------------------\n")
args := []string{
fmt.Sprintf("-I%s", *gogoProtoImport),
fmt.Sprintf("-I%s", protoBufDir),
fmt.Sprintf("--gogo_out=plugins=grpc,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/empty.proto=github.com/gogo/protobuf/types,Mgoogle/api/annotations.proto=github.com/gogo/googleapis/google/api,Mmodel.proto:%s", protoBufOutDir),
// fmt.Sprintf("--gogo_out=plugins=grpc:%s", protoBufOutDir),
fmt.Sprintf("%s", protoBufFile),
}
return args, nil
}
// CompileProtoC exec protoc for proto file, returns stdout result or error
func CompileProtoC(protoBufDir, protoBufOutDir, protoBufFile string) (string, error) {
args, err := createProtocCmdLine(protoBufDir, protoBufOutDir, protoBufFile)
if err != nil {
return "", err
}
cmd := exec.Command("protoc", args...)
cmdLineArgs := strings.Join(args, " ")
fmt.Printf("protoc %s\n", cmdLineArgs)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("error calling protoc: %T %v\n", err, err)))
fmt.Print(au.Red(fmt.Sprintf("%s\n", stdoutStderr)))
return "", err
}
return string(stdoutStderr), nil
}
// GoFmt exec gofmt for a code dir
func GoFmt(codeDir string) (string, error) {
args := []string{"-s", "-d", "-w", "-l", codeDir}
cmd := exec.Command("gofmt", args...)
cmdLineArgs := strings.Join(args, " ")
fmt.Printf("gofmt %s\n", cmdLineArgs)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("error calling protoc: %T %v\n", err, err)))
fmt.Print(au.Red(fmt.Sprintf("%s\n", stdoutStderr)))
return "", err
}
return string(stdoutStderr), nil
}
func generateProjectFiles(conf *dbmeta.Config, data map[string]interface{}) (err error) {
var GitIgnoreTmpl *dbmeta.GenTemplate
if GitIgnoreTmpl, err = LoadTemplate("gitignore.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
var ReadMeTmpl *dbmeta.GenTemplate
if ReadMeTmpl, err = LoadTemplate("README.md.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
populateProtoCinContext(conf, data)
err = conf.WriteTemplate(GitIgnoreTmpl, data, filepath.Join(*outDir, ".gitignore"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
err = conf.WriteTemplate(ReadMeTmpl, data, filepath.Join(*outDir, "README.md"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
return nil
}
func populateProtoCinContext(conf *dbmeta.Config, data map[string]interface{}) {
protofile := fmt.Sprintf("%s.proto", *sqlDatabase)
moduleDir := filepath.Join(*outDir, conf.ModelPackageName)
protocCmdLineArgs, err := createProtocCmdLine(*outDir, moduleDir, filepath.Join(*outDir, protofile))
if err != nil {
protoC := []string{"gen"}
protoC = append(protoC, protocCmdLineArgs...)
data["ProtocCmdLineArgs"] = protoC
data["ProtocCmdLine"] = strings.Join(protoC, " \\\n ")
}
}
func generateServerCode(conf *dbmeta.Config) (err error) {
data := map[string]interface{}{}
var MainServerTmpl *dbmeta.GenTemplate
if *addGormAnnotation {
if MainServerTmpl, err = LoadTemplate("main_gorm.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
} else {
if MainServerTmpl, err = LoadTemplate("main_sqlx.go.tmpl"); err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error loading template %v\n", err)))
return
}
}
serverDir := filepath.Join(*outDir, "app/server")
err = os.MkdirAll(serverDir, 0777)
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("unable to create serverDir: %s error: %v\n", serverDir, err)))
return
}
err = conf.WriteTemplate(MainServerTmpl, data, filepath.Join(serverDir, "main.go"))
if err != nil {
fmt.Print(au.Red(fmt.Sprintf("Error writing file: %v\n", err)))
os.Exit(1)
}
return nil
}
func copyTemplatesToTarget() (err error) {