/
util.go
91 lines (86 loc) · 2.63 KB
/
util.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
package gen
import (
"bytes"
"fmt"
"go/ast"
"go/doc"
"regexp"
"strings"
"github.com/carlos-yuan/cargen/util/convert"
"github.com/carlos-yuan/cargen/util/fileUtil"
)
func ModelToProtobuf(path, protoPkg, goPkg, modelPath, modelName string) {
pkg, err := parseDir(modelPath, modelName)
if err != nil {
panic(err)
}
pkgs := doc.New(pkg, modelPath, doc.AllMethods)
var protoBuf bytes.Buffer
protoBuf.WriteString(fmt.Sprintf("// Code generated by car-gen. DO NOT EDIT.\n\nsyntax = \"proto3\";\n\npackage %s;\n\noption go_package = \"%s\";\n\n", protoPkg, goPkg))
var tableName []string
for _, value := range pkgs.Consts {
for _, name := range value.Names {
if strings.Contains(name, "TableName") {
tableName = append(tableName, strings.ReplaceAll(name, "TableName", ""))
}
}
}
for _, t := range pkgs.Types {
for _, name := range tableName {
if t.Name == name && len(t.Decl.Specs) == 1 {
list := t.Decl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List
var i = 1
protoBuf.WriteString(fmt.Sprintf("message %sRsp {\n", t.Name))
for _, field := range list {
name := field.Names[0].Name
typ := ""
switch field.Type.(type) {
case *ast.Ident:
typ = field.Type.(*ast.Ident).Name
case *ast.SelectorExpr:
typ = field.Type.(*ast.SelectorExpr).X.(*ast.Ident).Name + "." + field.Type.(*ast.SelectorExpr).Sel.Name
case *ast.StarExpr:
switch field.Type.(*ast.StarExpr).X.(type) {
case *ast.Ident:
typ = field.Type.(*ast.StarExpr).X.(*ast.Ident).Name
case *ast.SelectorExpr:
typ = field.Type.(*ast.StarExpr).X.(*ast.SelectorExpr).X.(*ast.Ident).Name + "." + field.Type.(*ast.StarExpr).X.(*ast.SelectorExpr).Sel.Name
}
}
if !(name == "CreateBy" || name == "DeletedAt" || name == "UpdateBy") {
if typ == "time.Time" {
typ = "string"
}
switch typ {
case "float64":
typ = "double"
case "float32":
typ = "float"
case "time.Time":
typ = "string"
}
if name != "ID" {
name = convert.FistToLower(name)
}
reg := regexp.MustCompile("`gorm:(.*);comment:(.*)\"(.*)json:(.*)`")
params := reg.FindStringSubmatch(field.Tag.Value)
var comment string
if len(params) == 5 {
comment = params[2]
} else {
comment = name
}
protoBuf.WriteString(fmt.Sprintf("\t%s %s =%d;//%s\n", typ, name, i, comment))
i++
}
}
protoBuf.WriteString("}\n\n")
}
}
}
dir := path + "/" + protoPkg + "/rpc/" + protoPkg + "_model_gen.proto"
err = fileUtil.WriteByteFile(dir, protoBuf.Bytes())
if err != nil {
panic(err)
}
}