/
go-model-gen.go
105 lines (96 loc) · 2.55 KB
/
go-model-gen.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
package main
import (
"bytes"
_ "embed"
"encoding/json"
"flag"
"fmt"
"github.com/gertd/go-pluralize"
driver2 "github.com/xiaoshouchen/go-model-gen/driver"
"github.com/xiaoshouchen/go-model-gen/pkg"
"github.com/xiaoshouchen/go-model-gen/vars"
"go/format"
"html/template"
"log"
"os"
"syscall"
)
var dataSource = flag.String("f", "data_source.json", "文件地址")
var outputSource = flag.String("o", "./model/", "文件输出位置")
//go:embed tpl/model.tpl
var model string
//go:embed tpl/field.tpl
var field string
//go:embed tpl/insert.tpl
var insert string
//go:embed tpl/omit.tpl
var omit string
func main() {
var configs = make([]vars.DatabaseConfig, 0)
getConfig(&configs)
plur := pluralize.NewClient()
for _, config := range configs {
inst := driver2.GetInstance(config)
schemas := inst.GetTableStructure(config.Scheme, config.Tables)
err := os.Mkdir(*outputSource, 0777)
if err != nil && !os.IsExist(err) {
fmt.Println(err)
return
}
if len(schemas) > 0 {
for _, s := range schemas {
t, err := template.New("modelTpl").Funcs(template.FuncMap{
"lowCamel": pkg.LineToLowCamel,
"upCamel": pkg.LineToUpCamel,
"inline": pkg.Inline,
"singular": plur.Singular,
"plural": plur.Plural,
"transType": inst.TransType,
"containsNumber": pkg.ContainsNumber,
}).Parse(omit + insert + field + model)
if err != nil {
log.Fatal(err)
return
}
var buf = new(bytes.Buffer)
if err != nil {
log.Fatal(err)
return
}
err = t.ExecuteTemplate(buf, "modelTpl", s)
source, err := format.Source(buf.Bytes())
if err != nil {
fmt.Println(string(buf.Bytes()))
log.Fatal(s.TableName, err)
return
}
fileName := *outputSource + plur.Singular(s.TableName) + "_gen.go"
err = os.WriteFile(fileName, source, 0664)
if err != nil {
fmt.Println(err)
return
}
path := *outputSource + plur.Singular(s.TableName) + ".go"
if exists, err := pkg.FileExists(path); !exists || err != nil {
err = os.WriteFile(path, []byte("package model"), 0664)
if err != nil {
return
}
}
}
}
syscall.Exec("gofmt", []string{"-w", *outputSource}, []string{})
}
}
func getConfig(j *[]vars.DatabaseConfig) {
flag.Parse()
tables, err := os.ReadFile(*dataSource)
if err != nil {
fmt.Println("please create a data_source.json first")
}
var configMap = make(map[string][]vars.DatabaseConfig)
err = json.Unmarshal(tables, &configMap)
if configs, ok := configMap["databases"]; ok {
*j = configs
}
}