sys_auto_code.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. // @title CreateTemp
  22. // @description 函数的详细描述
  23. // @auth (2020/04/05 20:22)
  24. // @param autoCode model.AutoCodeStruct
  25. // @return err 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. // GetAllTplFile 用来获取 pathName 文件夹下所有 tpl 文件
  109. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  110. files, err := ioutil.ReadDir(pathName)
  111. for _, fi := range files {
  112. if fi.IsDir() {
  113. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  114. if err != nil {
  115. return nil, err
  116. }
  117. } else {
  118. if strings.HasSuffix(fi.Name(), ".tpl") {
  119. fileList = append(fileList, pathName+"/"+fi.Name())
  120. }
  121. }
  122. }
  123. return fileList, err
  124. }
  125. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  126. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  127. return err, TableNames
  128. }
  129. func GetDB() (err error, DBNames []request.DBReq) {
  130. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  131. return err, DBNames
  132. }
  133. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  134. 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
  135. return err, Columns
  136. }
  137. //func addAutoMoveFile(data *tplData) {
  138. // if strings.Contains(data.autoCodePath, "server") {
  139. // if strings.Contains(data.autoCodePath, "router") {
  140. // apiList := strings.Split(data.autoCodePath, "/")
  141. // data.autoMoveFilePath = filepath.Join(apiList[len(apiList)-2], apiList[len(apiList)-1])
  142. // } else if strings.Contains(data.autoCodePath, "api") {
  143. // apiList := strings.Split(data.autoCodePath, "/")
  144. // data.autoMoveFilePath = filepath.Join(apiList[len(apiList)-2], "v1", apiList[len(apiList)-1])
  145. // } else if strings.Contains(data.autoCodePath, "service") {
  146. // serviceList := strings.Split(data.autoCodePath, "/")
  147. // data.autoMoveFilePath = filepath.Join(serviceList[len(serviceList)-2], serviceList[len(serviceList)-1])
  148. // } else if strings.Contains(data.autoCodePath, "model") {
  149. // modelList := strings.Split(data.autoCodePath, "/")
  150. // data.autoMoveFilePath = filepath.Join(modelList[len(modelList)-2], modelList[len(modelList)-1])
  151. // } else if strings.Contains(data.autoCodePath, "request") {
  152. // requestList := strings.Split(data.autoCodePath, "/")
  153. // data.autoMoveFilePath = filepath.Join("model", requestList[len(requestList)-2], requestList[len(requestList)-1])
  154. // }
  155. // } else if strings.Contains(data.autoCodePath, "web") {
  156. // if strings.Contains(data.autoCodePath, "js") {
  157. // jsList := strings.Split(data.autoCodePath, "/")
  158. // data.autoMoveFilePath = filepath.Join("../", "web", "src", jsList[len(jsList)-2], jsList[len(jsList)-1])
  159. // } else if strings.Contains(data.autoCodePath, "form") {
  160. // formList := strings.Split(data.autoCodePath, "/")
  161. // data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", formList[len(formList)-3], strings.Split(formList[len(formList)-1], ".")[0]+"From.vue")
  162. // } else if strings.Contains(data.autoCodePath, "table") {
  163. // vueList := strings.Split(data.autoCodePath, "/")
  164. // data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", vueList[len(vueList)-3], vueList[len(vueList)-1])
  165. // }
  166. // }
  167. //}
  168. func addAutoMoveFile(data *tplData) {
  169. dir := filepath.Dir(data.autoCodePath)
  170. base := filepath.Base(data.autoCodePath)
  171. if strings.Contains(data.autoCodePath, "server") {
  172. if strings.Contains(data.autoCodePath, "router") {
  173. data.autoMoveFilePath = filepath.Join(dir, base)
  174. } else if strings.Contains(data.autoCodePath, "api") {
  175. data.autoMoveFilePath = filepath.Join(dir, "v1", base)
  176. } else if strings.Contains(data.autoCodePath, "service") {
  177. data.autoMoveFilePath = filepath.Join(dir, base)
  178. } else if strings.Contains(data.autoCodePath, "model") {
  179. data.autoMoveFilePath = filepath.Join(dir, base)
  180. } else if strings.Contains(data.autoCodePath, "request") {
  181. data.autoMoveFilePath = filepath.Join("model", dir, base)
  182. }
  183. } else if strings.Contains(data.autoCodePath, "web") {
  184. if strings.Contains(data.autoCodePath, "js") {
  185. data.autoMoveFilePath = filepath.Join("../", "web", "src", dir, base)
  186. } else if strings.Contains(data.autoCodePath, "form") {
  187. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Dir(dir), strings.TrimSuffix(base, filepath.Ext(base))+"From.vue")
  188. } else if strings.Contains(data.autoCodePath, "table") {
  189. data.autoMoveFilePath = filepath.Join("../", "web", "src", "view", filepath.Dir(dir), base)
  190. }
  191. }
  192. }