bufbuild / buf

The best way of working with Protocol Buffers.
https://buf.build
Apache License 2.0
9.16k stars 278 forks source link

[Rust] required fields results in `Option<T>`, and non-required fields result in `T` #3437

Closed MEnnabah closed 2 weeks ago

MEnnabah commented 2 weeks ago

GitHub repository with your minimal reproducible example (do not leave this field blank or fill out this field with "github.com/bufbuild/buf" or we will automatically close your issue, see the instructions above!)

N/A

Commands

cargo add --registry buf authzed_api_community_neoeinstein-prost

Output

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SubjectReference {
    #[prost(message, optional, tag="1")]
    pub object: ::core::option::Option<ObjectReference>,
    #[prost(string, tag="2")]
    pub optional_relation: ::prost::alloc::string::String,
}

Expected Output

Since SubjectReference is defined as follows:

message SubjectReference {
  ObjectReference object = 1 [ (validate.rules).message.required = true ];
  string optional_relation = 2 [ (validate.rules).string = {
    pattern : "^([a-z][a-z0-9_]{1,62}[a-z0-9])?$",
    max_bytes : 64,
  } ];
}

I expected the output to:

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SubjectReference {
    #[prost(message, optional, tag="1")]
    pub object: ObjectReference,
    #[prost(string, tag="2")]
    pub optional_relation: ::core::option::Option<::prost::alloc::string::String>,
}

Anything else?

Notice: in .proto file, the filed object was marked as required, and the field optional_relation is not marked as required. I expect the output to use Rust Option to match with the proto schema.

stefanvanburen commented 2 weeks ago

hey @MEnnabah, a couple things:

To start off with, those validate.rules options look to be protoc-gen-validate options, which have no impact on the generated code (besides generating Validate methods for supported languages, which currently does not include Rust).

The generated code is all coming from the prost code generator, wrapped by the protoc-gen-prost protobuf plugin. You may want to read this issue and the linked issues from the second comment, which discuss this representation in prost. The place to change the generated code would be within prost.

Unfortunately there's not much to be done on the buf side here, as the Cargo Registry is wrapping the underlying plugin / code generator, so I'm going to close this out.