You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

376 lines
12 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package service
  2. import (
  3. "errors"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/model"
  6. "gin-vue-admin/model/request"
  7. "gin-vue-admin/utils"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "text/template"
  13. "gorm.io/gorm"
  14. )
  15. const (
  16. autoPath = "autoCode/"
  17. basePath = "resource/template"
  18. )
  19. type tplData struct {
  20. template *template.Template
  21. locationPath string
  22. autoCodePath string
  23. autoMoveFilePath string
  24. }
  25. //@author: [songzhibin97](https://github.com/songzhibin97)
  26. //@function: PreviewTemp
  27. //@description: 预览创建代码
  28. //@param: model.AutoCodeStruct
  29. //@return: map[string]string, error
  30. func PreviewTemp(autoCode model.AutoCodeStruct) (map[string]string, error) {
  31. dataList, _, needMkdir, err := getNeedList(&autoCode)
  32. if err != nil {
  33. return nil, err
  34. }
  35. // 写入文件前,先创建文件夹
  36. if err = utils.CreateDir(needMkdir...); err != nil {
  37. return nil, err
  38. }
  39. // 创建map
  40. ret := make(map[string]string)
  41. // 生成map
  42. for _, value := range dataList {
  43. ext := ""
  44. if ext = filepath.Ext(value.autoCodePath); ext == ".txt" {
  45. continue
  46. }
  47. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if err = value.template.Execute(f, autoCode); err != nil {
  52. return nil, err
  53. }
  54. _ = f.Close()
  55. f, err = os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_RDONLY, 0755)
  56. if err != nil {
  57. return nil, err
  58. }
  59. builder := strings.Builder{}
  60. builder.WriteString("```")
  61. if ext != "" && strings.Contains(ext, ".") {
  62. builder.WriteString(strings.Replace(ext, ".", "", -1))
  63. }
  64. builder.WriteString("\n\n")
  65. data, err := ioutil.ReadAll(f)
  66. if err != nil {
  67. return nil, err
  68. }
  69. builder.Write(data)
  70. builder.WriteString("\n\n```")
  71. pathArr := strings.Split(value.autoCodePath, string(os.PathSeparator))
  72. ret[pathArr[1]+"-"+pathArr[3]] = builder.String()
  73. _ = f.Close()
  74. }
  75. defer func() { // 移除中间文件
  76. if err := os.RemoveAll(autoPath); err != nil {
  77. return
  78. }
  79. }()
  80. return ret, nil
  81. }
  82. //@author: [piexlmax](https://github.com/piexlmax)
  83. //@function: CreateTemp
  84. //@description: 创建代码
  85. //@param: model.AutoCodeStruct
  86. //@return: err error
  87. func CreateTemp(autoCode model.AutoCodeStruct) (err error) {
  88. dataList, fileList, needMkdir, err := getNeedList(&autoCode)
  89. if err != nil {
  90. return err
  91. }
  92. // 写入文件前,先创建文件夹
  93. if err = utils.CreateDir(needMkdir...); err != nil {
  94. return err
  95. }
  96. // 生成文件
  97. for _, value := range dataList {
  98. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  99. if err != nil {
  100. return err
  101. }
  102. if err = value.template.Execute(f, autoCode); err != nil {
  103. return err
  104. }
  105. _ = f.Close()
  106. }
  107. defer func() { // 移除中间文件
  108. if err := os.RemoveAll(autoPath); err != nil {
  109. return
  110. }
  111. }()
  112. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  113. for index, _ := range dataList {
  114. addAutoMoveFile(&dataList[index])
  115. }
  116. for _, value := range dataList { // 移动文件
  117. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  118. return err
  119. }
  120. }
  121. initializeGormFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  122. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
  123. initializeRouterFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  124. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
  125. err = utils.AutoInjectionCode(initializeGormFilePath, "MysqlTables", "model."+autoCode.StructName+"{},")
  126. if err != nil {
  127. return err
  128. }
  129. err = utils.AutoInjectionCode(initializeRouterFilePath, "Routers", "router.Init"+autoCode.StructName+"Router(PrivateGroup)")
  130. if err != nil {
  131. return err
  132. }
  133. if global.GVA_CONFIG.AutoCode.TransferRestart {
  134. go func() {
  135. _ = utils.Reload()
  136. }()
  137. }
  138. return errors.New("创建代码成功并移动文件成功")
  139. } else { // 打包
  140. if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. //@author: [piexlmax](https://github.com/piexlmax)
  147. //@function: GetAllTplFile
  148. //@description: 获取 pathName 文件夹下所有 tpl 文件
  149. //@param: pathName string, fileList []string
  150. //@return: []string, error
  151. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  152. files, err := ioutil.ReadDir(pathName)
  153. for _, fi := range files {
  154. if fi.IsDir() {
  155. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  156. if err != nil {
  157. return nil, err
  158. }
  159. } else {
  160. if strings.HasSuffix(fi.Name(), ".tpl") {
  161. fileList = append(fileList, pathName+"/"+fi.Name())
  162. }
  163. }
  164. }
  165. return fileList, err
  166. }
  167. //@author: [piexlmax](https://github.com/piexlmax)
  168. //@function: GetTables
  169. //@description: 获取数据库的所有表名
  170. //@param: dbName string
  171. //@return: err error, TableNames []request.TableReq
  172. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  173. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  174. return err, TableNames
  175. }
  176. //@author: [piexlmax](https://github.com/piexlmax)
  177. //@function: GetDB
  178. //@description: 获取数据库的所有数据库名
  179. //@return: err error, DBNames []request.DBReq
  180. func GetDB() (err error, DBNames []request.DBReq) {
  181. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  182. return err, DBNames
  183. }
  184. //@author: [piexlmax](https://github.com/piexlmax)
  185. //@function: GetDB
  186. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  187. //@param: tableName string, dbName string
  188. //@return: err error, Columns []request.ColumnReq
  189. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  190. 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
  191. return err, Columns
  192. }
  193. //@author: [SliverHorn](https://github.com/SliverHorn)
  194. //@author: [songzhibin97](https://github.com/songzhibin97)
  195. //@function: addAutoMoveFile
  196. //@description: 生成对应的迁移文件路径
  197. //@param: *tplData
  198. //@return: null
  199. func addAutoMoveFile(data *tplData) {
  200. base := filepath.Base(data.autoCodePath)
  201. fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
  202. n := len(fileSlice)
  203. if n <= 2 {
  204. return
  205. }
  206. if strings.Contains(fileSlice[1], "server") {
  207. if strings.Contains(fileSlice[n-2], "router") {
  208. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
  209. global.GVA_CONFIG.AutoCode.SRouter, base)
  210. } else if strings.Contains(fileSlice[n-2], "api") {
  211. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  212. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
  213. } else if strings.Contains(fileSlice[n-2], "service") {
  214. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  215. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
  216. } else if strings.Contains(fileSlice[n-2], "model") {
  217. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  218. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
  219. } else if strings.Contains(fileSlice[n-2], "request") {
  220. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  221. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
  222. }
  223. } else if strings.Contains(fileSlice[1], "web") {
  224. if strings.Contains(fileSlice[n-1], "js") {
  225. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  226. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
  227. } else if strings.Contains(fileSlice[n-2], "form") {
  228. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  229. 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")
  230. } else if strings.Contains(fileSlice[n-2], "table") {
  231. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  232. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  233. }
  234. }
  235. }
  236. //@author: [piexlmax](https://github.com/piexlmax)
  237. //@author: [SliverHorn](https://github.com/SliverHorn)
  238. //@function: CreateApi
  239. //@description: 自动创建api数据,
  240. //@param: a *model.AutoCodeStruct
  241. //@return: err error
  242. func AutoCreateApi(a *model.AutoCodeStruct) (err error) {
  243. var apiList = []model.SysApi{
  244. {
  245. Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
  246. Description: "新增" + a.Description,
  247. ApiGroup: a.Abbreviation,
  248. Method: "POST",
  249. },
  250. {
  251. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
  252. Description: "删除" + a.Description,
  253. ApiGroup: a.Abbreviation,
  254. Method: "DELETE",
  255. },
  256. {
  257. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
  258. Description: "批量删除" + a.Description,
  259. ApiGroup: a.Abbreviation,
  260. Method: "DELETE",
  261. },
  262. {
  263. Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
  264. Description: "更新" + a.Description,
  265. ApiGroup: a.Abbreviation,
  266. Method: "PUT",
  267. },
  268. {
  269. Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
  270. Description: "根据ID获取" + a.Description,
  271. ApiGroup: a.Abbreviation,
  272. Method: "GET",
  273. },
  274. {
  275. Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
  276. Description: "获取" + a.Description + "列表",
  277. ApiGroup: a.Abbreviation,
  278. Method: "GET",
  279. },
  280. }
  281. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  282. for _, v := range apiList {
  283. var api model.SysApi
  284. if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) {
  285. if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
  286. return err
  287. }
  288. }
  289. }
  290. return nil
  291. })
  292. return err
  293. }
  294. func getNeedList(autoCode *model.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
  295. // 去除所有空格
  296. utils.TrimSpace(autoCode)
  297. for _, field := range autoCode.Fields {
  298. utils.TrimSpace(field)
  299. }
  300. // 获取 basePath 文件夹下所有tpl文件
  301. tplFileList, err := GetAllTplFile(basePath, nil)
  302. if err != nil {
  303. return nil, nil, nil, err
  304. }
  305. dataList = make([]tplData, 0, len(tplFileList))
  306. fileList = make([]string, 0, len(tplFileList))
  307. needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  308. // 根据文件路径生成 tplData 结构体,待填充数据
  309. for _, value := range tplFileList {
  310. dataList = append(dataList, tplData{locationPath: value})
  311. }
  312. // 生成 *Template, 填充 template 字段
  313. for index, value := range dataList {
  314. dataList[index].template, err = template.ParseFiles(value.locationPath)
  315. if err != nil {
  316. return nil, nil, nil, err
  317. }
  318. }
  319. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  320. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  321. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  322. autoPath := "autoCode/"
  323. for index, value := range dataList {
  324. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  325. if trimBase == "readme.txt.tpl" {
  326. dataList[index].autoCodePath = autoPath + "readme.txt"
  327. continue
  328. }
  329. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  330. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  331. firstDot := strings.Index(origFileName, ".")
  332. if firstDot != -1 {
  333. dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
  334. origFileName[:firstDot], autoCode.PackageName+origFileName[firstDot:])
  335. }
  336. }
  337. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
  338. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  339. }
  340. }
  341. for _, value := range dataList {
  342. fileList = append(fileList, value.autoCodePath)
  343. }
  344. return dataList, fileList, needMkdir, err
  345. }