/
utils.go
357 lines (326 loc) · 9.68 KB
/
utils.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
package common
import (
"context"
_ "embed"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gview"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"gopkg.in/yaml.v3"
"io/ioutil"
"os"
"path"
"regexp"
"sort"
"strings"
)
var (
ColumnTypeStr = []string{"char", "varchar", "varchar2", "tinytext", "text", "mediumtext", "longtext", "binary", "varbinary", "blob"}
ColumnTypeDate = []string{"date"}
ColumnTypeTime = []string{"datetime", "time", "timestamp"}
ColumnTypeNumber = []string{"tinyint", "smallint", "mediumint", "int", "integer", "bigint", "float", "double", "decimal", "numeric", "bit"}
ColumnNameNotEdit = []string{"created_by", "created_at", "updated_by", "updated_at", "deleted_at"}
ColumnNameNotList = []string{"updated_by", "updated_at", "deleted_at"}
ColumnNameNotDetail = []string{"updated_by", "updated_at", "deleted_at"}
ColumnNameNotQuery = []string{"updated_by", "updated_at", "deleted_at", "remark"}
)
// IsExistInArray 判断 value 是否存在在切片array中
func IsExistInArray(value string, array []string) bool {
for _, v := range array {
if v == value {
return true
}
}
return false
}
// GetColumnLength 获取字段长度
func GetColumnLength(columnType string) int {
start := strings.Index(columnType, "(")
end := strings.Index(columnType, ")")
result := ""
if start >= 0 && end >= 0 {
result = columnType[start+1 : end-1]
}
return gconv.Int(result)
}
// IsStringObject 判断是否是数据库字符串类型
func IsStringObject(dataType string) bool {
return IsExistInArray(dataType, ColumnTypeStr)
}
// IsDateObject 判断是否是数据库时间类型
func IsDateObject(dataType string) bool {
return IsExistInArray(dataType, ColumnTypeDate)
}
// IsTimeObject 判断是否是数据库时间类型
func IsTimeObject(dataType string) bool {
return IsExistInArray(dataType, ColumnTypeTime)
}
// IsNumberObject 是否数字类型
func IsNumberObject(dataType string) bool {
return IsExistInArray(dataType, ColumnTypeNumber)
}
func GetGoModuleName() (string, error) {
curDir, err := os.Getwd()
if err != nil {
return "", gerror.New("获取本地路径失败")
}
goModuleFile := path.Join(curDir, "go.mod")
if !gfile.Exists(goModuleFile) {
return "", gerror.New("请在项目根路径下运行本程序,并要求根路径存在go.mod")
}
return GetGoModule(goModuleFile)
}
func GetGoModule(file string) (string, error) {
goModContent, err := ioutil.ReadFile(file)
if err != nil {
return "", gerror.Newf("获取%s内容失败", file)
}
lines := gstr.Split(string(goModContent), "\n")
reGoModule, _ := regexp.Compile("module\\s+([^\\s]+)")
for _, line := range lines {
matches := reGoModule.FindStringSubmatch(line)
if len(matches) >= 1 {
return matches[1], nil
}
}
return "", gerror.Newf("%s文件中找不到module指令", file)
}
func getBusinessName(tableName string, tablePrefix []string) string {
return removeTablePrefix(tableName, tablePrefix)
}
// 删除表前缀
func removeTablePrefix(tableName string, tablePrefix []string) string {
if !g.IsEmpty(tablePrefix) {
for _, str := range tablePrefix {
if strings.HasPrefix(tableName, str) {
return strings.Replace(tableName, str, "", 1) //注意,只替换一次
}
}
}
return tableName
}
func LoadTableDefYaml(ctx context.Context, tableName string, yamlInputPath string, goModuleName string, cache map[string]*TableDef) (*TableDef, error) {
cached, found := cache[tableName]
if found {
return cached, nil
}
def, err := loadCodeDefYaml(ctx, tableName, yamlInputPath)
if err != nil {
return nil, err
}
table := &TableDef{}
err = gconv.Struct(def.Table, table)
if err != nil {
return nil, err
}
table.SetVariableNames(goModuleName)
table.ColumnMap = def.Columns
table.PkColumns = make(map[string]*ColumnDef)
table.VirtualColumnMap = def.VirtualColumns
table.Columns = columnsSlice(def.Columns, false)
table.VirtualColumns = columnsSlice(def.VirtualColumns, true)
table.AddColumns = addColumnsSlice(def.AddColumns)
table.EditColumns = editColumnsSlice(def.EditColumns)
table.ListColumns = listColumnsSlice(def.ListColumns)
table.QueryColumns = queryColumnsSlice(def.QueryColumns)
table.DetailColumns = detailColumnsSlice(def.DetailColumns)
createdAt, hasCreatedAt := table.ColumnMap["created_at"]
if hasCreatedAt {
table.CreatedAtColumn = createdAt
}
createBy, hasCreatedBy := table.ColumnMap["created_by"]
table.HasCreatedBy = hasCreatedBy
if hasCreatedBy {
table.CreatedByColumn = createBy
}
_, hasUpdateBy := table.ColumnMap["updated_by"]
table.HasUpdatedBy = hasUpdateBy
table.RefColumns = gmap.NewListMap()
table.VirtualQueryRelated = make(map[string]*TableDef)
err = table.ProcessColumns(ctx, yamlInputPath, goModuleName, cache)
if err != nil {
return nil, err
}
cache[tableName] = table
return table, nil
}
func loadCodeDefYaml(ctx context.Context, tableName string, yamlInputPath string) (*CodeGenDef, error) {
curDir, err := os.Getwd()
if err != nil {
return nil, gerror.New("获取本地路径失败")
}
yamlFile := path.Join(curDir, yamlInputPath, tableName+".yaml")
bytes, err1 := os.ReadFile(yamlFile)
if err1 != nil {
return nil, gerror.New("读取 " + yamlFile + " 失败")
}
var def = &CodeGenDef{}
err = yaml.Unmarshal(bytes, def)
return def, err
}
func TemplateEngine() *gview.View {
view := gview.New()
_ = view.SetConfigWithMap(g.Map{
"Delimiters": []string{"{{", "}}"},
})
view.BindFuncMap(g.Map{
"UcFirst": func(str string) string {
return gstr.UcFirst(str)
},
"Sum": func(a, b int) int {
return a + b
},
"CaseCamelLower": gstr.CaseCamelLower, //首字母小写驼峰
"CaseCamel": gstr.CaseCamel, //首字母大写驼峰
"CaseKebab": gstr.CaseKebab, //全小写短横线分隔
"HasSuffix": gstr.HasSuffix, //是否存在后缀
"ContainsI": gstr.ContainsI, //是否包含子字符串
"VueTag": func(t string) string {
return t
},
"IsEmpty": g.IsEmpty, //是否为空
"IsNotEmpty": func(value interface{}) bool {
return !g.IsEmpty(value)
},
})
return view
}
func TrimBreak(str string) (rStr string, err error) {
var b []byte
rStr = str
// 将连续多个换行换为一个
if b, err = gregex.Replace("(([ \t]*)\r?\n){2,}", []byte("\n"), []byte(str)); err != nil {
return
}
// 去掉行尾空格
if b, err = gregex.Replace("(?:(?:[ \t]+)\r?\n)", []byte("\n"), b); err != nil {
return
}
// 在函数结尾和 import 结尾增加一个空行
if b, err = gregex.Replace("(?:\n(////|[)}])\n)", []byte("\n$1\n\n"), b); err != nil {
return
}
// 在函数结尾和 import 结尾增加一个空行
if b, err = gregex.Replace("(?:\n(import(?:[ \t]+)?[(])\n)", []byte("\n\n$1\n"), b); err != nil {
return
}
rStr = gconv.String(b)
return
}
func WriteFile(fileName, data string, cover bool) (err error) {
if !gfile.Exists(fileName) || cover {
var f *os.File
f, err = gfile.Create(fileName)
if err == nil {
_, _ = f.WriteString(data)
}
_ = f.Close()
}
return
}
func GetDataType(sqlType string) (dataType string, isUnsigned bool) {
t, _ := gregex.ReplaceString(`\(.+\)`, "", sqlType)
typeSlice := gstr.Split(gstr.Trim(t), " ")
if len(typeSlice) > 1 {
isUnsigned = gstr.ToLower(typeSlice[1]) == "unsigned"
}
dataType = gstr.ToLower(typeSlice[0])
return
}
func SplitComma(str string) []string {
var result []string
if g.IsEmpty(gstr.Trim(str)) {
return result
}
temp := gstr.Split(str, ",")
for _, one := range temp {
oneTrimmed := gstr.Trim(one)
if !g.IsEmpty(oneTrimmed) {
result = append(result, oneTrimmed)
}
}
return result
}
func columnsSlice(columnMap map[string]*ColumnDef, isVirtual bool) []*ColumnDef {
columns := make([]*ColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
column.IsVirtual = isVirtual
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}
func listColumnsSlice(columnMap map[string]*ListColumnDef) []*ListColumnDef {
columns := make([]*ListColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}
func addColumnsSlice(columnMap map[string]*AddColumnDef) []*AddColumnDef {
columns := make([]*AddColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}
func editColumnsSlice(columnMap map[string]*EditColumnDef) []*EditColumnDef {
columns := make([]*EditColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}
func queryColumnsSlice(columnMap map[string]*QueryColumnDef) []*QueryColumnDef {
columns := make([]*QueryColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}
func detailColumnsSlice(columnMap map[string]*DetailColumnDef) []*DetailColumnDef {
columns := make([]*DetailColumnDef, len(columnMap))
i := 0
for name, column := range columnMap {
column.Name = name
columns[i] = column
i++
}
sort.Slice(columns, func(i, j int) bool {
return columns[i].Sort < columns[j].Sort
})
return columns
}