sys_auto_code.go 13 KB

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