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.

375 lines
12 KiB

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