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.

361 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: 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. return errors.New("创建代码成功并移动文件成功")
  122. } else { // 打包
  123. if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  124. return err
  125. }
  126. }
  127. return nil
  128. }
  129. //@author: [piexlmax](https://github.com/piexlmax)
  130. //@function: GetAllTplFile
  131. //@description: 获取 pathName 文件夹下所有 tpl 文件
  132. //@param: pathName string, fileList []string
  133. //@return: []string, error
  134. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  135. files, err := ioutil.ReadDir(pathName)
  136. for _, fi := range files {
  137. if fi.IsDir() {
  138. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  139. if err != nil {
  140. return nil, err
  141. }
  142. } else {
  143. if strings.HasSuffix(fi.Name(), ".tpl") {
  144. fileList = append(fileList, pathName+"/"+fi.Name())
  145. }
  146. }
  147. }
  148. return fileList, err
  149. }
  150. //@author: [piexlmax](https://github.com/piexlmax)
  151. //@function: GetTables
  152. //@description: 获取数据库的所有表名
  153. //@param: pathName string
  154. //@param: fileList []string
  155. //@return: []string, error
  156. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  157. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  158. return err, TableNames
  159. }
  160. //@author: [piexlmax](https://github.com/piexlmax)
  161. //@function: GetDB
  162. //@description: 获取数据库的所有数据库名
  163. //@param: pathName string
  164. //@param: fileList []string
  165. //@return: []string, error
  166. func GetDB() (err error, DBNames []request.DBReq) {
  167. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  168. return err, DBNames
  169. }
  170. //@author: [piexlmax](https://github.com/piexlmax)
  171. //@function: GetDB
  172. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  173. //@param: pathName string
  174. //@param: fileList []string
  175. //@return: []string, error
  176. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  177. 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
  178. return err, Columns
  179. }
  180. //@author: [SliverHorn](https://github.com/SliverHorn)
  181. //@author: [songzhibin97](https://github.com/songzhibin97)
  182. //@function: addAutoMoveFile
  183. //@description: 生成对应的迁移文件路径
  184. //@param: *tplData
  185. //@return: null
  186. func addAutoMoveFile(data *tplData) {
  187. base := filepath.Base(data.autoCodePath)
  188. fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
  189. n := len(fileSlice)
  190. if n <= 2 {
  191. return
  192. }
  193. if strings.Contains(fileSlice[1], "server") {
  194. if strings.Contains(fileSlice[n-2], "router") {
  195. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
  196. global.GVA_CONFIG.AutoCode.SRouter, base)
  197. } else if strings.Contains(fileSlice[n-2], "api") {
  198. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  199. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
  200. } else if strings.Contains(fileSlice[n-2], "service") {
  201. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  202. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
  203. } else if strings.Contains(fileSlice[n-2], "model") {
  204. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  205. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
  206. } else if strings.Contains(fileSlice[n-2], "request") {
  207. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  208. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
  209. }
  210. } else if strings.Contains(fileSlice[1], "web") {
  211. if strings.Contains(fileSlice[n-1], "js") {
  212. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  213. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
  214. } else if strings.Contains(fileSlice[n-2], "workflowForm") {
  215. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  216. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WFlow, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), strings.TrimSuffix(base, filepath.Ext(base))+"WorkflowForm.vue")
  217. } else if strings.Contains(fileSlice[n-2], "form") {
  218. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  219. 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")
  220. } else if strings.Contains(fileSlice[n-2], "table") {
  221. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  222. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  223. }
  224. }
  225. }
  226. //@author: [piexlmax](https://github.com/piexlmax)
  227. //@author: [SliverHorn](https://github.com/SliverHorn)
  228. //@function: CreateApi
  229. //@description: 自动创建api数据,
  230. //@param: a *model.AutoCodeStruct
  231. //@return: error
  232. func AutoCreateApi(a *model.AutoCodeStruct) (err error) {
  233. var apiList = []model.SysApi{
  234. {
  235. Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
  236. Description: "新增" + a.Description,
  237. ApiGroup: a.Abbreviation,
  238. Method: "POST",
  239. },
  240. {
  241. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
  242. Description: "删除" + a.Description,
  243. ApiGroup: a.Abbreviation,
  244. Method: "DELETE",
  245. },
  246. {
  247. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
  248. Description: "批量删除" + a.Description,
  249. ApiGroup: a.Abbreviation,
  250. Method: "DELETE",
  251. },
  252. {
  253. Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
  254. Description: "更新" + a.Description,
  255. ApiGroup: a.Abbreviation,
  256. Method: "PUT",
  257. },
  258. {
  259. Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
  260. Description: "根据ID获取" + a.Description,
  261. ApiGroup: a.Abbreviation,
  262. Method: "GET",
  263. },
  264. {
  265. Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
  266. Description: "获取" + a.Description + "列表",
  267. ApiGroup: a.Abbreviation,
  268. Method: "GET",
  269. },
  270. }
  271. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  272. for _, v := range apiList {
  273. var api model.SysApi
  274. if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) {
  275. if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
  276. return err
  277. }
  278. }
  279. }
  280. return nil
  281. })
  282. return err
  283. }
  284. func getNeedList(autoCode *model.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
  285. // 获取 basePath 文件夹下所有tpl文件
  286. tplFileList, err := GetAllTplFile(basePath, nil)
  287. if err != nil {
  288. return nil, nil, nil, err
  289. }
  290. dataList = make([]tplData, 0, len(tplFileList))
  291. fileList = make([]string, 0, len(tplFileList))
  292. needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  293. // 根据文件路径生成 tplData 结构体,待填充数据
  294. for _, value := range tplFileList {
  295. dataList = append(dataList, tplData{locationPath: value})
  296. }
  297. // 生成 *Template, 填充 template 字段
  298. for index, value := range dataList {
  299. dataList[index].template, err = template.ParseFiles(value.locationPath)
  300. if err != nil {
  301. return nil, nil, nil, err
  302. }
  303. }
  304. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  305. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  306. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  307. autoPath := "autoCode/"
  308. for index, value := range dataList {
  309. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  310. if trimBase == "readme.txt.tpl" {
  311. dataList[index].autoCodePath = autoPath + "readme.txt"
  312. continue
  313. }
  314. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  315. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  316. firstDot := strings.Index(origFileName, ".")
  317. if firstDot != -1 {
  318. dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
  319. origFileName[:firstDot], autoCode.PackageName+origFileName[firstDot:])
  320. }
  321. }
  322. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
  323. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  324. }
  325. }
  326. for _, value := range dataList {
  327. fileList = append(fileList, value.autoCodePath)
  328. }
  329. return dataList, fileList, needMkdir, err
  330. }