sys_auto_code.go 11 KB

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