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.

209 lines
7.3 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. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "text/template"
  14. )
  15. type tplData struct {
  16. template *template.Template
  17. locationPath string
  18. autoCodePath string
  19. autoMoveFilePath string
  20. }
  21. //@author: [piexlmax](https://github.com/piexlmax)
  22. //@function: CreateTemp
  23. //@description: 创建代码
  24. //@param: model.AutoCodeStruct
  25. //@return: error
  26. func CreateTemp(autoCode model.AutoCodeStruct) (err error) {
  27. basePath := "resource/template"
  28. // 获取 basePath 文件夹下所有tpl文件
  29. tplFileList, err := GetAllTplFile(basePath, nil)
  30. if err != nil {
  31. return err
  32. }
  33. dataList := make([]tplData, 0, len(tplFileList))
  34. fileList := make([]string, 0, len(tplFileList))
  35. needMkdir := make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  36. // 根据文件路径生成 tplData 结构体,待填充数据
  37. for _, value := range tplFileList {
  38. dataList = append(dataList, tplData{locationPath: value})
  39. }
  40. // 生成 *Template, 填充 template 字段
  41. for index, value := range dataList {
  42. dataList[index].template, err = template.ParseFiles(value.locationPath)
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  48. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  49. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  50. autoPath := "autoCode/"
  51. for index, value := range dataList {
  52. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  53. if trimBase == "readme.txt.tpl" {
  54. dataList[index].autoCodePath = autoPath + "readme.txt"
  55. continue
  56. }
  57. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  58. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  59. firstDot := strings.Index(origFileName, ".")
  60. if firstDot != -1 {
  61. dataList[index].autoCodePath = autoPath + trimBase[:lastSeparator] + "/" + autoCode.PackageName + "/" +
  62. origFileName[:firstDot] + "/" + autoCode.PackageName + origFileName[firstDot:]
  63. }
  64. }
  65. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, "/"); lastSeparator != -1 {
  66. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  67. }
  68. }
  69. // 写入文件前,先创建文件夹
  70. if err = utils.CreateDir(needMkdir...); err != nil {
  71. return err
  72. }
  73. // 生成文件
  74. for _, value := range dataList {
  75. fileList = append(fileList, value.autoCodePath)
  76. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  77. if err != nil {
  78. return err
  79. }
  80. if err = value.template.Execute(f, autoCode); err != nil {
  81. return err
  82. }
  83. _ = f.Close()
  84. }
  85. defer func() { // 移除中间文件
  86. if err := os.RemoveAll(autoPath); err != nil {
  87. return
  88. }
  89. }()
  90. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  91. for index, _ := range dataList {
  92. addAutoMoveFile(&dataList[index])
  93. }
  94. for _, value := range dataList { // 移动文件
  95. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  96. fmt.Println(err)
  97. return err
  98. }
  99. }
  100. return errors.New("创建代码成功并移动文件成功")
  101. } else { // 打包
  102. if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  103. return err
  104. }
  105. }
  106. return nil
  107. }
  108. //@author: [piexlmax](https://github.com/piexlmax)
  109. //@function: GetAllTplFile
  110. //@description: 获取 pathName 文件夹下所有 tpl 文件
  111. //@param: pathName string, fileList []string
  112. //@return: []string, error
  113. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  114. files, err := ioutil.ReadDir(pathName)
  115. for _, fi := range files {
  116. if fi.IsDir() {
  117. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  118. if err != nil {
  119. return nil, err
  120. }
  121. } else {
  122. if strings.HasSuffix(fi.Name(), ".tpl") {
  123. fileList = append(fileList, pathName+"/"+fi.Name())
  124. }
  125. }
  126. }
  127. return fileList, err
  128. }
  129. //@author: [piexlmax](https://github.com/piexlmax)
  130. //@function: GetTables
  131. //@description: 获取数据库的所有表名
  132. //@param: pathName string
  133. //@param: fileList []string
  134. //@return: []string, error
  135. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  136. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  137. return err, TableNames
  138. }
  139. //@author: [piexlmax](https://github.com/piexlmax)
  140. //@function: GetDB
  141. //@description: 获取数据库的所有数据库名
  142. //@param: pathName string
  143. //@param: fileList []string
  144. //@return: []string, error
  145. func GetDB() (err error, DBNames []request.DBReq) {
  146. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  147. return err, DBNames
  148. }
  149. //@author: [piexlmax](https://github.com/piexlmax)
  150. //@function: GetDB
  151. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  152. //@param: pathName string
  153. //@param: fileList []string
  154. //@return: []string, error
  155. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  156. 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
  157. return err, Columns
  158. }
  159. //@author: [SliverHorn](https://github.com/SliverHorn)
  160. //@author: [songzhibin97](https://github.com/songzhibin97)
  161. //@function: addAutoMoveFile
  162. //@description: 生成对应的迁移文件路径
  163. //@param: *tplData
  164. //@return: null
  165. func addAutoMoveFile(data *tplData) {
  166. dir := filepath.Base(filepath.Dir(data.autoCodePath))
  167. base := filepath.Base(data.autoCodePath)
  168. if strings.Contains(data.autoCodePath, "server") {
  169. if strings.Contains(data.autoCodePath, "router") {
  170. data.autoMoveFilePath = filepath.Join(dir, base)
  171. } else if strings.Contains(data.autoCodePath, "api") {
  172. data.autoMoveFilePath = filepath.Join(dir, "v1", base)
  173. } else if strings.Contains(data.autoCodePath, "service") {
  174. data.autoMoveFilePath = filepath.Join(dir, base)
  175. } else if strings.Contains(data.autoCodePath, "model") {
  176. data.autoMoveFilePath = filepath.Join(dir, base)
  177. } else if strings.Contains(data.autoCodePath, "request") {
  178. data.autoMoveFilePath = filepath.Join("model", dir, base)
  179. }
  180. } else if strings.Contains(data.autoCodePath, "web") {
  181. if strings.Contains(data.autoCodePath, "js") {
  182. data.autoMoveFilePath = filepath.Join("../", "web", "src", dir, base)
  183. } else if strings.Contains(data.autoCodePath, "form") {
  184. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), strings.TrimSuffix(base, filepath.Ext(base))+"From.vue")
  185. } else if strings.Contains(data.autoCodePath, "table") {
  186. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  187. }
  188. }
  189. }