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.

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