You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

474 lines
16 KiB

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