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.

440 lines
14 KiB

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