sys_auto_code.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "gin-vue-admin/model"
  7. "gin-vue-admin/model/request"
  8. "gin-vue-admin/utils"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "text/template"
  14. "gorm.io/gorm"
  15. )
  16. const (
  17. autoPath = "autoCode/"
  18. basePath = "resource/template"
  19. )
  20. type tplData struct {
  21. template *template.Template
  22. locationPath string
  23. autoCodePath string
  24. autoMoveFilePath string
  25. }
  26. //@author: [songzhibin97](https://github.com/songzhibin97)
  27. //@function: PreviewTemp
  28. //@description: 预览创建代码
  29. //@param: model.AutoCodeStruct
  30. //@return: map[string]string, error
  31. func PreviewTemp(autoCode model.AutoCodeStruct) (map[string]string, error) {
  32. dataList, _, needMkdir, err := getNeedList(&autoCode)
  33. if err != nil {
  34. return nil, err
  35. }
  36. // 写入文件前,先创建文件夹
  37. if err = utils.CreateDir(needMkdir...); err != nil {
  38. return nil, err
  39. }
  40. // 创建map
  41. ret := make(map[string]string)
  42. // 生成map
  43. for _, value := range dataList {
  44. ext := ""
  45. if ext = filepath.Ext(value.autoCodePath); ext == ".txt" {
  46. continue
  47. }
  48. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  49. if err != nil {
  50. return nil, err
  51. }
  52. if err = value.template.Execute(f, autoCode); err != nil {
  53. return nil, err
  54. }
  55. _ = f.Close()
  56. f, err = os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_RDONLY, 0755)
  57. if err != nil {
  58. return nil, err
  59. }
  60. builder := strings.Builder{}
  61. builder.WriteString("```")
  62. if ext != "" && strings.Contains(ext, ".") {
  63. builder.WriteString(strings.Replace(ext, ".", "", -1))
  64. }
  65. builder.WriteString("\n\n")
  66. data, err := ioutil.ReadAll(f)
  67. if err != nil {
  68. return nil, err
  69. }
  70. builder.Write(data)
  71. builder.WriteString("\n\n```")
  72. pathArr := strings.Split(value.autoCodePath, string(os.PathSeparator))
  73. ret[pathArr[1]+"-"+pathArr[3]] = builder.String()
  74. _ = f.Close()
  75. }
  76. defer func() { // 移除中间文件
  77. if err := os.RemoveAll(autoPath); err != nil {
  78. return
  79. }
  80. }()
  81. return ret, nil
  82. }
  83. //@author: [piexlmax](https://github.com/piexlmax)
  84. //@function: CreateTemp
  85. //@description: 创建代码
  86. //@param: model.AutoCodeStruct
  87. //@return: err error
  88. func CreateTemp(autoCode model.AutoCodeStruct) (err error) {
  89. dataList, fileList, needMkdir, err := getNeedList(&autoCode)
  90. if err != nil {
  91. return err
  92. }
  93. // 写入文件前,先创建文件夹
  94. if err = utils.CreateDir(needMkdir...); err != nil {
  95. return err
  96. }
  97. // 生成文件
  98. for _, value := range dataList {
  99. f, err := os.OpenFile(value.autoCodePath, os.O_CREATE|os.O_WRONLY, 0755)
  100. if err != nil {
  101. return err
  102. }
  103. if err = value.template.Execute(f, autoCode); err != nil {
  104. return err
  105. }
  106. _ = f.Close()
  107. }
  108. defer func() { // 移除中间文件
  109. if err := os.RemoveAll(autoPath); err != nil {
  110. return
  111. }
  112. }()
  113. if autoCode.AutoMoveFile { // 判断是否需要自动转移
  114. for index, _ := range dataList {
  115. addAutoMoveFile(&dataList[index])
  116. }
  117. for _, value := range dataList { // 移动文件
  118. if err := utils.FileMove(value.autoCodePath, value.autoMoveFilePath); err != nil {
  119. return err
  120. }
  121. }
  122. initializeGormFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  123. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
  124. initializeRouterFilePath := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  125. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
  126. err = utils.AutoInjectionCode(initializeGormFilePath, "MysqlTables", "model."+autoCode.StructName+"{},")
  127. if err != nil {
  128. return err
  129. }
  130. err = utils.AutoInjectionCode(initializeRouterFilePath, "Routers", "router.Init"+autoCode.StructName+"Router(PrivateGroup)")
  131. if err != nil {
  132. return err
  133. }
  134. injectionCodeMeta := strings.Builder{}
  135. injectionCodeMeta.WriteString(fmt.Sprintf("%s@%s@%s", initializeGormFilePath, "MysqlTables", "model."+autoCode.StructName+"{},"))
  136. injectionCodeMeta.WriteString(";")
  137. injectionCodeMeta.WriteString(fmt.Sprintf("%s@%s@%s", initializeRouterFilePath, "Routers", "router.Init"+autoCode.StructName+"Router(PrivateGroup)"))
  138. // 保存生成信息
  139. bf := strings.Builder{}
  140. for _, data := range dataList {
  141. if len(data.autoMoveFilePath) != 0 {
  142. bf.WriteString(data.autoMoveFilePath)
  143. bf.WriteString(";")
  144. }
  145. }
  146. if autoCode.TableName != "" {
  147. err = CreateAutoCodeHistory(bf.String(),
  148. injectionCodeMeta.String(),
  149. autoCode.TableName,
  150. )
  151. } else {
  152. err = CreateAutoCodeHistory(bf.String(),
  153. injectionCodeMeta.String(),
  154. autoCode.StructName,
  155. )
  156. }
  157. if err != nil {
  158. return err
  159. }
  160. if global.GVA_CONFIG.AutoCode.TransferRestart {
  161. go func() {
  162. _ = utils.Reload()
  163. }()
  164. }
  165. return errors.New("创建代码成功并移动文件成功")
  166. } else { // 打包
  167. if err := utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
  168. return err
  169. }
  170. }
  171. return nil
  172. }
  173. //@author: [piexlmax](https://github.com/piexlmax)
  174. //@function: GetAllTplFile
  175. //@description: 获取 pathName 文件夹下所有 tpl 文件
  176. //@param: pathName string, fileList []string
  177. //@return: []string, error
  178. func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
  179. files, err := ioutil.ReadDir(pathName)
  180. for _, fi := range files {
  181. if fi.IsDir() {
  182. fileList, err = GetAllTplFile(pathName+"/"+fi.Name(), fileList)
  183. if err != nil {
  184. return nil, err
  185. }
  186. } else {
  187. if strings.HasSuffix(fi.Name(), ".tpl") {
  188. fileList = append(fileList, pathName+"/"+fi.Name())
  189. }
  190. }
  191. }
  192. return fileList, err
  193. }
  194. //@author: [piexlmax](https://github.com/piexlmax)
  195. //@function: GetTables
  196. //@description: 获取数据库的所有表名
  197. //@param: dbName string
  198. //@return: err error, TableNames []request.TableReq
  199. func GetTables(dbName string) (err error, TableNames []request.TableReq) {
  200. err = global.GVA_DB.Raw("select table_name as table_name from information_schema.tables where table_schema = ?", dbName).Scan(&TableNames).Error
  201. return err, TableNames
  202. }
  203. //@author: [piexlmax](https://github.com/piexlmax)
  204. //@function: GetDB
  205. //@description: 获取数据库的所有数据库名
  206. //@return: err error, DBNames []request.DBReq
  207. func GetDB() (err error, DBNames []request.DBReq) {
  208. err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
  209. return err, DBNames
  210. }
  211. //@author: [piexlmax](https://github.com/piexlmax)
  212. //@function: GetDB
  213. //@description: 获取指定数据库和指定数据表的所有字段名,类型值等
  214. //@param: tableName string, dbName string
  215. //@return: err error, Columns []request.ColumnReq
  216. func GetColumn(tableName string, dbName string) (err error, Columns []request.ColumnReq) {
  217. 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
  218. return err, Columns
  219. }
  220. func DropTable(tableName string) error {
  221. return global.GVA_DB.Exec("DROP TABLE " + tableName).Error
  222. }
  223. //@author: [SliverHorn](https://github.com/SliverHorn)
  224. //@author: [songzhibin97](https://github.com/songzhibin97)
  225. //@function: addAutoMoveFile
  226. //@description: 生成对应的迁移文件路径
  227. //@param: *tplData
  228. //@return: null
  229. func addAutoMoveFile(data *tplData) {
  230. base := filepath.Base(data.autoCodePath)
  231. fileSlice := strings.Split(data.autoCodePath, string(os.PathSeparator))
  232. n := len(fileSlice)
  233. if n <= 2 {
  234. return
  235. }
  236. if strings.Contains(fileSlice[1], "server") {
  237. if strings.Contains(fileSlice[n-2], "router") {
  238. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server,
  239. global.GVA_CONFIG.AutoCode.SRouter, base)
  240. } else if strings.Contains(fileSlice[n-2], "api") {
  241. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  242. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SApi, base)
  243. } else if strings.Contains(fileSlice[n-2], "service") {
  244. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  245. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SService, base)
  246. } else if strings.Contains(fileSlice[n-2], "model") {
  247. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  248. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SModel, base)
  249. } else if strings.Contains(fileSlice[n-2], "request") {
  250. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  251. global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SRequest, base)
  252. }
  253. } else if strings.Contains(fileSlice[1], "web") {
  254. if strings.Contains(fileSlice[n-1], "js") {
  255. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  256. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WApi, base)
  257. } else if strings.Contains(fileSlice[n-2], "form") {
  258. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  259. 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")
  260. } else if strings.Contains(fileSlice[n-2], "table") {
  261. data.autoMoveFilePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
  262. global.GVA_CONFIG.AutoCode.Web, global.GVA_CONFIG.AutoCode.WTable, filepath.Base(filepath.Dir(filepath.Dir(data.autoCodePath))), base)
  263. }
  264. }
  265. }
  266. //@author: [piexlmax](https://github.com/piexlmax)
  267. //@author: [SliverHorn](https://github.com/SliverHorn)
  268. //@function: CreateApi
  269. //@description: 自动创建api数据,
  270. //@param: a *model.AutoCodeStruct
  271. //@return: err error
  272. func AutoCreateApi(a *model.AutoCodeStruct) (err error) {
  273. var apiList = []model.SysApi{
  274. {
  275. Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
  276. Description: "新增" + a.Description,
  277. ApiGroup: a.Abbreviation,
  278. Method: "POST",
  279. },
  280. {
  281. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
  282. Description: "删除" + a.Description,
  283. ApiGroup: a.Abbreviation,
  284. Method: "DELETE",
  285. },
  286. {
  287. Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
  288. Description: "批量删除" + a.Description,
  289. ApiGroup: a.Abbreviation,
  290. Method: "DELETE",
  291. },
  292. {
  293. Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
  294. Description: "更新" + a.Description,
  295. ApiGroup: a.Abbreviation,
  296. Method: "PUT",
  297. },
  298. {
  299. Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
  300. Description: "根据ID获取" + a.Description,
  301. ApiGroup: a.Abbreviation,
  302. Method: "GET",
  303. },
  304. {
  305. Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
  306. Description: "获取" + a.Description + "列表",
  307. ApiGroup: a.Abbreviation,
  308. Method: "GET",
  309. },
  310. }
  311. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  312. for _, v := range apiList {
  313. var api model.SysApi
  314. if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) {
  315. if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务
  316. return err
  317. }
  318. }
  319. }
  320. return nil
  321. })
  322. return err
  323. }
  324. func getNeedList(autoCode *model.AutoCodeStruct) (dataList []tplData, fileList []string, needMkdir []string, err error) {
  325. // 去除所有空格
  326. utils.TrimSpace(autoCode)
  327. for _, field := range autoCode.Fields {
  328. utils.TrimSpace(field)
  329. }
  330. // 获取 basePath 文件夹下所有tpl文件
  331. tplFileList, err := GetAllTplFile(basePath, nil)
  332. if err != nil {
  333. return nil, nil, nil, err
  334. }
  335. dataList = make([]tplData, 0, len(tplFileList))
  336. fileList = make([]string, 0, len(tplFileList))
  337. needMkdir = make([]string, 0, len(tplFileList)) // 当文件夹下存在多个tpl文件时,改为map更合理
  338. // 根据文件路径生成 tplData 结构体,待填充数据
  339. for _, value := range tplFileList {
  340. dataList = append(dataList, tplData{locationPath: value})
  341. }
  342. // 生成 *Template, 填充 template 字段
  343. for index, value := range dataList {
  344. dataList[index].template, err = template.ParseFiles(value.locationPath)
  345. if err != nil {
  346. return nil, nil, nil, err
  347. }
  348. }
  349. // 生成文件路径,填充 autoCodePath 字段,readme.txt.tpl不符合规则,需要特殊处理
  350. // resource/template/web/api.js.tpl -> autoCode/web/autoCode.PackageName/api/autoCode.PackageName.js
  351. // resource/template/readme.txt.tpl -> autoCode/readme.txt
  352. autoPath := "autoCode/"
  353. for index, value := range dataList {
  354. trimBase := strings.TrimPrefix(value.locationPath, basePath+"/")
  355. if trimBase == "readme.txt.tpl" {
  356. dataList[index].autoCodePath = autoPath + "readme.txt"
  357. continue
  358. }
  359. if lastSeparator := strings.LastIndex(trimBase, "/"); lastSeparator != -1 {
  360. origFileName := strings.TrimSuffix(trimBase[lastSeparator+1:], ".tpl")
  361. firstDot := strings.Index(origFileName, ".")
  362. if firstDot != -1 {
  363. var fileName string
  364. if origFileName[firstDot:] != ".go" {
  365. fileName = autoCode.PackageName + origFileName[firstDot:]
  366. } else {
  367. fileName = autoCode.HumpPackageName + origFileName[firstDot:]
  368. }
  369. dataList[index].autoCodePath = filepath.Join(autoPath, trimBase[:lastSeparator], autoCode.PackageName,
  370. origFileName[:firstDot], fileName)
  371. }
  372. }
  373. if lastSeparator := strings.LastIndex(dataList[index].autoCodePath, string(os.PathSeparator)); lastSeparator != -1 {
  374. needMkdir = append(needMkdir, dataList[index].autoCodePath[:lastSeparator])
  375. }
  376. }
  377. for _, value := range dataList {
  378. fileList = append(fileList, value.autoCodePath)
  379. }
  380. return dataList, fileList, needMkdir, err
  381. }