auto_code_history.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package system
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/flipped-aurora/gin-vue-admin/server/utils/ast"
  7. "github.com/pkg/errors"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/flipped-aurora/gin-vue-admin/server/global"
  14. common "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
  15. model "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  16. request "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
  17. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  18. "go.uber.org/zap"
  19. )
  20. var AutocodeHistory = new(autoCodeHistory)
  21. type autoCodeHistory struct{}
  22. // Create 创建代码生成器历史记录
  23. // Author [SliverHorn](https://github.com/SliverHorn)
  24. // Author [songzhibin97](https://github.com/songzhibin97)
  25. func (s *autoCodeHistory) Create(ctx context.Context, info request.SysAutoHistoryCreate) error {
  26. create := info.Create()
  27. err := global.GVA_DB.WithContext(ctx).Create(&create).Error
  28. if err != nil {
  29. return errors.Wrap(err, "创建失败!")
  30. }
  31. return nil
  32. }
  33. // First 根据id获取代码生成器历史的数据
  34. // Author [SliverHorn](https://github.com/SliverHorn)
  35. // Author [songzhibin97](https://github.com/songzhibin97)
  36. func (s *autoCodeHistory) First(ctx context.Context, info common.GetById) (string, error) {
  37. var meta string
  38. err := global.GVA_DB.WithContext(ctx).Model(model.SysAutoCodeHistory{}).Where("id = ?", info.ID).Pluck("request", &meta).Error
  39. if err != nil {
  40. return "", errors.Wrap(err, "获取失败!")
  41. }
  42. return meta, nil
  43. }
  44. // Repeat 检测重复
  45. // Author [SliverHorn](https://github.com/SliverHorn)
  46. // Author [songzhibin97](https://github.com/songzhibin97)
  47. func (s *autoCodeHistory) Repeat(businessDB, structName, abbreviation, Package string) bool {
  48. var count int64
  49. global.GVA_DB.Model(&model.SysAutoCodeHistory{}).Where("business_db = ? and (struct_name = ? OR abbreviation = ?) and package = ? and flag = ?", businessDB, structName, abbreviation, Package, 0).Count(&count).Debug()
  50. return count > 0
  51. }
  52. // RollBack 回滚
  53. // Author [SliverHorn](https://github.com/SliverHorn)
  54. // Author [songzhibin97](https://github.com/songzhibin97)
  55. func (s *autoCodeHistory) RollBack(ctx context.Context, info request.SysAutoHistoryRollBack) error {
  56. var history model.SysAutoCodeHistory
  57. err := global.GVA_DB.Where("id = ?", info.ID).First(&history).Error
  58. if err != nil {
  59. return err
  60. }
  61. if history.ExportTemplateID != 0 {
  62. err = global.GVA_DB.Delete(&model.SysExportTemplate{}, "id = ?", history.ExportTemplateID).Error
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. if info.DeleteApi {
  68. ids := info.ApiIds(history)
  69. err = ApiServiceApp.DeleteApisByIds(ids)
  70. if err != nil {
  71. global.GVA_LOG.Error("ClearTag DeleteApiByIds:", zap.Error(err))
  72. }
  73. } // 清除API表
  74. if info.DeleteMenu {
  75. err = BaseMenuServiceApp.DeleteBaseMenu(int(history.MenuID))
  76. if err != nil {
  77. return errors.Wrap(err, "删除菜单失败!")
  78. }
  79. } // 清除菜单表
  80. if info.DeleteTable {
  81. err = s.DropTable(history.BusinessDB, history.Table)
  82. if err != nil {
  83. return errors.Wrap(err, "删除表失败!")
  84. }
  85. } // 删除表
  86. templates := make(map[string]string, len(history.Templates))
  87. for key, template := range history.Templates {
  88. {
  89. server := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server)
  90. keys := strings.Split(key, "/")
  91. key = filepath.Join(keys...)
  92. key = strings.TrimPrefix(key, server)
  93. } // key
  94. {
  95. web := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.WebRoot())
  96. server := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server)
  97. slices := strings.Split(template, "/")
  98. template = filepath.Join(slices...)
  99. ext := path.Ext(template)
  100. switch ext {
  101. case ".js", ".vue":
  102. template = filepath.Join(web, template)
  103. case ".go":
  104. template = filepath.Join(server, template)
  105. }
  106. } // value
  107. templates[key] = template
  108. }
  109. history.Templates = templates
  110. for key, value := range history.Injections {
  111. var injection ast.Ast
  112. switch key {
  113. case ast.TypePackageApiEnter, ast.TypePackageRouterEnter, ast.TypePackageServiceEnter:
  114. case ast.TypePackageApiModuleEnter, ast.TypePackageRouterModuleEnter, ast.TypePackageServiceModuleEnter:
  115. var entity ast.PackageModuleEnter
  116. _ = json.Unmarshal([]byte(value), &entity)
  117. injection = &entity
  118. case ast.TypePackageInitializeGorm:
  119. var entity ast.PackageInitializeGorm
  120. _ = json.Unmarshal([]byte(value), &entity)
  121. injection = &entity
  122. case ast.TypePackageInitializeRouter:
  123. var entity ast.PackageInitializeRouter
  124. _ = json.Unmarshal([]byte(value), &entity)
  125. injection = &entity
  126. case ast.TypePluginGen:
  127. var entity ast.PluginGen
  128. _ = json.Unmarshal([]byte(value), &entity)
  129. injection = &entity
  130. case ast.TypePluginApiEnter, ast.TypePluginRouterEnter, ast.TypePluginServiceEnter:
  131. var entity ast.PluginEnter
  132. _ = json.Unmarshal([]byte(value), &entity)
  133. injection = &entity
  134. case ast.TypePluginInitializeGorm:
  135. var entity ast.PluginInitializeGorm
  136. _ = json.Unmarshal([]byte(value), &entity)
  137. injection = &entity
  138. case ast.TypePluginInitializeRouter:
  139. var entity ast.PluginInitializeRouter
  140. _ = json.Unmarshal([]byte(value), &entity)
  141. injection = &entity
  142. }
  143. if injection == nil {
  144. continue
  145. }
  146. file, _ := injection.Parse("", nil)
  147. if file != nil {
  148. _ = injection.Rollback(file)
  149. err = injection.Format("", nil, file)
  150. if err != nil {
  151. return err
  152. }
  153. fmt.Printf("[filepath:%s]回滚注入代码成功!\n", key)
  154. }
  155. } // 清除注入代码
  156. removeBasePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root, "rm_file", strconv.FormatInt(int64(time.Now().Nanosecond()), 10))
  157. for _, value := range history.Templates {
  158. if !filepath.IsAbs(value) {
  159. continue
  160. }
  161. removePath := filepath.Join(removeBasePath, strings.TrimPrefix(value, global.GVA_CONFIG.AutoCode.Root))
  162. err = utils.FileMove(value, removePath)
  163. if err != nil {
  164. return errors.Wrapf(err, "[src:%s][dst:%s]文件移动失败!", value, removePath)
  165. }
  166. } // 移动文件
  167. err = global.GVA_DB.WithContext(ctx).Model(&model.SysAutoCodeHistory{}).Where("id = ?", info.ID).Update("flag", 1).Error
  168. if err != nil {
  169. return errors.Wrap(err, "更新失败!")
  170. }
  171. return nil
  172. }
  173. // Delete 删除历史数据
  174. // Author [SliverHorn](https://github.com/SliverHorn)
  175. // Author [songzhibin97](https://github.com/songzhibin97)
  176. func (s *autoCodeHistory) Delete(ctx context.Context, info common.GetById) error {
  177. err := global.GVA_DB.WithContext(ctx).Where("id = ?", info.Uint()).Delete(&model.SysAutoCodeHistory{}).Error
  178. if err != nil {
  179. return errors.Wrap(err, "删除失败!")
  180. }
  181. return nil
  182. }
  183. // GetList 获取系统历史数据
  184. // Author [SliverHorn](https://github.com/SliverHorn)
  185. // Author [songzhibin97](https://github.com/songzhibin97)
  186. func (s *autoCodeHistory) GetList(ctx context.Context, info common.PageInfo) (list []model.SysAutoCodeHistory, total int64, err error) {
  187. var entities []model.SysAutoCodeHistory
  188. db := global.GVA_DB.WithContext(ctx).Model(&model.SysAutoCodeHistory{})
  189. err = db.Count(&total).Error
  190. if err != nil {
  191. return nil, total, err
  192. }
  193. err = db.Scopes(info.Paginate()).Order("updated_at desc").Find(&entities).Error
  194. return entities, total, err
  195. }
  196. // DropTable 获取指定数据库和指定数据表的所有字段名,类型值等
  197. // @author: [piexlmax](https://github.com/piexlmax)
  198. func (s *autoCodeHistory) DropTable(BusinessDb, tableName string) error {
  199. if BusinessDb != "" {
  200. return global.MustGetGlobalDBByDBName(BusinessDb).Exec("DROP TABLE " + tableName).Error
  201. } else {
  202. return global.GVA_DB.Exec("DROP TABLE " + tableName).Error
  203. }
  204. }