sys_auto_code.go 14 KB

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