Skip to content

Commit 87b3b5e

Browse files
author
奇淼(piexlmax
authored
重构自动化代码,修复皮肤bug (flipped-aurora#1355)
* 增加读取ast方法和AddImport 方法来增加引用包功能 * 增加在指定方法中添加头部声明global.DB业务库的方法 * 增加了自动添加AutoMigrate方法。 * 将自动化产生自动迁移功能替换为新ast * 增加了自动注册router块的功能 * 废除旧的对router和gorm的处理方法,替换为新的自动化方法 * 修复开发模式下皮肤失效的问题
1 parent 9974d6a commit 87b3b5e

File tree

17 files changed

+637
-229
lines changed

17 files changed

+637
-229
lines changed

server/initialize/gorm.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func Gorm() *gorm.DB {
2121
return GormPgSql()
2222
case "oracle":
2323
return GormOracle()
24-
case "mssql":
24+
case "mssql":
2525
return GormMssql()
2626
default:
2727
return GormMysql()
@@ -30,7 +30,8 @@ func Gorm() *gorm.DB {
3030

3131
// RegisterTables 注册数据库表专用
3232
// Author SliverHorn
33-
func RegisterTables(db *gorm.DB) {
33+
func RegisterTables() {
34+
db := global.GVA_DB
3435
err := db.AutoMigrate(
3536
// 系统模块表
3637
system.SysApi{},
@@ -47,16 +48,10 @@ func RegisterTables(db *gorm.DB) {
4748
system.SysAuthorityBtn{},
4849
system.SysAutoCode{},
4950

50-
// 示例模块表
5151
example.ExaFile{},
5252
example.ExaCustomer{},
5353
example.ExaFileChunk{},
5454
example.ExaFileUploadAndDownload{},
55-
56-
// 自动化模块表
57-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
58-
59-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
6055
)
6156
if err != nil {
6257
global.GVA_LOG.Error("register table failed", zap.Error(err))

server/initialize/router.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616

1717
func Routers() *gin.Engine {
1818
Router := gin.Default()
19+
InstallPlugin(Router) // 安装插件
1920
systemRouter := router.RouterGroupApp.System
2021
exampleRouter := router.RouterGroupApp.Example
2122
// 如果想要不使用nginx代理前端网页,可以修改 web/.env.production 下的
@@ -69,13 +70,8 @@ func Routers() *gin.Engine {
6970
exampleRouter.InitCustomerRouter(PrivateGroup) // 客户路由
7071
exampleRouter.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
7172

72-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
73-
74-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
7573
}
7674

77-
InstallPlugin(Router) // 安装插件
78-
7975
global.GVA_LOG.Info("router register success")
8076
return Router
8177
}

server/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func main() {
2929
initialize.Timer()
3030
initialize.DBList()
3131
if global.GVA_DB != nil {
32-
initialize.RegisterTables(global.GVA_DB) // 初始化表
32+
initialize.RegisterTables() // 初始化表
3333
// 程序结束前关闭数据库链接
3434
db, _ := global.GVA_DB.DB()
3535
defer db.Close()
Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
package {{ .PackageName }}
22

33
type ApiGroup struct {
4-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
5-
6-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
74
}
Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
package {{ .PackageName }}
22

33
type RouterGroup struct {
4-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
5-
6-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
74
}

server/resource/autocode_template/subcontract/service_enter.go.tpl

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,5 @@ package {{ .PackageName }}
22

33

44
type ServiceGroup struct {
5-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
6-
7-
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
85
}
96

server/service/system/sys_auto_code.go

Lines changed: 21 additions & 202 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
11
package system
22

33
import (
4-
"bytes"
54
"encoding/json"
65
"errors"
76
"fmt"
8-
"go/ast"
9-
"go/format"
10-
"go/parser"
11-
"go/token"
7+
ast2 "github.com/flipped-aurora/gin-vue-admin/server/utils/ast"
8+
"golang.org/x/text/cases"
9+
"golang.org/x/text/language"
1210
"io"
13-
"log"
1411
"mime/multipart"
1512
"os"
1613
"path/filepath"
1714
"strconv"
1815
"strings"
1916
"text/template"
2017

18+
"github.com/flipped-aurora/gin-vue-admin/server/resource/autocode_template/subcontract"
2119
cp "github.com/otiai10/copy"
2220
"go.uber.org/zap"
23-
"golang.org/x/text/cases"
24-
"golang.org/x/text/language"
25-
26-
"github.com/flipped-aurora/gin-vue-admin/server/resource/autocode_template/subcontract"
2721

2822
"github.com/flipped-aurora/gin-vue-admin/server/global"
2923
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
@@ -53,23 +47,10 @@ type autoPackage struct {
5347
var (
5448
packageInjectionMap map[string]astInjectionMeta
5549
injectionPaths []injectionMeta
56-
caser = cases.Title(language.English)
5750
)
5851

5952
func Init(Package string) {
6053
injectionPaths = []injectionMeta{
61-
{
62-
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
63-
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go"),
64-
funcName: "MysqlTables",
65-
structNameF: Package + ".%s{},",
66-
},
67-
{
68-
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
69-
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go"),
70-
funcName: "Routers",
71-
structNameF: Package + "Router.Init%sRouter(PrivateGroup)",
72-
},
7354
{
7455
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
7556
global.GVA_CONFIG.AutoCode.Server, fmt.Sprintf(global.GVA_CONFIG.AutoCode.SApi, Package), "enter.go"),
@@ -313,6 +294,21 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
313294
return err
314295
}
315296
}
297+
298+
{
299+
// 在gorm.go 注入 自动迁移
300+
path := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
301+
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
302+
ast2.AddRegisterTablesAst(path, "RegisterTables", autoCode.Package, autoCode.BusinessDB, autoCode.StructName)
303+
}
304+
305+
{
306+
// router.go 注入 自动迁移
307+
path := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
308+
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
309+
ast2.AddRouterCode(path, "Routers", autoCode.Package, autoCode.StructName)
310+
}
311+
//给各个enter进行注入
316312
err = injectionCode(autoCode.StructName, &injectionCodeMeta)
317313
if err != nil {
318314
return
@@ -324,15 +320,6 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
324320
bf.WriteString(";")
325321
}
326322
}
327-
328-
var gormPath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
329-
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
330-
var routePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
331-
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
332-
var imporStr = fmt.Sprintf("github.com/flipped-aurora/gin-vue-admin/server/model/%s", autoCode.Package)
333-
_ = ImportReference(routePath, "", "", autoCode.Package, "")
334-
_ = ImportReference(gormPath, imporStr, "", "", "")
335-
336323
} else { // 打包
337324
if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
338325
return err
@@ -581,9 +568,7 @@ func (autoCodeService *AutoCodeService) getNeedList(autoCode *system.AutoCodeStr
581568
func injectionCode(structName string, bf *strings.Builder) error {
582569
for _, meta := range injectionPaths {
583570
code := fmt.Sprintf(meta.structNameF, structName)
584-
if err := utils.AutoInjectionCode(meta.path, meta.funcName, code); err != nil {
585-
return err
586-
}
571+
ast2.ImportForAutoEnter(meta.path, meta.funcName, code)
587572
bf.WriteString(fmt.Sprintf("%s@%s@%s;", meta.path, meta.funcName, code))
588573
}
589574
return nil
@@ -657,179 +642,13 @@ func (autoCodeService *AutoCodeService) CreatePackageTemp(packageName string) er
657642
// 创建完成后在对应的位置插入结构代码
658643
for _, v := range pendingTemp {
659644
meta := packageInjectionMap[v.name]
660-
if err := ImportReference(meta.path, fmt.Sprintf(meta.importCodeF, v.name, packageName), fmt.Sprintf(meta.structNameF, caser.String(packageName)), fmt.Sprintf(meta.packageNameF, packageName), meta.groupName); err != nil {
645+
if err := ast2.ImportReference(meta.path, fmt.Sprintf(meta.importCodeF, v.name, packageName), fmt.Sprintf(meta.structNameF, cases.Title(language.English).String(packageName)), fmt.Sprintf(meta.packageNameF, packageName), meta.groupName); err != nil {
661646
return err
662647
}
663648
}
664649
return nil
665650
}
666651

667-
type Visitor struct {
668-
ImportCode string
669-
StructName string
670-
PackageName string
671-
GroupName string
672-
}
673-
674-
func (vi *Visitor) Visit(node ast.Node) ast.Visitor {
675-
switch n := node.(type) {
676-
case *ast.GenDecl:
677-
// 查找有没有import context包
678-
// Notice:没有考虑没有import任何包的情况
679-
if n.Tok == token.IMPORT && vi.ImportCode != "" {
680-
vi.addImport(n)
681-
// 不需要再遍历子树
682-
return nil
683-
}
684-
if n.Tok == token.TYPE && vi.StructName != "" && vi.PackageName != "" && vi.GroupName != "" {
685-
vi.addStruct(n)
686-
return nil
687-
}
688-
case *ast.FuncDecl:
689-
if n.Name.Name == "Routers" {
690-
vi.addFuncBodyVar(n)
691-
return nil
692-
}
693-
694-
}
695-
return vi
696-
}
697-
698-
func (vi *Visitor) addStruct(genDecl *ast.GenDecl) ast.Visitor {
699-
for i := range genDecl.Specs {
700-
switch n := genDecl.Specs[i].(type) {
701-
case *ast.TypeSpec:
702-
if strings.Index(n.Name.Name, "Group") > -1 {
703-
switch t := n.Type.(type) {
704-
case *ast.StructType:
705-
f := &ast.Field{
706-
Names: []*ast.Ident{
707-
{
708-
Name: vi.StructName,
709-
Obj: &ast.Object{
710-
Kind: ast.Var,
711-
Name: vi.StructName,
712-
},
713-
},
714-
},
715-
Type: &ast.SelectorExpr{
716-
X: &ast.Ident{
717-
Name: vi.PackageName,
718-
},
719-
Sel: &ast.Ident{
720-
Name: vi.GroupName,
721-
},
722-
},
723-
}
724-
t.Fields.List = append(t.Fields.List, f)
725-
}
726-
}
727-
}
728-
}
729-
return vi
730-
}
731-
732-
func (vi *Visitor) addImport(genDecl *ast.GenDecl) ast.Visitor {
733-
// 是否已经import
734-
hasImported := false
735-
for _, v := range genDecl.Specs {
736-
importSpec := v.(*ast.ImportSpec)
737-
// 如果已经包含
738-
if importSpec.Path.Value == strconv.Quote(vi.ImportCode) {
739-
hasImported = true
740-
}
741-
}
742-
if !hasImported {
743-
genDecl.Specs = append(genDecl.Specs, &ast.ImportSpec{
744-
Path: &ast.BasicLit{
745-
Kind: token.STRING,
746-
Value: strconv.Quote(vi.ImportCode),
747-
},
748-
})
749-
}
750-
return vi
751-
}
752-
753-
func (vi *Visitor) addFuncBodyVar(funDecl *ast.FuncDecl) ast.Visitor {
754-
hasVar := false
755-
for _, v := range funDecl.Body.List {
756-
switch varSpec := v.(type) {
757-
case *ast.AssignStmt:
758-
for i := range varSpec.Lhs {
759-
switch nn := varSpec.Lhs[i].(type) {
760-
case *ast.Ident:
761-
if nn.Name == vi.PackageName+"Router" {
762-
hasVar = true
763-
}
764-
}
765-
}
766-
}
767-
}
768-
if !hasVar {
769-
assignStmt := &ast.AssignStmt{
770-
Lhs: []ast.Expr{
771-
&ast.Ident{
772-
Name: vi.PackageName + "Router",
773-
Obj: &ast.Object{
774-
Kind: ast.Var,
775-
Name: vi.PackageName + "Router",
776-
},
777-
},
778-
},
779-
Tok: token.DEFINE,
780-
Rhs: []ast.Expr{
781-
&ast.SelectorExpr{
782-
X: &ast.SelectorExpr{
783-
X: &ast.Ident{
784-
Name: "router",
785-
},
786-
Sel: &ast.Ident{
787-
Name: "RouterGroupApp",
788-
},
789-
},
790-
Sel: &ast.Ident{
791-
Name: caser.String(vi.PackageName),
792-
},
793-
},
794-
},
795-
}
796-
funDecl.Body.List = append(funDecl.Body.List, funDecl.Body.List[1])
797-
index := 1
798-
copy(funDecl.Body.List[index+1:], funDecl.Body.List[index:])
799-
funDecl.Body.List[index] = assignStmt
800-
}
801-
return vi
802-
}
803-
804-
func ImportReference(filepath, importCode, structName, packageName, groupName string) error {
805-
fSet := token.NewFileSet()
806-
fParser, err := parser.ParseFile(fSet, filepath, nil, parser.ParseComments)
807-
if err != nil {
808-
return err
809-
}
810-
importCode = strings.TrimSpace(importCode)
811-
v := &Visitor{
812-
ImportCode: importCode,
813-
StructName: structName,
814-
PackageName: packageName,
815-
GroupName: groupName,
816-
}
817-
if importCode == "" {
818-
ast.Print(fSet, fParser)
819-
}
820-
821-
ast.Walk(v, fParser)
822-
823-
var output []byte
824-
buffer := bytes.NewBuffer(output)
825-
err = format.Node(buffer, fSet, fParser)
826-
if err != nil {
827-
log.Fatal(err)
828-
}
829-
// 写回数据
830-
return os.WriteFile(filepath, buffer.Bytes(), 0o600)
831-
}
832-
833652
// CreatePlug 自动创建插件模板
834653
func (autoCodeService *AutoCodeService) CreatePlug(plug system.AutoPlugReq) error {
835654
// 检查列表参数是否有效

0 commit comments

Comments
 (0)