sys_auto_code.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package system
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "gin-vue-admin/global"
  7. "gin-vue-admin/model/system"
  8. "gin-vue-admin/model/system/request"
  9. "gin-vue-admin/utils"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "text/template"
  16. "gorm.io/gorm"
  17. )
  18. const (
  19. autoPath = "autoCode/"
  20. basePath = "resource/template"
  21. )
  22. type tplData struct {
  23. template *template.Template
  24. locationPath string
  25. autoCodePath string
  26. autoMoveFilePath string
  27. }
  28. type AutoCodeService struct {
  29. }
  30. var AutoCodeServiceApp = new(AutoCodeService)
  31. //@author: [songzhibin97](https://github.com/songzhibin97)
  32. //@function: PreviewTemp
  33. //@description: 预览创建代码
  34. //@param: model.AutoCodeStruct
  35. //@return: map[string]string, error
  36. func (autoCodeService *AutoCodeService) PreviewTemp(autoCode system.AutoCodeStruct) (map[string]string, error) {
  37. dataList, _, needMkdir, err := autoCodeService.getNeedList(&autoCode)
  38. if err != nil {
  39. return nil, err
  40. }
  41. // 写入文件前,先创建文件夹
  42. if err = utils.CreateDir(needMkdir...); err != nil {
  43. return nil, err
  44. }
  45. // 创建map
  46. ret := make(map[string]string)
  47. // 生成map
  48. for _, value := range dataList {
  49. ext := ""
  50. if ext = filepath.Ext(value.autoCodePath); ext == ".txt" {
  51. continue
  52. }
  53. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  54. if err != nil {
  55. return nil, err
  56. }
  57. if err = value.template.Execute(f, autoCode); err != nil {
  58. return nil, err
  59. }
  60. _ = f.Close()
  61. f, err = os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_RDONLY, 0755)
  62. if err != nil {
  63. return nil, err
  64. }
  65. builder := strings.Builder{}
  66. builder.WriteString("```")
  67. if ext != "" && strings.Contains(ext, ".") {
  68. builder.WriteString(strings.Replace(ext, ".", "", -1))
  69. }
  70. builder.WriteString("\n\n")
  71. data, err := ioutil.ReadAll(f)
  72. if err != nil {
  73. return nil, err
  74. }
  75. builder.Write(data)
  76. builder.WriteString("\n\n```")
  77. pathArr := strings.Split(value.autoCodePath, string(os.PathSeparator))
  78. ret[pathArr[1]+"-"+pathArr[3]] = builder.String()
  79. _ = f.Close()
  80. }
  81. defer func() { // 移除中间文件
  82. if err := os.RemoveAll(autoPath); err != nil {
  83. return
  84. }
  85. }()
  86. return ret, nil
  87. }
  88. //@author: [piexlmax](https://github.com/piexlmax)
  89. //@function: CreateTemp
  90. //@description: 创建代码
  91. //@param: model.AutoCodeStruct
  92. //@return: err error
  93. func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruct, ids ...uint) (err error) {
  94. dataList, fileList, needMkdir, err := autoCodeService.getNeedList(&autoCode)
  95. if err != nil {
  96. return err
  97. }
  98. meta, _ := json.Marshal(autoCode)
  99. // 写入文件前,先创建文件夹
  100. if err = utils.CreateDir(needMkdir...); err != nil {
  101. return err
  102. }
  103. // 生成文件
  104. for _, value := range dataList {
  105. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  106. if err != nil {
  107. return err
  108. }
  109. if err = value.template.Execute(f, autoCode); err != nil {
  110. return err
  111. }
  112. _ = f.Close()
  113. }
  114. defer func() { // 移除中间文件
  115. if err := os.RemoveAll(autoPath); err != nil {
  116. return
  117. }
  118. }()
  119. bf := strings.Builder{}
  120. idBf := strings.Builder{}
  121. injectionCodeMeta := strings.Builder{}
  122. for _, id := range ids {
  123. idBf.WriteString(strconv.Itoa(int(id)))
  124. idBf.WriteString(";")
  125. }
  126. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  127. for index := range dataList {
  128. autoCodeService.addAutoMoveFile(&dataList[index])
  129. }
  130. for _, value := range dataList { // 移动文件
  131. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  132. return err
  133. }
  134. }
  135. initializeGormFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  136. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
  137. initializeRouterFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  138. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
  139. err = utils.AutoInjectionCode(initializeGormFilePath, "MysqlTables", "model."+autoCode.StructName+"{},")
  140. if err != nil {
  141. return err
  142. }
  143. err = utils.AutoInjectionCode(initializeRouterFilePath, "Routers", "router.Init"+autoCode.StructName+"Router(PrivateGroup)")
  144. if err != nil {
  145. return err
  146. }
  147. injectionCodeMeta.WriteString(fmt.Sprintf("%s@%s@%s", initializeGormFilePath, "MysqlTables", "model."+autoCode.StructName+"{},"))
  148. injectionCodeMeta.WriteString(";")
  149. injectionCodeMeta.WriteString(fmt.Sprintf("%s@%s@%s", initializeRouterFilePath, "Routers", "router.Init"+autoCode.StructName+"Router(PrivateGroup)"))
  150. // 保存生成信息
  151. for _, data := range dataList {
  152. if len(data.autoMoveFilePath) != 0 {
  153. bf.WriteString(data.autoMoveFilePath)
  154. bf.WriteString(";")
  155. }
  156. }
  157. if global.GVA_CONFIG.AutoCode.TransferRestart {
  158. go func() {
  159. _ = utils.Reload()
  160. }()
  161. }
  162. //return errors.New("创建代码成功并移动文件成功")
  163. } else { // 打包
  164. if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  165. return err
  166. }
  167. }
  168. if autoCode.AutoMoveFile || autoCode.AutoCreateApiToSql {
  169. if autoCode.TableName != "" {
  170. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  171. string(meta),
  172. autoCode.StructName,
  173. autoCode.Description,
  174. bf.String(),
  175. injectionCodeMeta.String(),
  176. autoCode.TableName,
  177. idBf.String(),
  178. )
  179. } else {
  180. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  181. string(meta),
  182. autoCode.StructName,
  183. autoCode.Description,
  184. bf.String(),
  185. injectionCodeMeta.String(),
  186. autoCode.StructName,
  187. idBf.String(),
  188. )
  189. }
  190. }
  191. if err != nil {
  192. return err
  193. }
  194. if autoCode.AutoMoveFile {
  195. return errors.New("创建代码成功并移动文件成功")
  196. }
  197. return nil
  198. }
  199. //@author: [piexlmax](https://github.com/piexlmax)
  200. //@function: GetAllTplFile
  201. //@description: 获取 pathName 文件夹下所有 tpl 文件
  202. //@param: pathName string, fileList []string
  203. //@return: []string, error
  204. func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  205. files, err := ioutil.ReadDir(pathName)
  206. for _, fi := range files {
  207. if fi.IsDir() {
  208. fileList, err = autoCodeService.GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  209. if err != nil {
  210. return nil, err
  211. }
  212. } else {
  213. if strings.HasSuffix(fi.Name(), ".tpl") {
  214. fileList = append(fileList, pathName+"/"+fi.Name())
  215. }
  216. }
  217. }
  218. return fileList, err
  219. }
  220. //@author: [piexlmax](https://github.com/piexlmax)
  221. //@function: GetTables
  222. //@description: 获取数据库的所有表名
  223. //@param: dbName string
  224. //@return: err error, TableNames []request.TableReq
  225. func (autoCodeService *AutoCodeService) GetTables(dbName string) (err error, TableNames []request.TableReq) {
  226. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  227. return err, TableNames
  228. }
  229. //@author: [piexlmax](https://github.com/piexlmax)
  230. //@function: GetDB
  231. //@description: 获取数据库的所有数据库名
  232. //@return: err error, DBNames []request.DBReq
  233. func (autoCodeService *AutoCodeService) GetDB() (err error, DBNames []request.DBReq) {
  234. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  235. return err, DBNames
  236. }
  237. //@author: [piexlmax](https://github.com/piexlmax)
  238. //@function: GetDB
  239. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  240. //@param: tableName string, dbName string
  241. //@return: err error, Columns []request.ColumnReq
  242. func (autoCodeService *AutoCodeService) GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  243. 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
  244. return err, Columns
  245. }
  246. func (autoCodeService *AutoCodeService) DropTable(tableName string) error {
  247. return global.GVA_DB.Exec("DROP TABLE " + tableName).Error
  248. }
  249. //@author: [SliverHorn](https://github.com/SliverHorn)
  250. //@author: [songzhibin97](https://github.com/songzhibin97)
  251. //@function: addAutoMoveFile
  252. //@description: 生成对应的迁移文件路径
  253. //@param: *tplData
  254. //@return: null
  255. func (autoCodeService *AutoCodeService) addAutoMoveFile(data *tplData) {
  256. base := filepath.Base(data.autoCodePath)
  257. fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
  258. n := len(fileSlice)
  259. if n <= 2 {
  260. return
  261. }
  262. if strings.Contains(fileSlice[1], "server") {
  263. if strings.Contains(fileSlice[n-2], "router") {
  264. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
  265. global.GVA_CONFIG.AutoCode.SRouter, base)
  266. } else if strings.Contains(fileSlice[n-2], "api") {
  267. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  268. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
  269. } else if strings.Contains(fileSlice[n-2], "service") {
  270. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  271. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
  272. } else if strings.Contains(fileSlice[n-2], "model") {
  273. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  274. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
  275. } else if strings.Contains(fileSlice[n-2], "request") {
  276. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  277. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
  278. }
  279. } else if strings.Contains(fileSlice[1], "web") {
  280. if strings.Contains(fileSlice[n-1], "js") {
  281. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  282. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
  283. } else if strings.Contains(fileSlice[n-2], "form") {
  284. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  285. 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")
  286. } else if strings.Contains(fileSlice[n-2], "table") {
  287. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  288. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, 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: err error
  298. func (autoCodeService *AutoCodeService) AutoCreateApi(a *system.AutoCodeStruct) (ids []uint, err error) {
  299. var apiList = []system.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 system.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. } else {
  344. ids = append(ids, v.ID)
  345. }
  346. }
  347. }
  348. return nil
  349. })
  350. return ids, err
  351. }
  352. func (autoCodeService *AutoCodeService) getNeedList(autoCode *system.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
  353. // 去除所有空格
  354. utils.TrimSpace(autoCode)
  355. for _, field := range autoCode.Fields {
  356. utils.TrimSpace(field)
  357. }
  358. // 获取 basePath 文件夹下所有tpl文件
  359. tplFileList, err := autoCodeService.GetAllTplFile(basePath, nil)
  360. if err != nil {
  361. return nil, nil, nil, err
  362. }
  363. dataList = make([]tplData, 0, len(tplFileList))
  364. fileList = make([]string, 0, len(tplFileList))
  365. needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  366. // 根据文件路径生成 tplData 结构体,待填充数据
  367. for _, value := range tplFileList {
  368. dataList = append(dataList, tplData{locationPath: value})
  369. }
  370. // 生成 *Template, 填充 template 字段
  371. for index, value := range dataList {
  372. dataList[index].template, err = template.ParseFiles(value.locationPath)
  373. if err != nil {
  374. return nil, nil, nil, err
  375. }
  376. }
  377. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  378. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  379. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  380. autoPath := "autoCode/"
  381. for index, value := range dataList {
  382. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  383. if trimBase == "readme.txt.tpl" {
  384. dataList[index].autoCodePath = autoPath + "readme.txt"
  385. continue
  386. }
  387. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  388. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  389. firstDot := strings.Index(origFileName, ".")
  390. if firstDot != -1 {
  391. var fileName string
  392. if origFileName[firstDot:] != ".go" {
  393. fileName = autoCode.PackageName + origFileName[firstDot:]
  394. } else {
  395. fileName = autoCode.HumpPackageName + origFileName[firstDot:]
  396. }
  397. dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
  398. origFileName[:firstDot], fileName)
  399. }
  400. }
  401. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
  402. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  403. }
  404. }
  405. for _, value := range dataList {
  406. fileList = append(fileList, value.autoCodePath)
  407. }
  408. return dataList, fileList, needMkdir, err
  409. }