protogen: Unify oneof getters with default protoc plugin

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
This commit is contained in:
Evgenii Stratonikov 2024-08-26 14:33:18 +03:00
parent 2bdcbe4d44
commit aa68585b53

View file

@ -126,23 +126,18 @@ func emitOneofGettersSetters(g *protogen.GeneratedFile, msg *protogen.Message, f
// For some reason protoc generates different code for oneof message/non-message fields: // For some reason protoc generates different code for oneof message/non-message fields:
// 1. For message we have 2 level struct wrapping and setters use inner type. // 1. For message we have 2 level struct wrapping and setters use inner type.
// 2. For other types we also have 2 level wrapping, but setters use outer type. // 2. For other types we also have 2 level wrapping, but setters use outer type.
ft := fieldType(g, ff)
g.P("func (x *", msg.GoIdent.GoName, ") Get", ff.GoName, "() ", ft, " {")
g.P("if xx, ok := x.Get", ff.Oneof.GoName, "().(*", ff.GoIdent, "); ok { return xx.", ff.GoName, " }")
g.P("return ", fieldDefaultValue(ff))
g.P("}")
if ff.Desc.Kind() == protoreflect.MessageKind { if ff.Desc.Kind() == protoreflect.MessageKind {
ft := fieldType(g, ff)
g.P("func (x *", msg.GoIdent.GoName, ") Get", ff.GoName, "() ", ft, " {")
g.P("if xx, ok := x.Get", ff.Oneof.GoName, "().(*", ff.GoIdent, "); ok { return xx.", ff.GoName, " }")
g.P("return nil")
g.P("}")
g.P("func (x *", msg.GoIdent.GoName, ") Set", ff.GoName, "(v ", ft, ") {") g.P("func (x *", msg.GoIdent.GoName, ") Set", ff.GoName, "(v ", ft, ") {")
g.P("x.", ff.Oneof.GoName, " = &", ff.GoIdent, "{", ff.GoName, ": v}") g.P("x.", ff.Oneof.GoName, " = &", ff.GoIdent, "{", ff.GoName, ": v}")
g.P("}") g.P("}")
} else { } else {
g.P("func (x *", msg.GoIdent.GoName, ") Get", ff.GoName, "() *", ff.GoIdent, " {")
g.P("if xx, ok := x.Get", ff.Oneof.GoName, "().(*", ff.GoIdent, "); ok { return xx }")
g.P("return nil")
g.P("}")
g.P("func (x *", msg.GoIdent.GoName, ") Set", ff.GoName, "(v *", ff.GoIdent, ") {") g.P("func (x *", msg.GoIdent.GoName, ") Set", ff.GoName, "(v *", ff.GoIdent, ") {")
g.P("x.", ff.Oneof.GoName, " = v") g.P("x.", ff.Oneof.GoName, " = v")
g.P("}") g.P("}")