sys_auto_code.go 14 KB

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