sys_auto_code.go 14.8 KB
Newer Older
1
package system
2 3

import (
4
	"encoding/json"
m0_50812349's avatar
m0_50812349 已提交
5
	"errors"
S
songzhibin97 已提交
6
	"fmt"
7
	"io/ioutil"
8
	"os"
m0_50812349's avatar
m0_50812349 已提交
9
	"path/filepath"
S
songzhibin97 已提交
10
	"strconv"
11
	"strings"
12
	"text/template"
13

14 15 16
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
S
songzhibin97 已提交
17

18
	"gorm.io/gorm"
19 20
)

21
const (
22
	autoPath = "autocode_template/"
23 24 25
	basePath = "resource/template"
)

S
songzhibin97 已提交
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
var injectionPaths []injectionMeta

func Init() {
	if len(injectionPaths) != 0 {
		return
	}
	injectionPaths = []injectionMeta{
		{
			path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go"),
			funcName:    "MysqlTables",
			structNameF: "autocode.%s{},",
		},
		{
			path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go"),
			funcName:    "Routers",
			structNameF: "autocodeRouter.Init%sRouter(PrivateGroup)",
		},
		{
			path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, "enter.go"),
			funcName:    "ApiGroup",
			structNameF: "%sApi",
		},
		{
			path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRouter, "enter.go"),
			funcName:    "RouterGroup",
			structNameF: "%sRouter",
		},
		{
			path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, "enter.go"),
			funcName:    "ServiceGroup",
			structNameF: "%sService",
		},
	}
}

type injectionMeta struct {
	path        string
	funcName    string
	structNameF string // 带格式化的
}

72
type tplData struct {
m0_50812349's avatar
m0_50812349 已提交
73 74 75 76
	template         *template.Template
	locationPath     string
	autoCodePath     string
	autoMoveFilePath string
77 78
}

S
songzhibin97 已提交
79
type AutoCodeService struct{}
80 81 82

var AutoCodeServiceApp = new(AutoCodeService)

83 84 85 86 87 88
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: PreviewTemp
//@description: 预览创建代码
//@param: model.AutoCodeStruct
//@return: map[string]string, error

89
func (autoCodeService *AutoCodeService) PreviewTemp(autoCode system.AutoCodeStruct) (map[string]string, error) {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
90
	makeDictTypes(&autoCode)
91
	dataList, _, needMkdir, err := autoCodeService.getNeedList(&autoCode)
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
	if err != nil {
		return nil, err
	}

	// 写入文件前,先创建文件夹
	if err = utils.CreateDir(needMkdir...); err != nil {
		return nil, err
	}

	// 创建map
	ret := make(map[string]string)

	// 生成map
	for _, value := range dataList {
		ext := ""
		if ext = filepath.Ext(value.autoCodePath); ext == ".txt" {
			continue
		}
S
songzhibin97 已提交
110
		f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0o755)
111 112 113 114 115 116 117
		if err != nil {
			return nil, err
		}
		if err = value.template.Execute(f, autoCode); err != nil {
			return nil, err
		}
		_ = f.Close()
S
songzhibin97 已提交
118
		f, err = os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_RDONLY, 0o755)
119 120 121 122
		if err != nil {
			return nil, err
		}
		builder := strings.Builder{}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
123
		builder.WriteString("```")
124

Mr.奇淼('s avatar
Mr.奇淼( 已提交
125 126 127 128
		if ext != "" && strings.Contains(ext, ".") {
			builder.WriteString(strings.Replace(ext, ".", "", -1))
		}
		builder.WriteString("\n\n")
129 130 131 132 133
		data, err := ioutil.ReadAll(f)
		if err != nil {
			return nil, err
		}
		builder.Write(data)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
134
		builder.WriteString("\n\n```")
135

136
		pathArr := strings.Split(value.autoCodePath, string(os.PathSeparator))
Mr.奇淼('s avatar
Mr.奇淼( 已提交
137
		ret[pathArr[1]+"-"+pathArr[3]] = builder.String()
138 139 140 141 142 143 144 145 146 147 148
		_ = f.Close()

	}
	defer func() { // 移除中间文件
		if err := os.RemoveAll(autoPath); err != nil {
			return
		}
	}()
	return ret, nil
}

Mr.奇淼('s avatar
Mr.奇淼( 已提交
149 150 151 152 153 154 155 156
func makeDictTypes(autoCode *system.AutoCodeStruct) {
	DictTypeM := make(map[string]string)
	for _, v := range autoCode.Fields {
		if v.DictType != "" {
			DictTypeM[v.DictType] = ""
		}
	}

S
songzhibin97 已提交
157
	for k := range DictTypeM {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
158 159 160 161
		autoCode.DictTypes = append(autoCode.DictTypes, k)
	}
}

m0_50812349's avatar
m0_50812349 已提交
162 163 164 165
//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateTemp
//@description: 创建代码
//@param: model.AutoCodeStruct
何秀钢 已提交
166
//@return: err error
Mr.奇淼('s avatar
Mr.奇淼( 已提交
167

168
func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruct, ids ...uint) (err error) {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
169
	makeDictTypes(&autoCode)
S
songzhibin97 已提交
170 171 172 173
	// 增加判断: 重复创建struct
	if autoCode.AutoMoveFile && AutoCodeHistoryServiceApp.Repeat(autoCode.StructName) {
		return RepeatErr
	}
174
	dataList, fileList, needMkdir, err := autoCodeService.getNeedList(&autoCode)
175 176 177
	if err != nil {
		return err
	}
178
	meta, _ := json.Marshal(autoCode)
179 180 181 182 183 184 185
	// 写入文件前,先创建文件夹
	if err = utils.CreateDir(needMkdir...); err != nil {
		return err
	}

	// 生成文件
	for _, value := range dataList {
S
songzhibin97 已提交
186
		f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0o755)
187 188 189
		if err != nil {
			return err
		}
190
		if err = value.template.Execute(f, autoCode); err != nil {
191 192
			return err
		}
193
		_ = f.Close()
194
	}
195

m0_50812349's avatar
m0_50812349 已提交
196
	defer func() { // 移除中间文件
V
v_zhibsong 已提交
197 198 199 200
		if err := os.RemoveAll(autoPath); err != nil {
			return
		}
	}()
201 202 203 204 205 206 207
	bf := strings.Builder{}
	idBf := strings.Builder{}
	injectionCodeMeta := strings.Builder{}
	for _, id := range ids {
		idBf.WriteString(strconv.Itoa(int(id)))
		idBf.WriteString(";")
	}
m0_50812349's avatar
m0_50812349 已提交
208
	if autoCode.AutoMoveFile { // 判断是否需要自动转移
S
songzhibin97 已提交
209
		Init()
210 211
		for index := range dataList {
			autoCodeService.addAutoMoveFile(&dataList[index])
m0_50812349's avatar
m0_50812349 已提交
212
		}
S
songzhibin97 已提交
213 214 215 216 217 218
		// 判断目标文件是否都可以移动
		for _, value := range dataList {
			if utils.FileExist(value.autoMoveFilePath) {
				return errors.New(fmt.Sprintf("目标文件已存在:%s\n", value.autoMoveFilePath))
			}
		}
m0_50812349's avatar
m0_50812349 已提交
219
		for _, value := range dataList { // 移动文件
m0_50812349's avatar
m0_50812349 已提交
220
			if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
V
v_zhibsong 已提交
221 222 223
				return err
			}
		}
S
songzhibin97 已提交
224
		err = injectionCode(autoCode.StructName, &injectionCodeMeta)
225
		if err != nil {
S
songzhibin97 已提交
226
			return
227
		}
S
songzhibin97 已提交
228 229 230 231 232 233 234 235
		// 保存生成信息
		for _, data := range dataList {
			if len(data.autoMoveFilePath) != 0 {
				bf.WriteString(data.autoMoveFilePath)
				bf.WriteString(";")
			}
		}

236
		if global.GVA_CONFIG.AutoCode.TransferRestart {
S
songzhibin97 已提交
237 238 239
			// endless 会复用之前的指令
			// 如果是你 goland debug/run 后用的还是之前打包的文件,没有做到真正意义上的重启
			// 故此,拿掉迁移后的重启功能
S
songzhibin97 已提交
240
		}
m0_50812349's avatar
m0_50812349 已提交
241
	} else { // 打包
242
		if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
V
v_zhibsong 已提交
243 244
			return err
		}
245
	}
246 247
	if autoCode.AutoMoveFile || autoCode.AutoCreateApiToSql {
		if autoCode.TableName != "" {
248
			err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
249
				string(meta),
250 251
				autoCode.StructName,
				autoCode.Description,
252 253 254 255 256 257
				bf.String(),
				injectionCodeMeta.String(),
				autoCode.TableName,
				idBf.String(),
			)
		} else {
258
			err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
259
				string(meta),
260 261
				autoCode.StructName,
				autoCode.Description,
262 263 264 265 266 267
				bf.String(),
				injectionCodeMeta.String(),
				autoCode.StructName,
				idBf.String(),
			)
		}
268 269 270 271 272
	}
	if err != nil {
		return err
	}
	if autoCode.AutoMoveFile {
273
		return system.AutoMoveErr
274
	}
275 276
	return nil
}
277

m0_50812349's avatar
m0_50812349 已提交
278 279 280 281 282 283
//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetAllTplFile
//@description: 获取 pathName 文件夹下所有 tpl 文件
//@param: pathName string, fileList []string
//@return: []string, error

284
func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList []string) ([]string, error) {
285 286 287
	files, err := ioutil.ReadDir(pathName)
	for _, fi := range files {
		if fi.IsDir() {
288
			fileList, err = autoCodeService.GetAllTplFile(pathName+"/"+fi.Name(), fileList)
289 290 291 292 293 294 295 296 297 298 299
			if err != nil {
				return nil, err
			}
		} else {
			if strings.HasSuffix(fi.Name(), ".tpl") {
				fileList = append(fileList, pathName+"/"+fi.Name())
			}
		}
	}
	return fileList, err
}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
300

m0_50812349's avatar
m0_50812349 已提交
301 302 303
//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetDB
//@description: 获取指定数据库和指定数据表的所有字段名,类型值等
何秀钢 已提交
304 305
//@param: tableName string, dbName string
//@return: err error, Columns []request.ColumnReq
m0_50812349's avatar
m0_50812349 已提交
306

307
func (autoCodeService *AutoCodeService) DropTable(tableName string) error {
S
songzhibin97 已提交
308 309 310
	return global.GVA_DB.Exec("DROP TABLE " + tableName).Error
}

m0_50812349's avatar
m0_50812349 已提交
311 312 313 314 315 316
//@author: [SliverHorn](https://github.com/SliverHorn)
//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: addAutoMoveFile
//@description: 生成对应的迁移文件路径
//@param: *tplData
//@return: null
S
songzhibin97 已提交
317

318
func (autoCodeService *AutoCodeService) addAutoMoveFile(data *tplData) {
S
songzhibin97 已提交
319
	base := filepath.Base(data.autoCodePath)
320 321 322 323 324 325 326
	fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
	n := len(fileSlice)
	if n <= 2 {
		return
	}
	if strings.Contains(fileSlice[1], "server") {
		if strings.Contains(fileSlice[n-2], "router") {
S
songzhibin97 已提交
327 328
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
				global.GVA_CONFIG.AutoCode.SRouter, base)
329
		} else if strings.Contains(fileSlice[n-2], "api") {
S
songzhibin97 已提交
330 331
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
332
		} else if strings.Contains(fileSlice[n-2], "service") {
S
songzhibin97 已提交
333 334
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
335
		} else if strings.Contains(fileSlice[n-2], "model") {
S
songzhibin97 已提交
336 337
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
338
		} else if strings.Contains(fileSlice[n-2], "request") {
S
songzhibin97 已提交
339 340
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
m0_50812349's avatar
m0_50812349 已提交
341
		}
342 343
	} else if strings.Contains(fileSlice[1], "web") {
		if strings.Contains(fileSlice[n-1], "js") {
S
songzhibin97 已提交
344 345
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
				global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
346
		} else if strings.Contains(fileSlice[n-2], "form") {
S
songzhibin97 已提交
347
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
S
songzhibin97 已提交
348
				global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WForm, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), strings.TrimSuffix(base, filepath.Ext(base))+"Form.vue")
349
		} else if strings.Contains(fileSlice[n-2], "table") {
S
songzhibin97 已提交
350
			data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
S
songzhibin97 已提交
351
				global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
m0_50812349's avatar
m0_50812349 已提交
352 353 354
		}
	}
}
355 356 357 358 359 360

//@author: [piexlmax](https://github.com/piexlmax)
//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: CreateApi
//@description: 自动创建api数据,
//@param: a *model.AutoCodeStruct
何秀钢 已提交
361
//@return: err error
362

363
func (autoCodeService *AutoCodeService) AutoCreateApi(a *system.AutoCodeStruct) (ids []uint, err error) {
S
songzhibin97 已提交
364
	apiList := []system.SysApi{
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
		{
			Path:        "/" + a.Abbreviation + "/" + "create" + a.StructName,
			Description: "新增" + a.Description,
			ApiGroup:    a.Abbreviation,
			Method:      "POST",
		},
		{
			Path:        "/" + a.Abbreviation + "/" + "delete" + a.StructName,
			Description: "删除" + a.Description,
			ApiGroup:    a.Abbreviation,
			Method:      "DELETE",
		},
		{
			Path:        "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
			Description: "批量删除" + a.Description,
			ApiGroup:    a.Abbreviation,
			Method:      "DELETE",
		},
		{
			Path:        "/" + a.Abbreviation + "/" + "update" + a.StructName,
			Description: "更新" + a.Description,
			ApiGroup:    a.Abbreviation,
			Method:      "PUT",
		},
		{
			Path:        "/" + a.Abbreviation + "/" + "find" + a.StructName,
			Description: "根据ID获取" + a.Description,
			ApiGroup:    a.Abbreviation,
			Method:      "GET",
		},
		{
			Path:        "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
			Description: "获取" + a.Description + "列表",
			ApiGroup:    a.Abbreviation,
			Method:      "GET",
		},
	}
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		for _, v := range apiList {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
404
			var api system.SysApi
405
			if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) {
S
songzhibin97 已提交
406
				if err = tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
407
					return err
S
songzhibin97 已提交
408 409
				} else {
					ids = append(ids, v.ID)
410
				}
411 412 413 414
			}
		}
		return nil
	})
S
songzhibin97 已提交
415
	return ids, err
416
}
417

418
func (autoCodeService *AutoCodeService) getNeedList(autoCode *system.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
S
songzhibin97 已提交
419 420 421 422 423
	// 去除所有空格
	utils.TrimSpace(autoCode)
	for _, field := range autoCode.Fields {
		utils.TrimSpace(field)
	}
424
	// 获取 basePath 文件夹下所有tpl文件
425
	tplFileList, err := autoCodeService.GetAllTplFile(basePath, nil)
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
	if err != nil {
		return nil, nil, nil, err
	}
	dataList = make([]tplData, 0, len(tplFileList))
	fileList = make([]string, 0, len(tplFileList))
	needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
	// 根据文件路径生成 tplData 结构体,待填充数据
	for _, value := range tplFileList {
		dataList = append(dataList, tplData{locationPath: value})
	}
	// 生成 *Template, 填充 template 字段
	for index, value := range dataList {
		dataList[index].template, err = template.ParseFiles(value.locationPath)
		if err != nil {
			return nil, nil, nil, err
		}
	}
	// 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
	// resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
	// resource/template/readme.txt.tpl -> autoCode/readme.txt
	for index, value := range dataList {
		trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
		if trimBase == "readme.txt.tpl" {
			dataList[index].autoCodePath = autoPath + "readme.txt"
			continue
		}

		if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
			origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
			firstDot := strings.Index(origFileName, ".")
			if firstDot != -1 {
457
				var fileName string
S
songzhibin97 已提交
458 459 460 461
				if origFileName[firstDot:] != ".go" {
					fileName = autoCode.PackageName + origFileName[firstDot:]
				} else {
					fileName = autoCode.HumpPackageName + origFileName[firstDot:]
462 463
				}

464
				dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
465
					origFileName[:firstDot], fileName)
466 467 468 469 470 471 472 473 474 475 476 477
			}
		}

		if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
			needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
		}
	}
	for _, value := range dataList {
		fileList = append(fileList, value.autoCodePath)
	}
	return dataList, fileList, needMkdir, err
}
S
songzhibin97 已提交
478 479 480 481 482 483 484 485 486 487 488 489

// injectionCode 封装代码注入
func injectionCode(structName string, bf *strings.Builder) error {
	for _, meta := range injectionPaths {
		code := fmt.Sprintf(meta.structNameF, structName)
		if err := utils.AutoInjectionCode(meta.path, meta.funcName, code); err != nil {
			return err
		}
		bf.WriteString(fmt.Sprintf("%s@%s@%s;", meta.path, meta.funcName, code))
	}
	return nil
}