-
Notifications
You must be signed in to change notification settings - Fork 21
/
transport_grpc_protobuf_type_converters.go
282 lines (260 loc) · 9.19 KB
/
transport_grpc_protobuf_type_converters.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package template
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
. "github.com/dave/jennifer/jen"
mstrings "github.com/devimteam/microgen/generator/strings"
"github.com/devimteam/microgen/generator/write_strategy"
"github.com/devimteam/microgen/logger"
"github.com/vetcher/go-astra/types"
)
const (
GolangProtobufPtypesTimestamp = "github.com/golang/protobuf/ptypes/timestamp"
JsonbPackage = "github.com/sas1024/gorm-jsonb/jsonb"
GolangProtobufPtypes = "github.com/golang/protobuf/ptypes"
GolangProtobufWrappers = "github.com/golang/protobuf/ptypes/wrappers"
)
type stubGRPCTypeConverterTemplate struct {
info *GenerationInfo
alreadyRenderedConverters []string
state WriteStrategyState
}
func NewStubGRPCTypeConverterTemplate(info *GenerationInfo) Template {
return &stubGRPCTypeConverterTemplate{
info: info,
}
}
func specialTypeConverter(p types.Type) *Statement {
name := types.TypeName(p)
imp := types.TypeImport(p)
// error -> string
if name != nil && *name == "error" && imp == nil {
return Id("string")
}
// time.Time -> timestamp.Timestamp
if name != nil && *name == "Time" && imp != nil && imp.Package == "time" {
if types.TypeArray(p) == nil { // ignore []time.Time case
return Op("*").Qual(GolangProtobufPtypesTimestamp, "Timestamp")
}
}
// jsonb.JSONB -> string
if name != nil && *name == "JSONB" && imp != nil && imp.Package == JsonbPackage {
return Id("string")
}
// *string -> *wrappers.StringValue
if name != nil && *name == "string" && imp == nil {
_, ok := p.(types.TPointer)
if ok {
return Op("*").Qual(GolangProtobufWrappers, "StringValue")
}
}
// *float64 -> *wrappers.DoubleValue
if name != nil && *name == "float64" && imp == nil {
ptr, ok := p.(types.TPointer)
if ok && ptr.NumberOfPointers == 1 {
return Op("*").Qual(GolangProtobufWrappers, "DoubleValue")
}
}
return nil
}
func converterToProtoBody(field *types.Variable) Code {
s := &Statement{}
switch typeToProto(field.Type, 0) {
case "ErrorToProto":
s.If(Id(mstrings.ToLowerFirst(field.Name))).Op("==").Nil().Block(
Return().List(Lit(""), Nil()),
).Line()
s.Return().List(Id(mstrings.ToLowerFirst(field.Name)).Dot("Error").Call(), Nil())
case "ByteListToProto", "ListByteToProto":
s.Return().List(Id(mstrings.ToLowerFirst(field.Name)), Nil())
case "TimeTimeToProto":
s.Return().Qual(GolangProtobufPtypes, "TimestampProto").Call(Id(field.Name))
case "ListStringToProto", "SliceStringToProto":
s.Return().List(Id(mstrings.ToLowerFirst(field.Name)), Nil())
// if str == "" {
// return nil
// }
// return &wrappers.StringValue{Value: str}
case "PtrStringToProto":
s.If(Id(mstrings.ToLowerFirst(field.Name)).Op("==").Nil()).Block(
Return().List(Nil(), Nil()),
)
s.Line().Return().List(Op("&").Qual(GolangProtobufWrappers, "StringValue").Block(Dict{Id("Value"): Op("*").Id(mstrings.ToLowerFirst(field.Name)).Op(",")}), Nil())
default:
s.Panic(Lit("function not provided")).Comment("// TODO: provide converter")
}
return s
}
func converterProtoToBody(field *types.Variable) Code {
s := &Statement{}
switch protoToType(field.Type, 0) {
case "ProtoToError":
s.If().Id("proto" + mstrings.ToUpperFirst(field.Name)).Op("==").Lit("").Block(
Return().List(Nil(), Nil()),
).Line()
s.Return().List(Qual("errors", "New").Call(Id("proto"+mstrings.ToUpperFirst(field.Name))), Nil())
case "ProtoToByteList", "ProtoToListByte":
s.Return().List(Id("proto"+mstrings.ToUpperFirst(field.Name)), Nil())
case "ProtoToTimeTime":
s.Return().Qual(GolangProtobufPtypes, "Timestamp").Call(Id("proto" + mstrings.ToUpperFirst(field.Name)))
case "ProtoToListString", "ProtoToSliceString":
s.Return().List(Id("proto"+mstrings.ToUpperFirst(field.Name)), Nil())
case "ProtoToPtrString":
s.If(Id("proto" + mstrings.ToUpperFirst(field.Name)).Op("==").Nil()).Block(
Return().List(Nil(), Nil()),
)
s.Line().Return().List(Op("&").Id("proto"+mstrings.ToUpperFirst(field.Name)).Dot("Value"), Nil())
default:
s.Panic(Lit("function not provided")).Comment("// TODO: provide converter")
}
return s
}
// Render whole file with protobuf converters.
//
// // This file was automatically generated by "microgen" utility.
// package protobuf
//
// func IntListToProto(positions []int) (protoPositions []int64, convPositionsErr error) {
// panic("method not provided")
// }
//
// func ProtoToIntList(protoPositions []int64) (positions []int, convPositionsErr error) {
// panic("method not provided")
// }
//
func (t *stubGRPCTypeConverterTemplate) Render(ctx context.Context) write_strategy.Renderer {
f := &Statement{}
for _, signature := range t.info.Iface.Methods {
if !t.info.AllowedMethods[signature.Name] {
continue
}
args := append(RemoveContextIfFirst(signature.Args), removeErrorIfLast(signature.Results)...)
for _, field := range args {
if _, ok := golangTypeToProto(ctx, "", &field); !ok && !mstrings.IsInStringSlice(typeToProto(field.Type, 0), t.alreadyRenderedConverters) {
f.Line().Add(t.stubConverterToProto(ctx, &field)).Line()
t.alreadyRenderedConverters = append(t.alreadyRenderedConverters, typeToProto(field.Type, 0))
}
if _, ok := protoTypeToGolang(ctx, "", &field); !ok && !mstrings.IsInStringSlice(protoToType(field.Type, 0), t.alreadyRenderedConverters) {
f.Line().Add(t.stubConverterProtoTo(ctx, &field)).Line()
t.alreadyRenderedConverters = append(t.alreadyRenderedConverters, protoToType(field.Type, 0))
}
}
}
if t.state == AppendStrat {
return f
}
file := NewFile("transportgrpc")
file.ImportAlias(t.info.ProtobufPackageImport, "pb")
file.ImportAlias(t.info.SourcePackageImport, serviceAlias)
file.HeaderComment(t.info.FileHeader)
file.PackageComment(`It is better for you if you do not change functions names!`)
file.PackageComment(`This file will never be overwritten.`)
file.Add(f)
return file
}
func (stubGRPCTypeConverterTemplate) DefaultPath() string {
return filenameBuilder(PathTransport, "grpc", "protobuf_type_converters")
}
func (t *stubGRPCTypeConverterTemplate) Prepare(ctx context.Context) error {
if t.info.ProtobufPackageImport == "" {
return fmt.Errorf("protobuf package is empty")
}
return nil
}
func (t *stubGRPCTypeConverterTemplate) ChooseStrategy(ctx context.Context) (write_strategy.Strategy, error) {
if err := statFile(t.info.OutputFilePath, t.DefaultPath()); os.IsNotExist(err) {
t.state = FileStrat
return write_strategy.NewCreateFileStrategy(t.info.OutputFilePath, t.DefaultPath()), nil
}
file, err := parsePackage(filepath.Join(t.info.OutputFilePath, t.DefaultPath()))
if err != nil {
logger.Logger.Log(0, "can't parse", t.DefaultPath(), ":", err)
return write_strategy.NewNopStrategy("", ""), nil
}
for i := range file.Functions {
t.alreadyRenderedConverters = append(t.alreadyRenderedConverters, file.Functions[i].Name)
}
t.state = AppendStrat
return write_strategy.NewAppendToFileStrategy(t.info.OutputFilePath, t.DefaultPath()), nil
}
// Render stub method for golang to protobuf converter.
//
// func IntListToProto(positions []int) (protoPositions []int64, convPositionsErr error) {
// return
// }
//
func (t *stubGRPCTypeConverterTemplate) stubConverterToProto(ctx context.Context, field *types.Variable) *Statement {
return Func().Id(typeToProto(field.Type, 0)).
Params(Id(mstrings.ToLowerFirst(field.Name)).Add(fieldType(ctx, field.Type, false))).
Params(Add(t.protoFieldType(ctx, field.Type)), Error()).
Block(converterToProtoBody(field))
}
// Render stub method for protobuf to golang converter.
//
// func ProtoToIntList(protoPositions []int64) (positions []int, convPositionsErr error) {
// return
// }
//
func (t *stubGRPCTypeConverterTemplate) stubConverterProtoTo(ctx context.Context, field *types.Variable) *Statement {
return Func().Id(protoToType(field.Type, 0)).
Params(Id("proto"+mstrings.ToUpperFirst(field.Name)).Add(t.protoFieldType(ctx, field.Type))).
Params(Add(fieldType(ctx, field.Type, false)), Error()).
Block(converterProtoToBody(field))
}
// Render protobuf field type for given func field.
//
// *repository.Visit
//
func (t *stubGRPCTypeConverterTemplate) protoFieldType(ctx context.Context, field types.Type) *Statement {
c := &Statement{}
if code := specialTypeConverter(field); code != nil {
return c.Add(code)
}
custom := false
for field != nil {
switch f := field.(type) {
case types.TImport:
if f.Import != nil {
c.Qual(t.info.ProtobufPackageImport, "")
custom = true
}
field = f.Next
case types.TName:
protoType := f.TypeName
if tmp, ok := goToProtoTypesMap[f.TypeName]; ok {
protoType = tmp
custom = true
}
if !custom && !types.IsBuiltin(f) {
c.Qual(t.info.ProtobufPackageImport, protoType)
} else {
c.Id(protoType)
}
field = nil
case types.TArray:
if f.IsSlice {
c.Index()
} else if f.ArrayLen > 0 {
c.Index(Lit(f.ArrayLen))
}
field = f.Next
case types.TMap:
return c.Map(t.protoFieldType(ctx, f.Key)).Add(t.protoFieldType(ctx, f.Value))
case types.TPointer:
c.Op(strings.Repeat("*", f.NumberOfPointers))
field = f.Next
case types.TInterface:
mhds := interfaceType(ctx, f.Interface)
return c.Interface(mhds...)
case types.TEllipsis:
c.Index()
field = f.Next
default:
return c
}
}
return c
}