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.

380 lines
13 KiB

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