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.

271 lines
9.1 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "gin-vue-admin/model"
  7. "gin-vue-admin/model/request"
  8. "gin-vue-admin/utils"
  9. "gorm.io/gorm"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "text/template"
  15. )
  16. type tplData struct {
  17. template *template.Template
  18. locationPath string
  19. autoCodePath string
  20. autoMoveFilePath string
  21. }
  22. //@author: [piexlmax](https://github.com/piexlmax)
  23. //@function: CreateTemp
  24. //@description: 创建代码
  25. //@param: model.AutoCodeStruct
  26. //@return: error
  27. func CreateTemp(autoCode model.AutoCodeStruct) (err error) {
  28. basePath := "resource/template"
  29. // 获取 basePath 文件夹下所有tpl文件
  30. tplFileList, err := GetAllTplFile(basePath, nil)
  31. if err != nil {
  32. return err
  33. }
  34. dataList := make([]tplData, 0, len(tplFileList))
  35. fileList := make([]string, 0, len(tplFileList))
  36. needMkdir := make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  37. // 根据文件路径生成 tplData 结构体,待填充数据
  38. for _, value := range tplFileList {
  39. dataList = append(dataList, tplData{locationPath: value})
  40. }
  41. // 生成 *Template, 填充 template 字段
  42. for index, value := range dataList {
  43. dataList[index].template, err = template.ParseFiles(value.locationPath)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  49. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  50. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  51. autoPath := "autoCode/"
  52. for index, value := range dataList {
  53. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  54. if trimBase == "readme.txt.tpl" {
  55. dataList[index].autoCodePath = autoPath + "readme.txt"
  56. continue
  57. }
  58. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  59. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  60. firstDot := strings.Index(origFileName, ".")
  61. if firstDot != -1 {
  62. dataList[index].autoCodePath = autoPath + trimBase[:lastSeparator] + "/" + autoCode.PackageName + "/" +
  63. origFileName[:firstDot] + "/" + autoCode.PackageName + origFileName[firstDot:]
  64. }
  65. }
  66. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, "/"); lastSeparator != -1 {
  67. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  68. }
  69. }
  70. // 写入文件前,先创建文件夹
  71. if err = utils.CreateDir(needMkdir...); err != nil {
  72. return err
  73. }
  74. // 生成文件
  75. for _, value := range dataList {
  76. fileList = append(fileList, value.autoCodePath)
  77. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  78. if err != nil {
  79. return err
  80. }
  81. if err = value.template.Execute(f, autoCode); err != nil {
  82. return err
  83. }
  84. _ = f.Close()
  85. }
  86. defer func() { // 移除中间文件
  87. if err := os.RemoveAll(autoPath); err != nil {
  88. return
  89. }
  90. }()
  91. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  92. for index, _ := range dataList {
  93. addAutoMoveFile(&dataList[index])
  94. }
  95. for _, value := range dataList { // 移动文件
  96. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  97. fmt.Println(err)
  98. return err
  99. }
  100. }
  101. return errors.New("创建代码成功并移动文件成功")
  102. } else { // 打包
  103. if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  104. return err
  105. }
  106. }
  107. return nil
  108. }
  109. //@author: [piexlmax](https://github.com/piexlmax)
  110. //@function: GetAllTplFile
  111. //@description: 获取 pathName 文件夹下所有 tpl 文件
  112. //@param: pathName string, fileList []string
  113. //@return: []string, error
  114. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  115. files, err := ioutil.ReadDir(pathName)
  116. for _, fi := range files {
  117. if fi.IsDir() {
  118. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  119. if err != nil {
  120. return nil, err
  121. }
  122. } else {
  123. if strings.HasSuffix(fi.Name(), ".tpl") {
  124. fileList = append(fileList, pathName+"/"+fi.Name())
  125. }
  126. }
  127. }
  128. return fileList, err
  129. }
  130. //@author: [piexlmax](https://github.com/piexlmax)
  131. //@function: GetTables
  132. //@description: 获取数据库的所有表名
  133. //@param: pathName string
  134. //@param: fileList []string
  135. //@return: []string, error
  136. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  137. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  138. return err, TableNames
  139. }
  140. //@author: [piexlmax](https://github.com/piexlmax)
  141. //@function: GetDB
  142. //@description: 获取数据库的所有数据库名
  143. //@param: pathName string
  144. //@param: fileList []string
  145. //@return: []string, error
  146. func GetDB() (err error, DBNames []request.DBReq) {
  147. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  148. return err, DBNames
  149. }
  150. //@author: [piexlmax](https://github.com/piexlmax)
  151. //@function: GetDB
  152. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  153. //@param: pathName string
  154. //@param: fileList []string
  155. //@return: []string, error
  156. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  157. 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
  158. return err, Columns
  159. }
  160. //@author: [SliverHorn](https://github.com/SliverHorn)
  161. //@author: [songzhibin97](https://github.com/songzhibin97)
  162. //@function: addAutoMoveFile
  163. //@description: 生成对应的迁移文件路径
  164. //@param: *tplData
  165. //@return: null
  166. func addAutoMoveFile(data *tplData) {
  167. dir := filepath.Base(filepath.Dir(data.autoCodePath))
  168. base := filepath.Base(data.autoCodePath)
  169. if strings.Contains(data.autoCodePath, "server") {
  170. if strings.Contains(data.autoCodePath, "router") {
  171. data.autoMoveFilePath = filepath.Join(dir, base)
  172. } else if strings.Contains(data.autoCodePath, "api") {
  173. data.autoMoveFilePath = filepath.Join(dir, "v1", base)
  174. } else if strings.Contains(data.autoCodePath, "service") {
  175. data.autoMoveFilePath = filepath.Join(dir, base)
  176. } else if strings.Contains(data.autoCodePath, "model") {
  177. data.autoMoveFilePath = filepath.Join(dir, base)
  178. } else if strings.Contains(data.autoCodePath, "request") {
  179. data.autoMoveFilePath = filepath.Join("model", dir, base)
  180. }
  181. } else if strings.Contains(data.autoCodePath, "web") {
  182. if strings.Contains(data.autoCodePath, "js") {
  183. data.autoMoveFilePath = filepath.Join("../", "web", "src", dir, base)
  184. } else if strings.Contains(data.autoCodePath, "form") {
  185. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), strings.TrimSuffix(base, filepath.Ext(base))+"From.vue")
  186. } else if strings.Contains(data.autoCodePath, "table") {
  187. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  188. }
  189. }
  190. }
  191. //@author: [piexlmax](https://github.com/piexlmax)
  192. //@author: [SliverHorn](https://github.com/SliverHorn)
  193. //@function: CreateApi
  194. //@description: 自动创建api数据,
  195. //@param: a *model.AutoCodeStruct
  196. //@return: error
  197. func AutoCreateApi(a *model.AutoCodeStruct) (err error) {
  198. var apiList = []model.SysApi{
  199. {
  200. Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
  201. Description: "新增" + a.Description,
  202. ApiGroup: a.Abbreviation,
  203. Method: "POST",
  204. },
  205. {
  206. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
  207. Description: "删除" + a.Description,
  208. ApiGroup: a.Abbreviation,
  209. Method: "DELETE",
  210. },
  211. {
  212. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
  213. Description: "批量删除" + a.Description,
  214. ApiGroup: a.Abbreviation,
  215. Method: "DELETE",
  216. },
  217. {
  218. Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
  219. Description: "更新" + a.Description,
  220. ApiGroup: a.Abbreviation,
  221. Method: "PUT",
  222. },
  223. {
  224. Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
  225. Description: "根据ID获取" + a.Description,
  226. ApiGroup: a.Abbreviation,
  227. Method: "GET",
  228. },
  229. {
  230. Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
  231. Description: "获取" + a.Description + "列表",
  232. ApiGroup: a.Abbreviation,
  233. Method: "GET",
  234. },
  235. }
  236. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  237. for _, v := range apiList {
  238. var api model.SysApi
  239. if err := tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error; err != nil {
  240. return err
  241. }
  242. if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
  243. return err
  244. }
  245. }
  246. return nil
  247. })
  248. return err
  249. }