-
Notifications
You must be signed in to change notification settings - Fork 8
/
1_middleend_generator.go
449 lines (399 loc) · 14.9 KB
/
1_middleend_generator.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package modules
import (
"encoding/json"
"slices"
pgs "github.com/lyft/protoc-gen-star/v2"
"github.com/pubg/protoc-gen-jsonschema/pkg/jsonschema"
"github.com/pubg/protoc-gen-jsonschema/pkg/proto"
"github.com/samber/lo"
"google.golang.org/protobuf/types/known/anypb"
)
func buildFromMessage(pluginOptions *proto.PluginOptions, message pgs.Message, mo *proto.MessageOptions) *jsonschema.Schema {
schema := &jsonschema.Schema{}
schema.Type = "object"
schema.Title = proto.GetTitleOrEmpty(mo)
schema.Description = proto.GetDescriptionOrComment(message, mo)
schema.Properties = jsonschema.NewOrderedSchemaMap()
fillSchemaByObjectKeywords(schema, mo.GetObject())
for _, field := range message.Fields() {
// Skip OneOf Block field
//if field.OneOf() != nil {
// continue
//}
propName := toPropertyName(field, pluginOptions.GetPreserveProtoFieldNames())
fieldSchema := &jsonschema.Schema{Ref: toRefId(field)}
if !pluginOptions.GetMandatoryNullable() && (field.InRealOneOf() || field.HasOptionalKeyword()) || proto.GetFieldOptions(field).GetNullable() {
fieldSchema = &jsonschema.Schema{OneOf: []*jsonschema.Schema{
{Type: "null"},
fieldSchema,
}}
}
if !field.InRealOneOf() && !field.HasOptionalKeyword() && !field.Type().IsRepeated() && !field.Type().IsMap() {
// If field is not a member of oneOf
schema.Required = append(schema.Required, propName)
}
schema.Properties.Set(propName, fieldSchema)
}
// Convert Protobuf OneOfs to JSONSchema keywords
for _, oneOf := range message.OneOfs() {
propertyNames := lo.Map[pgs.Field, string](oneOf.Fields(), func(item pgs.Field, _ int) string {
return toPropertyName(item, pluginOptions.GetPreserveProtoFieldNames())
})
oneOfSchemas := lo.Map[string, *jsonschema.Schema](propertyNames, func(item string, _ int) *jsonschema.Schema {
return &jsonschema.Schema{Required: []string{item}}
})
negativeSchema := &jsonschema.Schema{Not: &jsonschema.Schema{AnyOf: make([]*jsonschema.Schema, len(oneOfSchemas))}}
copy(negativeSchema.Not.AnyOf, oneOfSchemas)
combinedSchemas := append(oneOfSchemas, negativeSchema)
schema.AllOf = append(schema.AllOf, &jsonschema.Schema{OneOf: combinedSchemas})
}
return schema
}
func buildFromWellKnownMessage(pluginOptions *proto.PluginOptions, message pgs.Message, mo *proto.MessageOptions) *jsonschema.Schema {
baseSchema := buildFromMessage(pluginOptions, message, mo)
wellKnownType := getWellKnownMessageType(message)
if wellKnownType == WellKnownMessageTypeNone {
panic("not well known type")
}
switch wellKnownType {
case WellKnownMessageTypeK8sIntOrString:
schema := &jsonschema.Schema{}
schema.Title = baseSchema.Title
schema.Description = baseSchema.Description
schema.OneOf = []*jsonschema.Schema{
{Type: "string"},
{Type: "integer"},
}
return schema
case WellKnownMessageTypeK8sVolume:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.VolumeSource"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "volumeSource")
baseSchema.Properties.Delete("volumeSource")
case WellKnownMessageTypeK8sSecretProjection:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sConfigMapVolumeSource:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sConfigMapProjection:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sConfigMapKeySelector:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sSecretKeySelector:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sConfigMapEnvSource:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sSecretEnvSource:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.LocalObjectReference"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "localObjectReference")
baseSchema.Properties.Delete("localObjectReference")
case WellKnownMessageTypeK8sProbe:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.ProbeHandler"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "handler")
baseSchema.Properties.Delete("handler")
case WellKnownMessageTypeK8sEphemeralContainer:
baseSchema.OneOf = []*jsonschema.Schema{{Ref: ".k8s.io.api.core.v1.EphemeralContainerCommon"}}
baseSchema.Required = deletePropertyInRequired(baseSchema.Required, "ephemeralContainerCommon")
baseSchema.Properties.Delete("ephemeralContainerCommon")
}
return baseSchema
}
type WellKnownMessageType int
const (
WellKnownMessageTypeNone WellKnownMessageType = iota
WellKnownMessageTypeK8sIntOrString
WellKnownMessageTypeK8sVolume
WellKnownMessageTypeK8sSecretProjection
WellKnownMessageTypeK8sConfigMapVolumeSource
WellKnownMessageTypeK8sConfigMapProjection
WellKnownMessageTypeK8sConfigMapKeySelector
WellKnownMessageTypeK8sSecretKeySelector
WellKnownMessageTypeK8sConfigMapEnvSource
WellKnownMessageTypeK8sSecretEnvSource
WellKnownMessageTypeK8sProbe
WellKnownMessageTypeK8sEphemeralContainer
)
func isWellKnownMessage(message pgs.Message) bool {
return getWellKnownMessageType(message) != WellKnownMessageTypeNone
}
func getWellKnownMessageType(message pgs.Message) WellKnownMessageType {
switch message.FullyQualifiedName() {
case ".k8s.io.apimachinery.pkg.util.intstr.IntOrString":
return WellKnownMessageTypeK8sIntOrString
case ".k8s.io.api.core.v1.Volume":
return WellKnownMessageTypeK8sVolume
case ".k8s.io.api.core.v1.SecretProjection":
return WellKnownMessageTypeK8sSecretProjection
case ".k8s.io.api.core.v1.ConfigMapVolumeSource":
return WellKnownMessageTypeK8sConfigMapVolumeSource
case ".k8s.io.api.core.v1.ConfigMapProjection":
return WellKnownMessageTypeK8sConfigMapProjection
case ".k8s.io.api.core.v1.ConfigMapKeySelector":
return WellKnownMessageTypeK8sConfigMapKeySelector
case ".k8s.io.api.core.v1.SecretKeySelector":
return WellKnownMessageTypeK8sSecretKeySelector
case ".k8s.io.api.core.v1.ConfigMapEnvSource":
return WellKnownMessageTypeK8sConfigMapEnvSource
case ".k8s.io.api.core.v1.SecretEnvSource":
return WellKnownMessageTypeK8sSecretEnvSource
case ".k8s.io.api.core.v1.Probe":
return WellKnownMessageTypeK8sProbe
case ".k8s.io.api.core.v1.EphemeralContainer":
return WellKnownMessageTypeK8sEphemeralContainer
}
return WellKnownMessageTypeNone
}
func buildFromMessageField(field pgs.Field, fo *proto.FieldOptions) *jsonschema.Schema {
schema := &jsonschema.Schema{}
schema.Title = proto.GetTitleOrEmpty(fo)
schema.Description = proto.GetDescriptionOrComment(field, fo)
if field.Type().IsRepeated() {
schema.Ref = toRefId(field.Type().Element().Embed())
} else {
schema.Ref = toRefId(field.Type().Embed())
}
if field.Type().IsRepeated() {
return wrapSchemaInArray(schema, field, fo)
} else {
return schema
}
}
func buildFromMapField(pluginOptions *proto.PluginOptions, field pgs.Field, fo *proto.FieldOptions) *jsonschema.Schema {
schema := &jsonschema.Schema{}
schema.Title = proto.GetTitleOrEmpty(fo)
schema.Description = proto.GetDescriptionOrComment(field, fo)
schema.Type = "object"
valueSchema := &jsonschema.Schema{}
value := field.Type().Element()
protoType := value.ProtoType()
if protoType.IsInt() {
if pluginOptions.GetInt64AsString() && isInt64(protoType) {
schema.Type = "string"
schema.Format = "int64"
} else {
schema.Type = "integer"
fillSchemaByNumericKeywords(schema, fo.GetNumeric())
}
} else if protoType.IsNumeric() {
valueSchema.Type = "number"
} else if protoType == pgs.MessageT {
valueSchema.Ref = toRefId(value.Embed())
} else if protoType == pgs.BoolT {
valueSchema.Type = "boolean"
} else if protoType == pgs.EnumT {
valueSchema.Ref = toRefId(value.Enum())
} else if protoType == pgs.StringT {
valueSchema.Type = "string"
} else if protoType == pgs.BytesT {
valueSchema.Type = "string"
// Base64 Regex Expression
valueSchema.Pattern = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
}
schema.AdditionalProperties = valueSchema
return schema
}
func buildFromScalaField(pluginOptions *proto.PluginOptions, field pgs.Field, fo *proto.FieldOptions) *jsonschema.Schema {
schema := &jsonschema.Schema{}
schema.Title = proto.GetTitleOrEmpty(fo)
schema.Description = proto.GetDescriptionOrComment(field, fo)
protoType := field.Type().ProtoType()
if protoType.IsInt() {
if pluginOptions.GetInt64AsString() && isInt64(protoType) {
schema.Type = "string"
schema.Format = "int64"
} else {
schema.Type = "integer"
fillSchemaByNumericKeywords(schema, fo.GetNumeric())
}
} else if protoType == pgs.DoubleT || protoType == pgs.FloatT {
schema.Type = "number"
fillSchemaByNumericKeywords(schema, fo.GetNumeric())
} else if protoType == pgs.BoolT {
schema.Type = "boolean"
} else if protoType == pgs.EnumT {
if field.Type().IsRepeated() {
schema.Ref = toRefId(field.Type().Element().Enum())
} else {
schema.Ref = toRefId(field.Type().Enum())
}
} else if protoType == pgs.StringT {
schema.Type = "string"
fillSchemaByStringKeywords(schema, fo.GetString_())
} else if protoType == pgs.BytesT {
schema.Type = "string"
// Base64 Regex Expression
schema.Pattern = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
fillSchemaByStringKeywords(schema, fo.GetString_())
}
if field.Type().IsRepeated() {
return wrapSchemaInArray(schema, field, fo)
} else {
return schema
}
}
func buildFromEnum(enum pgs.Enum) (*jsonschema.Schema, error) {
eo := proto.GetEnumOptions(enum)
schema := &jsonschema.Schema{}
switch eo.GetMappingType() {
case proto.EnumOptions_MapToString:
schema.Type = "string"
case proto.EnumOptions_MapToNumber:
schema.Type = "number"
case proto.EnumOptions_MapToCustom:
schema.Type = "string"
}
schema.Title = proto.GetTitleOrEmpty(eo)
schema.Description = proto.GetDescriptionOrComment(enum, eo)
for _, enumValue := range enum.Values() {
switch eo.GetMappingType() {
case proto.EnumOptions_MapToString:
schema.Enum = append(schema.Enum, enumValue.Name().String())
case proto.EnumOptions_MapToNumber:
schema.Enum = append(schema.Enum, enumValue.Value())
case proto.EnumOptions_MapToCustom:
evo := proto.GetEnumValueOptions(enumValue)
customValue, err := parseScalaValueFromAny(evo.GetCustomValue())
if err != nil {
return nil, err
}
if customValue == nil {
schema.Enum = append(schema.Enum, enumValue.Name().String())
} else {
schema.Enum = append(schema.Enum, customValue)
}
}
}
return schema, nil
}
func wrapSchemaInArray(schema *jsonschema.Schema, field pgs.Field, fo *proto.FieldOptions) *jsonschema.Schema {
repeatedSchema := &jsonschema.Schema{}
repeatedSchema.Title = schema.Title
repeatedSchema.Description = schema.Description
repeatedSchema.Type = "array"
repeatedSchema.Items = schema
fillSchemaByArrayKeywords(repeatedSchema, fo.GetArray())
return repeatedSchema
}
func buildFromWellKnownField(field pgs.Field, fo *proto.FieldOptions) *jsonschema.Schema {
schema := &jsonschema.Schema{}
schema.Title = proto.GetTitleOrEmpty(fo)
schema.Description = proto.GetDescriptionOrComment(field, fo)
wellKnownType := getWellKnownFieldType(field)
if wellKnownType == WellKnownTypeNone {
panic("not well known type")
}
switch wellKnownType {
case WellKnownTypeTimestamp:
schema.Type = "string"
schema.Format = "date-time"
fillSchemaByStringKeywords(schema, fo.GetString_())
case WellKnownTypeDuration:
schema.Type = "string"
schema.Format = "duration"
fillSchemaByStringKeywords(schema, fo.GetString_())
case WellKnownTypeAny:
schema.Type = "object"
case WellKnownTypeNullValue:
schema.Type = "null"
}
if field.Type().IsRepeated() {
return wrapSchemaInArray(schema, field, fo)
} else {
return schema
}
return schema
}
func isWellKnownField(field pgs.Field) bool {
return getWellKnownFieldType(field) != WellKnownTypeNone
}
type WellKnownFieldType int
const (
WellKnownTypeNone WellKnownFieldType = iota
WellKnownTypeTimestamp
WellKnownTypeDuration
WellKnownTypeAny
WellKnownTypeNullValue
)
func getWellKnownFieldType(field pgs.Field) WellKnownFieldType {
if field.Type().IsMap() || field.Type().ProtoType() != pgs.MessageT {
return WellKnownTypeNone
}
var message pgs.Message
if field.Type().IsRepeated() {
message = field.Type().Element().Embed()
} else {
message = field.Type().Embed()
}
switch message.FullyQualifiedName() {
case ".google.protobuf.Timestamp":
return WellKnownTypeTimestamp
case ".google.protobuf.Duration":
return WellKnownTypeDuration
case ".google.protobuf.Any":
return WellKnownTypeAny
case ".google.protobuf.NullValue":
return WellKnownTypeNullValue
default:
return WellKnownTypeNone
}
}
func parseScalaValueFromAny(anyValue *anypb.Any) (any, error) {
if anyValue == nil || anyValue.Value == nil {
return nil, nil
}
var value any
if err := json.Unmarshal(anyValue.Value, &value); err != nil {
return nil, err
}
return value, nil
}
func isScalarType(field pgs.Field) bool {
protoType := field.Type().ProtoType()
if protoType.IsNumeric() {
return true
}
if protoType == pgs.BoolT {
return true
}
if protoType == pgs.EnumT {
return true
}
if protoType == pgs.StringT || protoType == pgs.BytesT {
return true
}
return false
}
func toPropertyName(field pgs.Field, preserveProto bool) string {
if !preserveProto && field.Descriptor().JsonName != nil {
return field.Descriptor().GetJsonName()
}
return field.Name().String()
}
type FqdnResolver interface {
FullyQualifiedName() string
}
func toRefId(resolver FqdnResolver) jsonschema.RefId {
return jsonschema.RefId(resolver.FullyQualifiedName())
}
func isInt64(protoType pgs.ProtoType) bool {
switch protoType {
case pgs.Int64T, pgs.UInt64T, pgs.SFixed64, pgs.SInt64, pgs.Fixed64T:
return true
}
return false
}
func deletePropertyInRequired(required []string, item string) []string {
return slices.DeleteFunc(required, func(val string) bool {
return val == item
})
}