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.

489 lines
15 KiB

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