sys_auto_code.go 8.3 KB
Newer Older
1 2 3
package service

import (
m0_50812349's avatar
m0_50812349 已提交
4
	"errors"
m0_50812349's avatar
m0_50812349 已提交
5
	"fmt"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
6
	"gin-vue-admin/global"
7
	"gin-vue-admin/model"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
8
	"gin-vue-admin/model/request"
9
	"gin-vue-admin/utils"
10
	"io/ioutil"
11
	"os"
m0_50812349's avatar
m0_50812349 已提交
12
	"path/filepath"
13
	"strings"
14
	"text/template"
15 16
)

17
type tplData struct {
m0_50812349's avatar
m0_50812349 已提交
18 19 20 21
	template         *template.Template
	locationPath     string
	autoCodePath     string
	autoMoveFilePath string
22 23
}

24 25
// @title    CreateTemp
// @description   函数的详细描述
26 27
// @auth                     (2020/04/05  20:22)
// @param     autoCode        model.AutoCodeStruct
28
// @return    err             error
Mr.奇淼('s avatar
Mr.奇淼( 已提交
29

30
func CreateTemp(autoCode model.AutoCodeStruct) (err error) {
31 32 33
	basePath := "resource/template"
	// 获取 basePath 文件夹下所有tpl文件
	tplFileList, err := GetAllTplFile(basePath, nil)
34 35 36
	if err != nil {
		return err
	}
37 38 39 40 41 42
	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})
43
	}
44 45 46
	// 生成 *Template, 填充 template 字段
	for index, value := range dataList {
		dataList[index].template, err = template.ParseFiles(value.locationPath)
47 48 49
		if err != nil {
			return err
		}
50 51 52
	}

	// 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
53
	// resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
54 55 56 57 58 59 60
	// resource/template/readme.txt.tpl -> autoCode/readme.txt
	autoPath := "autoCode/"
	for index, value := range dataList {
		trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
		if trimBase == "readme.txt.tpl" {
			dataList[index].autoCodePath = autoPath + "readme.txt"
			continue
61
		}
62 63 64 65 66 67 68 69

		if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
			origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
			firstDot := strings.Index(origFileName, ".")
			if firstDot != -1 {
				dataList[index].autoCodePath = autoPath + trimBase[:lastSeparator] + "/" + autoCode.PackageName + "/" +
					origFileName[:firstDot] + "/" + autoCode.PackageName + origFileName[firstDot:]
			}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
70
		}
71 72 73

		if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, "/"); lastSeparator != -1 {
			needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
74
		}
75 76 77 78 79 80 81 82 83 84 85
	}

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

	// 生成文件
	for _, value := range dataList {
		fileList = append(fileList, value.autoCodePath)
		f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
86 87 88
		if err != nil {
			return err
		}
89
		if err = value.template.Execute(f, autoCode); err != nil {
90 91
			return err
		}
92
		_ = f.Close()
93
	}
94

m0_50812349's avatar
m0_50812349 已提交
95
	defer func() { // 移除中间文件
V
v_zhibsong 已提交
96 97 98 99
		if err := os.RemoveAll(autoPath); err != nil {
			return
		}
	}()
m0_50812349's avatar
m0_50812349 已提交
100 101 102 103 104
	if autoCode.AutoMoveFile { // 判断是否需要自动转移
		for index, _ := range dataList {
			addAutoMoveFile(&dataList[index])
		}
		for _, value := range dataList { // 移动文件
m0_50812349's avatar
m0_50812349 已提交
105
			if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
m0_50812349's avatar
m0_50812349 已提交
106
				fmt.Println(err)
V
v_zhibsong 已提交
107 108 109
				return err
			}
		}
m0_50812349's avatar
m0_50812349 已提交
110
		return errors.New("创建代码成功并移动文件成功")
m0_50812349's avatar
m0_50812349 已提交
111
	} else { // 打包
V
v_zhibsong 已提交
112 113 114
		if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
			return err
		}
115 116 117
	}
	return nil
}
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

// GetAllTplFile 用来获取 pathName 文件夹下所有 tpl 文件
func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
	files, err := ioutil.ReadDir(pathName)
	for _, fi := range files {
		if fi.IsDir() {
			fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
			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.奇淼( 已提交
136 137

func GetTables(dbName string) (err error, TableNames []request.TableReq) {
138
	err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
Mr.奇淼('s avatar
Mr.奇淼( 已提交
139 140 141 142 143 144 145 146
	return err, TableNames
}

func GetDB() (err error, DBNames []request.DBReq) {
	err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
	return err, DBNames
}

147
func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
148
	err = global.GVA_DB.Raw("SELECT COLUMN_NAME column_name,DATA_TYPE data_type,CASE DATA_TYPE WHEN 'longtext' THEN c.CHARACTER_MAXIMUM_LENGTH WHEN 'varchar' THEN c.CHARACTER_MAXIMUM_LENGTH WHEN 'double' THEN CONCAT_WS( ',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE ) WHEN 'decimal' THEN CONCAT_WS( ',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE ) WHEN 'int' THEN c.NUMERIC_PRECISION WHEN 'bigint' THEN c.NUMERIC_PRECISION ELSE '' END AS data_type_long,COLUMN_COMMENT column_comment FROM INFORMATION_SCHEMA.COLUMNS c WHERE table_name = ? AND table_schema = ?", tableName, dbName).Scan(&Columns).Error
149
	return err, Columns
Mr.奇淼('s avatar
Mr.奇淼( 已提交
150
}
m0_50812349's avatar
m0_50812349 已提交
151

S
songzhibin97 已提交
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
//func addAutoMoveFile(data *tplData) {
//	if strings.Contains(data.autoCodePath, "server") {
//		if strings.Contains(data.autoCodePath, "router") {
//			apiList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join(apiList[len(apiList)-2], apiList[len(apiList)-1])
//		} else if strings.Contains(data.autoCodePath, "api") {
//			apiList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join(apiList[len(apiList)-2], "v1", apiList[len(apiList)-1])
//		} else if strings.Contains(data.autoCodePath, "service") {
//			serviceList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join(serviceList[len(serviceList)-2], serviceList[len(serviceList)-1])
//		} else if strings.Contains(data.autoCodePath, "model") {
//			modelList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join(modelList[len(modelList)-2], modelList[len(modelList)-1])
//		} else if strings.Contains(data.autoCodePath, "request") {
//			requestList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join("model", requestList[len(requestList)-2], requestList[len(requestList)-1])
//		}
//	} else if strings.Contains(data.autoCodePath, "web") {
//		if strings.Contains(data.autoCodePath, "js") {
//			jsList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join("../", "web", "src", jsList[len(jsList)-2], jsList[len(jsList)-1])
//		} else if strings.Contains(data.autoCodePath, "form") {
//			formList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", formList[len(formList)-3], strings.Split(formList[len(formList)-1], ".")[0]+"From.vue")
//		} else if strings.Contains(data.autoCodePath, "table") {
//			vueList := strings.Split(data.autoCodePath, "/")
//			data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", vueList[len(vueList)-3], vueList[len(vueList)-1])
//		}
//	}
//}

m0_50812349's avatar
m0_50812349 已提交
184
func addAutoMoveFile(data *tplData) {
S
change2  
songzhibin97 已提交
185
	dir := filepath.Base(filepath.Dir(data.autoCodePath))
S
songzhibin97 已提交
186
	base := filepath.Base(data.autoCodePath)
m0_50812349's avatar
m0_50812349 已提交
187 188
	if strings.Contains(data.autoCodePath, "server") {
		if strings.Contains(data.autoCodePath, "router") {
S
songzhibin97 已提交
189
			data.autoMoveFilePath = filepath.Join(dir, base)
m0_50812349's avatar
m0_50812349 已提交
190
		} else if strings.Contains(data.autoCodePath, "api") {
S
songzhibin97 已提交
191
			data.autoMoveFilePath = filepath.Join(dir, "v1", base)
m0_50812349's avatar
m0_50812349 已提交
192
		} else if strings.Contains(data.autoCodePath, "service") {
S
songzhibin97 已提交
193
			data.autoMoveFilePath = filepath.Join(dir, base)
m0_50812349's avatar
m0_50812349 已提交
194
		} else if strings.Contains(data.autoCodePath, "model") {
S
songzhibin97 已提交
195
			data.autoMoveFilePath = filepath.Join(dir, base)
m0_50812349's avatar
m0_50812349 已提交
196
		} else if strings.Contains(data.autoCodePath, "request") {
S
songzhibin97 已提交
197
			data.autoMoveFilePath = filepath.Join("model", dir, base)
m0_50812349's avatar
m0_50812349 已提交
198 199 200
		}
	} else if strings.Contains(data.autoCodePath, "web") {
		if strings.Contains(data.autoCodePath, "js") {
S
songzhibin97 已提交
201
			data.autoMoveFilePath = filepath.Join("../", "web", "src", dir, base)
m0_50812349's avatar
m0_50812349 已提交
202
		} else if strings.Contains(data.autoCodePath, "form") {
S
re  
songzhibin97 已提交
203
			data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), strings.TrimSuffix(base, filepath.Ext(base))+"From.vue")
m0_50812349's avatar
m0_50812349 已提交
204
		} else if strings.Contains(data.autoCodePath, "table") {
S
re  
songzhibin97 已提交
205
			data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
m0_50812349's avatar
m0_50812349 已提交
206 207 208
		}
	}
}