msggen: Support enums in requests too

They are sent as i32 over protobuf, so we need to convert them into
their enum representation.
This commit is contained in:
Christian Decker 2022-01-27 14:08:26 +01:00
parent 494243d41c
commit efed7d8617
2 changed files with 24 additions and 2 deletions

View File

@ -279,8 +279,11 @@ class GrpcUnconverterGenerator(GrpcConverterGenerator):
self.write(f"{name}: c.{name}.iter().map(|s| s.into()).collect(),\n", numindent=3)
elif isinstance(f, EnumField):
raise ValueError("enums from i32 are not implemented yet")
if f.required:
self.write(f"{name}: c.{name}.into(),\n", numindent=3)
else:
self.write(f"{name}: c.{name}.map(|v| v.try_into().unwrap()),\n", numindent=3)
pass
elif isinstance(f, PrimitiveField):
typ = f.typename + ("?" if not f.required else "")
# We may need to reduce or increase the size of some

View File

@ -87,6 +87,25 @@ def gen_enum(e):
decl += f" {norm},\n"
decl += "}\n\n"
# Implement From<i32> so we can convert from the numerical
# representation
decl += dedent(f"""\
impl TryFrom<i32> for {e.typename} {{
type Error = anyhow::Error;
fn try_from(c: i32) -> Result<{e.typename}, anyhow::Error> {{
match c {{
""")
for i, v in enumerate(e.variants):
norm = v.normalized()
# decl += f" #[serde(rename = \"{v}\")]\n"
decl += f" {i} => Ok({e.typename}::{norm}),\n"
decl += dedent(f"""\
o => Err(anyhow::anyhow!("Unknown variant {{}} for enum {e.typename}", o)),
}}
}}
}}
""")
typename = e.typename
if e.path in overrides: