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.

492 lines
15 KiB

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