/
autocode.go
375 lines (356 loc) · 11.1 KB
/
autocode.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
package atom
import (
"fmt"
"github.com/jtao539/autocode/util/database"
"go/build"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
var template string
const MODName = "github.com/jtao539/autocode/template"
const TPL = ".tpl"
type Atom struct {
Name string
TblName string
Path string
ModName string
Version string
}
type Model struct {
columnName string `db:"column_name"`
columnComment string `db:"column_comment"`
dataType string `db:"data_type"`
}
func (a *Atom) CreateModel() {
str := fmt.Sprintf("select column_name,column_comment,data_type from information_schema.columns where table_name='%s' and table_schema='%s' ORDER BY ORDINAL_POSITION", a.TblName, database.Name)
var list []Model
// err := db.GDB.DB.Select(&list, str)
query, err := database.GDB.DB.Query(str)
if err != nil {
fmt.Println(err)
return
}
for query.Next() {
m := Model{}
query.Scan(&m.columnName, &m.columnComment, &m.dataType)
list = append(list, m)
}
code := fmt.Sprintf("package model\n\nimport (\n\t\"database/sql\"\n\t\"github.com/jtao539/sqlxp\"\n)\n\ntype %s struct {\n", a.Name)
for i := 0; i < len(list); i++ {
m := list[i]
tag := fmt.Sprintf("`db:\"%s\" json:\"%s\"`", m.columnName, m.columnName)
switch m.dataType {
case "int", "tinyint", "bigint":
code += "\t" + Case2Camel(m.columnName) + " sql.NullInt32 " + tag + " // " + m.columnComment + "\n"
case "varchar":
code += "\t" + Case2Camel(m.columnName) + " sql.NullString " + tag + " // " + m.columnComment + "\n"
case "decimal":
code += "\t" + Case2Camel(m.columnName) + " sql.NullFloat64 " + tag + " // " + m.columnComment + "\n"
}
}
line := fmt.Sprintf("}\n\ntype %sDTO struct {\n", a.Name)
code += line
for i := 0; i < len(list); i++ {
m := list[i]
tag := fmt.Sprintf("`db:\"%s\" json:\"%s\"`", m.columnName, m.columnName)
if m.columnName == "create_time" || m.columnName == "create_user" || m.columnName == "create_user_id" {
continue
}
switch m.dataType {
case "int", "tinyint", "bigint":
code += "\t" + Case2Camel(m.columnName) + " int " + tag + " // " + m.columnComment + "\n"
case "varchar":
code += "\t" + Case2Camel(m.columnName) + " string " + tag + " // " + m.columnComment + "\n"
case "decimal":
code += "\t" + Case2Camel(m.columnName) + " float64 " + tag + " // " + m.columnComment + "\n"
}
}
lastLine := fmt.Sprintf("}\n\ntype %sReq struct {\n\tsqlxp.PageInfo\n\t%sDTO\n}\n\nfunc (%s) TableName() string {\n\treturn \"%s\"\n}", a.Name, a.Name, a.Name, a.TblName)
code += lastLine
fileName := Camel2Case(a.Name)
filePath := fmt.Sprintf("%s/model/%s.go", a.Path, fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "Model 完成")
}
func (a *Atom) CreateDB() {
global := fmt.Sprintf("%s/db/global.go", a.Path)
tempGlobal := fmt.Sprintf("%s/db/global%s", template, TPL)
if flag, _ := PathExists(global); !flag {
var code string
if bytes, err := ioutil.ReadFile(tempGlobal); err != nil {
log.Fatal("Failed to read file: " + tempGlobal)
} else {
code = string(bytes)
code = strings.ReplaceAll(code, MODName, a.ModName)
}
f, err := os.OpenFile(global, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
}
fileName := Camel2Case(a.Name)
filePath := fmt.Sprintf("%s/db/%s.go", a.Path, fileName)
tempFilePath := fmt.Sprintf("%s/db/department%s", template, TPL)
var str string
if bytes, err := ioutil.ReadFile(tempFilePath); err != nil {
log.Fatal("Failed to read file: " + tempFilePath)
} else {
str = string(bytes)
}
str = strings.ReplaceAll(str, MODName, a.ModName)
code := strings.ReplaceAll(str, "Department", a.Name)
code = strings.ReplaceAll(code, "department", fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "DB 完成")
}
func (a *Atom) CreateService() {
fileName := Camel2Case(a.Name)
filePath := fmt.Sprintf("%s/service/%s.go", a.Path, fileName)
tempFilePath := fmt.Sprintf("%s/service/department%s", template, TPL)
var str string
if bytes, err := ioutil.ReadFile(tempFilePath); err != nil {
log.Fatal("Failed to read file: " + tempFilePath)
} else {
str = string(bytes)
}
str = strings.ReplaceAll(str, MODName, a.ModName)
code := strings.ReplaceAll(str, "Department", a.Name)
code = strings.ReplaceAll(code, "department", fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "Service 完成")
}
func (a *Atom) CreateApi() {
fileName := Camel2Case(a.Name)
filePath := fmt.Sprintf("%s/api/%s.go", a.Path, fileName)
tempFilePath := fmt.Sprintf("%s/api/department%s", template, TPL)
var str string
if bytes, err := ioutil.ReadFile(tempFilePath); err != nil {
log.Fatal("Failed to read file: " + tempFilePath)
} else {
str = string(bytes)
}
str = strings.ReplaceAll(str, MODName, a.ModName)
code := strings.ReplaceAll(str, "Department", a.Name)
code = strings.ReplaceAll(code, "department", fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "api 完成")
}
func (a *Atom) CreateRouter() {
register := fmt.Sprintf("%s/router/register.go", a.Path)
tempRegister := fmt.Sprintf("%s/router/register%s", template, TPL)
if flag, _ := PathExists(register); !flag {
var code string
if bytes, err := ioutil.ReadFile(tempRegister); err != nil {
log.Fatal("Failed to read file: " + tempRegister)
} else {
code = string(bytes)
}
f, err := os.OpenFile(register, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
}
fileName := Camel2Case(a.Name)
filePath := fmt.Sprintf("%s/router/%s.go", a.Path, fileName)
tempFilePath := fmt.Sprintf("%s/router/department%s", template, TPL)
var str string
if bytes, err := ioutil.ReadFile(tempFilePath); err != nil {
log.Fatal("Failed to read file: " + tempFilePath)
} else {
str = string(bytes)
}
str = strings.ReplaceAll(str, MODName, a.ModName)
code := strings.ReplaceAll(str, "Department", a.Name)
code = strings.ReplaceAll(code, "department", fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "router 完成")
}
func (a *Atom) Clear() {
fileName := Camel2Case(a.Name)
pathArray := []string{"model", "db", "service", "api", "router"}
for i := 0; i < len(pathArray); i++ {
filePath := a.Path + "/" + pathArray[i] + "/" + fileName + ".go"
if flag, _ := PathExists(filePath); flag {
err := os.Remove(filePath)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(filePath, "清空成功")
}
}
fileNameS := strings.ToLower(a.Name)
pathArrayS := []string{"model", "db", "service", "api", "router"}
for i := 0; i < len(pathArray); i++ {
filePath := a.Path + "/" + pathArrayS[i] + "/" + fileNameS + ".go"
if flag, _ := PathExists(filePath); flag {
err := os.Remove(filePath)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(filePath, "清空成功")
}
}
}
func (a *Atom) MkSomeDir() {
pathArray := []string{"model", "db", "service", "api", "router", "common", "json", "config"}
for i := 0; i < len(pathArray); i++ {
MkDir(a.Path, pathArray[i])
}
innerArray := []string{"syserror", "request", "response", "util", "zlog"}
for i := 0; i < len(innerArray); i++ {
MkDir(a.Path+"/common", innerArray[i])
}
}
func MkDir(path, fileName string) {
filePath := path + "/" + fileName + "/"
if flag, _ := PathExists(filePath); !flag {
err := os.Mkdir(filePath, 0777)
if err != nil {
fmt.Println(err)
return
}
}
}
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
//当为空文件或文件夹存在
if err == nil {
return true, nil
}
//os.IsNotExist(err)为true,文件或文件夹不存在
if os.IsNotExist(err) {
return false, nil
}
//其它类型,不确定是否存在
return false, err
}
func (a *Atom) GeneralAutoCode() {
a.InitTemplate()
a.Clear()
a.MkSomeDir()
a.CreateError()
a.CreateResponse()
a.CreateRResponse()
a.CreateRequest()
a.CreateUtil()
a.CreateZLog()
a.CreateConfig()
a.CreateModel()
a.CreateDB()
a.CreateService()
a.CreateApi()
a.CreateRouter()
a.CreateJson()
}
func (a *Atom) CreateApiFile() {
str := fmt.Sprintf("select column_name,column_comment,data_type from information_schema.columns where table_name='%s' and table_schema='%s' ORDER BY ORDINAL_POSITION", a.TblName, database.Name)
var list []Model
// err := db.GDB.DB.Select(&list, str)
query, err := database.GDB.DB.Query(str)
if err != nil {
fmt.Println(err)
return
}
for query.Next() {
m := Model{}
query.Scan(&m.columnName, &m.columnComment, &m.dataType)
list = append(list, m)
}
// "id": 1, // 合同订单id
for i := 0; i < len(list); i++ {
m := list[i]
switch m.dataType {
case "int", "tinyint", "decimal":
fmt.Println("\"" + m.columnName + "\":1," + " // " + m.columnComment)
case "varchar":
fmt.Println("\"" + m.columnName + "\":\"\"," + " // " + m.columnComment)
}
}
fmt.Println(a.Name, "API 完成")
}
func (a *Atom) CreateJson() {
str := fmt.Sprintf("select column_name,column_comment,data_type from information_schema.columns where table_name='%s' and table_schema='%s' ORDER BY ORDINAL_POSITION", a.TblName, database.Name)
var list []Model
// err := db.GDB.DB.Select(&list, str)
query, err := database.GDB.DB.Query(str)
if err != nil {
fmt.Println(err)
return
}
for query.Next() {
m := Model{}
query.Scan(&m.columnName, &m.columnComment, &m.dataType)
list = append(list, m)
}
code := fmt.Sprintf("{\n")
for i := 0; i < len(list); i++ {
m := list[i]
switch m.dataType {
case "int", "tinyint":
code += "\t \"" + m.columnName + "\" : 1," + " // " + m.columnComment + "\n"
case "varchar", "timestamp":
code += "\t \"" + m.columnName + "\" : \"\"," + " // " + m.columnComment + "\n"
case "decimal":
code += "\t \"" + m.columnName + "\" : 1.1," + " // " + m.columnComment + "\n"
}
}
if strings.Contains(code, ",") {
code = fmt.Sprintf("%s%s", code[:strings.LastIndex(code, ",")], code[strings.LastIndex(code, ",")+1:])
}
line := fmt.Sprintf("}")
code += line
fileName := LowFirst(a.Name)
filePath := fmt.Sprintf("%s/json/%s.json", a.Path, fileName)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
f.Write([]byte(code))
defer f.Close()
fmt.Println(filePath, "Json 完成")
}
func (a *Atom) InitTemplate() {
template = build.Default.GOPATH + string(filepath.Separator) + "pkg" + string(filepath.Separator) + "mod" + string(filepath.Separator) + "github.com" + string(filepath.Separator) + "jtao539" + string(filepath.Separator) + "autocode@" + a.Version + string(filepath.Separator) + "template"
}