sys_auto_code.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. dataList, fileList, needMkdir, err := autoCodeService.getNeedList(&autoCode)
  138. if err != nil {
  139. return err
  140. }
  141. meta, _ := json.Marshal(autoCode)
  142. // 写入文件前,先创建文件夹
  143. if err = utils.CreateDir(needMkdir...); err != nil {
  144. return err
  145. }
  146. // 生成文件
  147. for _, value := range dataList {
  148. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  149. if err != nil {
  150. return err
  151. }
  152. if err = value.template.Execute(f, autoCode); err != nil {
  153. return err
  154. }
  155. _ = f.Close()
  156. }
  157. defer func() { // 移除中间文件
  158. if err := os.RemoveAll(autoPath); err != nil {
  159. return
  160. }
  161. }()
  162. bf := strings.Builder{}
  163. idBf := strings.Builder{}
  164. injectionCodeMeta := strings.Builder{}
  165. for _, id := range ids {
  166. idBf.WriteString(strconv.Itoa(int(id)))
  167. idBf.WriteString(";")
  168. }
  169. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  170. Init()
  171. for index := range dataList {
  172. autoCodeService.addAutoMoveFile(&dataList[index])
  173. }
  174. for _, value := range dataList { // 移动文件
  175. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  176. return err
  177. }
  178. }
  179. err = injectionCode(autoCode.StructName, &injectionCodeMeta)
  180. if err != nil {
  181. return
  182. }
  183. // 保存生成信息
  184. for _, data := range dataList {
  185. if len(data.autoMoveFilePath) != 0 {
  186. bf.WriteString(data.autoMoveFilePath)
  187. bf.WriteString(";")
  188. }
  189. }
  190. if global.GVA_CONFIG.AutoCode.TransferRestart {
  191. go func() {
  192. _ = utils.Reload()
  193. }()
  194. }
  195. } else { // 打包
  196. if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  197. return err
  198. }
  199. }
  200. if autoCode.AutoMoveFile || autoCode.AutoCreateApiToSql {
  201. if autoCode.TableName != "" {
  202. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  203. string(meta),
  204. autoCode.StructName,
  205. autoCode.Description,
  206. bf.String(),
  207. injectionCodeMeta.String(),
  208. autoCode.TableName,
  209. idBf.String(),
  210. )
  211. } else {
  212. err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
  213. string(meta),
  214. autoCode.StructName,
  215. autoCode.Description,
  216. bf.String(),
  217. injectionCodeMeta.String(),
  218. autoCode.StructName,
  219. idBf.String(),
  220. )
  221. }
  222. }
  223. if err != nil {
  224. return err
  225. }
  226. if autoCode.AutoMoveFile {
  227. return system.AutoMoveErr
  228. }
  229. return nil
  230. }
  231. //@author: [piexlmax](https://github.com/piexlmax)
  232. //@function: GetAllTplFile
  233. //@description: 获取 pathName 文件夹下所有 tpl 文件
  234. //@param: pathName string, fileList []string
  235. //@return: []string, error
  236. func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  237. files, err := ioutil.ReadDir(pathName)
  238. for _, fi := range files {
  239. if fi.IsDir() {
  240. fileList, err = autoCodeService.GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  241. if err != nil {
  242. return nil, err
  243. }
  244. } else {
  245. if strings.HasSuffix(fi.Name(), ".tpl") {
  246. fileList = append(fileList, pathName+"/"+fi.Name())
  247. }
  248. }
  249. }
  250. return fileList, err
  251. }
  252. //@author: [piexlmax](https://github.com/piexlmax)
  253. //@function: GetTables
  254. //@description: 获取数据库的所有表名
  255. //@param: dbName string
  256. //@return: err error, TableNames []request.TableReq
  257. func (autoCodeService *AutoCodeService) GetTables(dbName string) (err error, TableNames []request.TableReq) {
  258. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  259. return err, TableNames
  260. }
  261. //@author: [piexlmax](https://github.com/piexlmax)
  262. //@function: GetDB
  263. //@description: 获取数据库的所有数据库名
  264. //@return: err error, DBNames []request.DBReq
  265. func (autoCodeService *AutoCodeService) GetDB() (err error, DBNames []request.DBReq) {
  266. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  267. return err, DBNames
  268. }
  269. //@author: [piexlmax](https://github.com/piexlmax)
  270. //@function: GetDB
  271. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  272. //@param: tableName string, dbName string
  273. //@return: err error, Columns []request.ColumnReq
  274. func (autoCodeService *AutoCodeService) GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  275. 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
  276. return err, Columns
  277. }
  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. var 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. }