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.

498 lines
16 KiB

4 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. for _, value := range dataList { // 移动文件
  179. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  180. return err
  181. }
  182. }
  183. err = injectionCode(autoCode.StructName, &injectionCodeMeta)
  184. if err != nil {
  185. return
  186. }
  187. // 保存生成信息
  188. for _, data := range dataList {
  189. if len(data.autoMoveFilePath) != 0 {
  190. bf.WriteString(data.autoMoveFilePath)
  191. bf.WriteString(";")
  192. }
  193. }
  194. if global.GVA_CONFIG.AutoCode.TransferRestart {
  195. go func() {
  196. _ = utils.Reload()
  197. }()
  198. }
  199. } else { // 打包
  200. if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  201. return err
  202. }
  203. }
  204. if autoCode.AutoMoveFile || autoCode.AutoCreateApiToSql {
  205. if autoCode.TableName != "" {
  206. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  207. string(meta),
  208. autoCode.StructName,
  209. autoCode.Description,
  210. bf.String(),
  211. injectionCodeMeta.String(),
  212. autoCode.TableName,
  213. idBf.String(),
  214. )
  215. } else {
  216. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  217. string(meta),
  218. autoCode.StructName,
  219. autoCode.Description,
  220. bf.String(),
  221. injectionCodeMeta.String(),
  222. autoCode.StructName,
  223. idBf.String(),
  224. )
  225. }
  226. }
  227. if err != nil {
  228. return err
  229. }
  230. if autoCode.AutoMoveFile {
  231. return system.AutoMoveErr
  232. }
  233. return nil
  234. }
  235. //@author: [piexlmax](https://github.com/piexlmax)
  236. //@function: GetAllTplFile
  237. //@description: 获取 pathName 文件夹下所有 tpl 文件
  238. //@param: pathName string, fileList []string
  239. //@return: []string, error
  240. func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  241. files, err := ioutil.ReadDir(pathName)
  242. for _, fi := range files {
  243. if fi.IsDir() {
  244. fileList, err = autoCodeService.GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  245. if err != nil {
  246. return nil, err
  247. }
  248. } else {
  249. if strings.HasSuffix(fi.Name(), ".tpl") {
  250. fileList = append(fileList, pathName+"/"+fi.Name())
  251. }
  252. }
  253. }
  254. return fileList, err
  255. }
  256. //@author: [piexlmax](https://github.com/piexlmax)
  257. //@function: GetTables
  258. //@description: 获取数据库的所有表名
  259. //@param: dbName string
  260. //@return: err error, TableNames []request.TableReq
  261. func (autoCodeService *AutoCodeService) GetTables(dbName string) (err error, TableNames []request.TableReq) {
  262. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  263. return err, TableNames
  264. }
  265. //@author: [piexlmax](https://github.com/piexlmax)
  266. //@function: GetDB
  267. //@description: 获取数据库的所有数据库名
  268. //@return: err error, DBNames []request.DBReq
  269. func (autoCodeService *AutoCodeService) GetDB() (err error, DBNames []request.DBReq) {
  270. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  271. return err, DBNames
  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) GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  279. 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
  280. return err, Columns
  281. }
  282. func (autoCodeService *AutoCodeService) DropTable(tableName string) error {
  283. return global.GVA_DB.Exec("DROP TABLE " + tableName).Error
  284. }
  285. //@author: [SliverHorn](https://github.com/SliverHorn)
  286. //@author: [songzhibin97](https://github.com/songzhibin97)
  287. //@function: addAutoMoveFile
  288. //@description: 生成对应的迁移文件路径
  289. //@param: *tplData
  290. //@return: null
  291. func (autoCodeService *AutoCodeService) addAutoMoveFile(data *tplData) {
  292. base := filepath.Base(data.autoCodePath)
  293. fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
  294. n := len(fileSlice)
  295. if n <= 2 {
  296. return
  297. }
  298. if strings.Contains(fileSlice[1], "server") {
  299. if strings.Contains(fileSlice[n-2], "router") {
  300. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
  301. global.GVA_CONFIG.AutoCode.SRouter, base)
  302. } else if strings.Contains(fileSlice[n-2], "api") {
  303. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  304. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
  305. } else if strings.Contains(fileSlice[n-2], "service") {
  306. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  307. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
  308. } else if strings.Contains(fileSlice[n-2], "model") {
  309. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  310. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
  311. } else if strings.Contains(fileSlice[n-2], "request") {
  312. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  313. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
  314. }
  315. } else if strings.Contains(fileSlice[1], "web") {
  316. if strings.Contains(fileSlice[n-1], "js") {
  317. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  318. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
  319. } else if strings.Contains(fileSlice[n-2], "form") {
  320. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  321. 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")
  322. } else if strings.Contains(fileSlice[n-2], "table") {
  323. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  324. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  325. }
  326. }
  327. }
  328. //@author: [piexlmax](https://github.com/piexlmax)
  329. //@author: [SliverHorn](https://github.com/SliverHorn)
  330. //@function: CreateApi
  331. //@description: 自动创建api数据,
  332. //@param: a *model.AutoCodeStruct
  333. //@return: err error
  334. func (autoCodeService *AutoCodeService) AutoCreateApi(a *system.AutoCodeStruct) (ids []uint, err error) {
  335. var apiList = []system.SysApi{
  336. {
  337. Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
  338. Description: "新增" + a.Description,
  339. ApiGroup: a.Abbreviation,
  340. Method: "POST",
  341. },
  342. {
  343. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
  344. Description: "删除" + a.Description,
  345. ApiGroup: a.Abbreviation,
  346. Method: "DELETE",
  347. },
  348. {
  349. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
  350. Description: "批量删除" + a.Description,
  351. ApiGroup: a.Abbreviation,
  352. Method: "DELETE",
  353. },
  354. {
  355. Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
  356. Description: "更新" + a.Description,
  357. ApiGroup: a.Abbreviation,
  358. Method: "PUT",
  359. },
  360. {
  361. Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
  362. Description: "根据ID获取" + a.Description,
  363. ApiGroup: a.Abbreviation,
  364. Method: "GET",
  365. },
  366. {
  367. Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
  368. Description: "获取" + a.Description + "列表",
  369. ApiGroup: a.Abbreviation,
  370. Method: "GET",
  371. },
  372. }
  373. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  374. for _, v := range apiList {
  375. var api system.SysApi
  376. if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) {
  377. if err = tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
  378. return err
  379. } else {
  380. ids = append(ids, v.ID)
  381. }
  382. }
  383. }
  384. return nil
  385. })
  386. return ids, err
  387. }
  388. func (autoCodeService *AutoCodeService) getNeedList(autoCode *system.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
  389. // 去除所有空格
  390. utils.TrimSpace(autoCode)
  391. for _, field := range autoCode.Fields {
  392. utils.TrimSpace(field)
  393. }
  394. // 获取 basePath 文件夹下所有tpl文件
  395. tplFileList, err := autoCodeService.GetAllTplFile(basePath, nil)
  396. if err != nil {
  397. return nil, nil, nil, err
  398. }
  399. dataList = make([]tplData, 0, len(tplFileList))
  400. fileList = make([]string, 0, len(tplFileList))
  401. needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  402. // 根据文件路径生成 tplData 结构体,待填充数据
  403. for _, value := range tplFileList {
  404. dataList = append(dataList, tplData{locationPath: value})
  405. }
  406. // 生成 *Template, 填充 template 字段
  407. for index, value := range dataList {
  408. dataList[index].template, err = template.ParseFiles(value.locationPath)
  409. if err != nil {
  410. return nil, nil, nil, err
  411. }
  412. }
  413. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  414. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  415. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  416. for index, value := range dataList {
  417. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  418. if trimBase == "readme.txt.tpl" {
  419. dataList[index].autoCodePath = autoPath + "readme.txt"
  420. continue
  421. }
  422. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  423. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  424. firstDot := strings.Index(origFileName, ".")
  425. if firstDot != -1 {
  426. var fileName string
  427. if origFileName[firstDot:] != ".go" {
  428. fileName = autoCode.PackageName + origFileName[firstDot:]
  429. } else {
  430. fileName = autoCode.HumpPackageName + origFileName[firstDot:]
  431. }
  432. dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
  433. origFileName[:firstDot], fileName)
  434. }
  435. }
  436. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
  437. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  438. }
  439. }
  440. for _, value := range dataList {
  441. fileList = append(fileList, value.autoCodePath)
  442. }
  443. return dataList, fileList, needMkdir, err
  444. }
  445. // injectionCode 封装代码注入
  446. func injectionCode(structName string, bf *strings.Builder) error {
  447. for _, meta := range injectionPaths {
  448. code := fmt.Sprintf(meta.structNameF, structName)
  449. if err := utils.AutoInjectionCode(meta.path, meta.funcName, code); err != nil {
  450. return err
  451. }
  452. bf.WriteString(fmt.Sprintf("%s@%s@%s;", meta.path, meta.funcName, code))
  453. }
  454. return nil
  455. }