/
convert.go
252 lines (233 loc) · 6.82 KB
/
convert.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"sort"
"strings"
"golang.org/x/tools/go/packages"
)
type StructType struct {
FullName string
Name string
Pkg *packages.Package
Content map[string]string
}
type Convert struct {
from *StructType
to *StructType
pkg *packages.Package
}
var raw = []string{"int8", "int16", "int32", "int", "int64"}
var (
from = flag.String("from", "", "input from")
to = flag.String("to", "", "input to")
)
func main() {
flag.Parse()
if from == nil || to == nil {
os.Exit(1)
}
cfg := &packages.Config{
Mode: packages.LoadAllSyntax,
Tests: true,
}
pkg, _ := packages.Load(cfg)
locationPkg := pkg[0]
allPkgs := listAllPkgs(pkg[0])
convert := Convert{pkg: locationPkg}
if convert.from = buildStructType(locationPkg, allPkgs, *from); convert.from == nil {
fmt.Println("build from struct fail")
return
}
if convert.to = buildStructType(locationPkg, allPkgs, *to); convert.to == nil {
fmt.Println("build to struct fail")
return
}
if convert.write() == nil {
fmt.Println("ok!")
} else {
fmt.Println("sorry, an error has occured!")
}
}
func buildStructType(locationPkg *packages.Package, allPkgs map[string]*packages.Package, filed string) *StructType {
result := &StructType{FullName: filed}
if s := strings.Index(filed, "."); s > 0 {
result.Name = filed[s+1:]
if result.Pkg = allPkgs[filed[:s]]; result.Pkg == nil {
return nil
}
} else {
result.Name = filed
result.Pkg = locationPkg
}
res := findAllFieldsFromPkg(result.Pkg)
if result.Content = res[result.Name]; result.Content == nil {
return nil
}
return result
}
func indexOf(ss []string, s string) int {
for i, v := range ss {
if v == s {
return i
}
}
return -1
}
func stringfySingle(name string, fromType, toType string) string {
if fromType == toType {
return fmt.Sprintf("\tto.%v = from.%v\n", name, name)
}
if "*"+fromType == toType {
return fmt.Sprintf("\tto.%v = &from.%v\n", name, name)
}
if fromType == "*"+toType {
result := fmt.Sprintf("\tif from.%v != nil {\n", name)
result += fmt.Sprintf("\t\tto.%v = *from.%v\n", name, name)
result += "\t}\n"
return result
}
// 判断能不能转换
fromIdx := indexOf(raw, strings.ReplaceAll(fromType, "*", ""))
toIdx := indexOf(raw, strings.ReplaceAll(toType, "*", ""))
if fromIdx >= 0 && toIdx >= 0 {
result := ""
if fromIdx > toIdx {
result += fmt.Sprintf("\t// %v -> %v\n", fromType, toType)
}
if !strings.HasPrefix(fromType, "*") && !strings.HasPrefix(toType, "*") {
// i -> i
result += fmt.Sprintf("\tto.%v = %v(from.%v)\n", name, toType, name)
} else if strings.HasPrefix(fromType, "*") && !strings.HasPrefix(toType, "*") {
// *i -> i
result += fmt.Sprintf("\tif from.%v != nil {\n", name)
result += fmt.Sprintf("\t\tto.%v = %v(*from.%v)\n", name, toType, name)
result += "\t}\n"
} else if !strings.HasPrefix(fromType, "*") && strings.HasPrefix(toType, "*") {
// i -> *i
tempName := lowwer(name) + "Temp"
result += fmt.Sprintf("\t%v := %v(from.%v)\n", tempName, toType[1:], name)
result += fmt.Sprintf("\tto.%v = &%v\n", name, tempName)
} else if strings.HasPrefix(fromType, "*") && strings.HasPrefix(toType, "*") {
// *i -> *i
tempName := lowwer(name) + "Temp"
result += fmt.Sprintf("\tif from.%v != nil {\n", name)
result += fmt.Sprintf("\t\t%v := %v(*from.%v)\n", tempName, toType[1:], name)
result += fmt.Sprintf("\t\tto.%v = &%v\n", name, tempName)
result += "\t}\n"
}
return result
}
return ""
}
func (c *Convert) write() error {
functionName := fmt.Sprintf("Convert%v%vTo%v%v", capitalize(c.from.Pkg.Name), c.from.Name, capitalize(c.to.Pkg.Name), c.to.Name)
functionContent := fmt.Sprintf("func %v(from *%v) *%v {\n",
functionName, c.from.FullName, c.to.FullName)
functionContent += "\tif from == nil {\n\t\treturn nil\n\t}\n"
functionContent += fmt.Sprintf("\tto := &%v{}\n", c.to.FullName)
var names []string
for name := range c.from.Content {
if _, ok := c.to.Content[name]; ok {
names = append(names, name)
}
}
sort.Strings(names)
for _, name := range names {
functionContent += stringfySingle(name, c.from.Content[name], c.to.Content[name])
}
functionContent += "\treturn to\n}"
convertFile, err := os.OpenFile("convert.go", os.O_RDWR, os.ModeAppend)
if pathErr := (*os.PathError)(nil); errors.As(err, &pathErr) {
convertFile, _ = os.Create("convert.go")
}
content, _ := io.ReadAll(convertFile)
defer convertFile.Close()
buf := bytes.Buffer{}
f, _ := parser.ParseFile(token.NewFileSet(), "", content, 0)
if len(content) == 0 || f == nil {
buf.WriteString(fmt.Sprintf("package %v\n\n", c.pkg.Name))
buf.WriteString(fmt.Sprintf("import (\n\t\"%v\"\n", c.from.Pkg.PkgPath))
if c.from.Pkg.PkgPath != c.to.Pkg.PkgPath {
buf.WriteString(fmt.Sprintf("\t\"%v\"\n", c.to.Pkg.PkgPath))
}
buf.WriteString(")\n\n")
buf.WriteString(functionContent)
} else {
for _, decl := range f.Decls {
if v, ok := decl.(*ast.FuncDecl); ok && v.Name.Name == functionName {
buf.Write(content[:v.Pos()-1])
buf.WriteString(functionContent)
buf.Write(content[v.End()-1:])
break
}
}
if buf.Len() == 0 {
buf.Write(content)
buf.WriteString("\n\n")
buf.WriteString(functionContent)
}
}
convertFile.Seek(0, 0)
_, err = convertFile.Write(buf.Bytes())
return err
}
func findAllFieldsFromPkg(pkg *packages.Package) (fields map[string]map[string]string) {
fields = make(map[string]map[string]string)
for _, goFile := range pkg.GoFiles {
rawFile, _ := os.Open(goFile)
content, _ := io.ReadAll(rawFile)
f, _ := parser.ParseFile(token.NewFileSet(), "", content, 0)
for _, v := range f.Decls {
if g, ok := v.(*ast.GenDecl); ok && g.Tok == token.TYPE {
for _, v := range g.Specs {
if typeSpec, ok := v.(*ast.TypeSpec); ok {
if structType, ok := typeSpec.Type.(*ast.StructType); ok {
fields[typeSpec.Name.Name] = make(map[string]string)
for _, field := range structType.Fields.List {
if len(field.Names) > 0 {
if starExpr, ok := field.Type.(*ast.StarExpr); ok {
if identType, ok := (starExpr.X).(*ast.Ident); ok {
fields[typeSpec.Name.Name][field.Names[0].Name] = "*" + identType.Name
}
} else if identType, ok := (field.Type).(*ast.Ident); ok {
fields[typeSpec.Name.Name][field.Names[0].Name] = identType.Name
}
}
}
}
}
}
}
}
}
return
}
func listAllPkgs(pkg *packages.Package) map[string]*packages.Package {
result := make(map[string]*packages.Package)
for _, value := range pkg.Imports {
result[value.Name] = value
}
return result
}
func capitalize(str string) string {
r := []rune(str)
if r[0] >= 97 && r[0] <= 122 {
r[0] -= 32
}
return string(r)
}
func lowwer(str string) string {
r := []rune(str)
if r[0] >= 65 && r[0] <= 90 {
r[0] += 32
}
return string(r)
}