sys_auto_code.go 14 KB

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