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.

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