forked from flipped-aurora/gin-vue-admin
/
inject_import.go
110 lines (102 loc) · 2.76 KB
/
inject_import.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package east
import (
"fmt"
"github.com/ve-weiyi/go-sdk/utils/jsonconv"
"go/ast"
"go/parser"
"go/token"
"log"
"strconv"
)
// 插入 import ImportAlias ImportPackage
type ImportMeta struct {
fset *token.FileSet
InjectCode string
ImportAlias string //导入别名
ImportPackage string //导入包路径
HasDone bool
}
func (vi *ImportMeta) Visit(node ast.Node) ast.Visitor {
switch genDecl := node.(type) {
case *ast.GenDecl:
if genDecl.Tok == token.IMPORT {
//ast.Println(token.NewFileSet(),genDecl)
// 是否已经import
hasImported := false
for _, v := range genDecl.Specs {
importSpec := v.(*ast.ImportSpec)
// 如果已经包含
if importSpec.Path.Value == strconv.Quote(vi.ImportPackage) {
hasImported = true
}
}
if !hasImported && !vi.HasDone {
importSp := &ast.ImportSpec{
Name: &ast.Ident{
Name: vi.ImportAlias,
},
Path: &ast.BasicLit{
Kind: token.STRING,
Value: strconv.Quote(vi.ImportPackage),
},
}
//放到最后
genDecl.Specs = append(genDecl.Specs, importSp)
vi.HasDone = true
//log.Println("ImportPackage end", vi.ImportPackage, vi.hasImported)
//ast.Println(token.NewFileSet(), node)
}
//log.Println("--", jsonconv.ObjectToJsonIndent(genDecl.Specs))
} else {
}
}
return vi
}
func (vi *ImportMeta) RollBack(node ast.Node) ast.Visitor {
if genDecl, ok := node.(*ast.GenDecl); ok {
if genDecl.Tok == token.IMPORT {
//ast.Println(token.NewFileSet(),genDecl)
// 是否已经import
for k, v := range genDecl.Specs {
importSpec := v.(*ast.ImportSpec)
// 如果已经包含
if importSpec.Path.Value == strconv.Quote(vi.ImportPackage) {
//删除
genDecl.Specs = append(append([]ast.Spec{}, genDecl.Specs[:k]...), genDecl.Specs[k+1:]...)
genDecl.Specs = nil
}
}
}
}
return vi
}
func (vi *ImportMeta) RollBackImportSpec(file *ast.File) ast.Visitor {
var newImport []*ast.ImportSpec
for _, imp := range file.Imports {
if imp.Path.Value == strconv.Quote(vi.ImportPackage) {
newImport = append(newImport, imp)
}
}
file.Imports = newImport
//log.Println("RollBackImportSpec", vi.ImportPackage)
//ast.Println(token.NewFileSet(), file.Imports)
return vi
}
func NewImportMete(importCode string) {
meta := &ImportMeta{}
input := fmt.Sprintf("package main\nimport (%s)", importCode)
fParse, err := parser.ParseFile(token.NewFileSet(), "", input, 0)
if err != nil {
fmt.Println("Error parsing file:", err)
}
ast.Print(token.NewFileSet(), fParse)
ast.Inspect(fParse, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.ImportSpec:
meta.ImportAlias = x.Name.Name
meta.ImportPackage = x.Path.Value
}
return true
})
log.Println("NewImportMete", jsonconv.ObjectToJsonIndent(meta))
}