pub struct Config { /* private fields */ }
prost
only.Expand description
Configuration options for Protobuf code generation.
This configuration builder can be used to set non-default code generation options.
Implementations§
source§impl Config
impl Config
sourcepub fn btree_map<I, S>(&mut self, paths: I) -> &mut Config
pub fn btree_map<I, S>(&mut self, paths: I) -> &mut Config
Configure the code generator to generate Rust BTreeMap
fields for Protobuf
map
type fields.
§Arguments
paths
- paths to specific fields, messages, or packages which should use a Rust
BTreeMap
for Protobuf map
fields. Paths are specified in terms of the Protobuf type
name (not the generated Rust type name). Paths with a leading .
are treated as fully
qualified names. Paths without a leading .
are treated as relative, and are suffix
matched on the fully qualified field name. If a Protobuf map field matches any of the
paths, a Rust BTreeMap
field is generated instead of the default HashMap
.
The matching is done on the Protobuf names, before converting to Rust-friendly casing standards.
§Examples
// Match a specific field in a message type.
config.btree_map(&[".my_messages.MyMessageType.my_map_field"]);
// Match all map fields in a message type.
config.btree_map(&[".my_messages.MyMessageType"]);
// Match all map fields in a package.
config.btree_map(&[".my_messages"]);
// Match all map fields. Specially useful in `no_std` contexts.
config.btree_map(&["."]);
// Match all map fields in a nested message.
config.btree_map(&[".my_messages.MyMessageType.MyNestedMessageType"]);
// Match all fields named 'my_map_field'.
config.btree_map(&["my_map_field"]);
// Match all fields named 'my_map_field' in messages named 'MyMessageType', regardless of
// package or nesting.
config.btree_map(&["MyMessageType.my_map_field"]);
// Match all fields named 'my_map_field', and all fields in the 'foo.bar' package.
config.btree_map(&["my_map_field", ".foo.bar"]);
sourcepub fn bytes<I, S>(&mut self, paths: I) -> &mut Config
pub fn bytes<I, S>(&mut self, paths: I) -> &mut Config
Configure the code generator to generate Rust bytes::Bytes
fields for Protobuf
bytes
type fields.
§Arguments
paths
- paths to specific fields, messages, or packages which should use a Rust
Bytes
for Protobuf bytes
fields. Paths are specified in terms of the Protobuf type
name (not the generated Rust type name). Paths with a leading .
are treated as fully
qualified names. Paths without a leading .
are treated as relative, and are suffix
matched on the fully qualified field name. If a Protobuf map field matches any of the
paths, a Rust Bytes
field is generated instead of the default Vec<u8>
.
The matching is done on the Protobuf names, before converting to Rust-friendly casing standards.
§Examples
// Match a specific field in a message type.
config.bytes(&[".my_messages.MyMessageType.my_bytes_field"]);
// Match all bytes fields in a message type.
config.bytes(&[".my_messages.MyMessageType"]);
// Match all bytes fields in a package.
config.bytes(&[".my_messages"]);
// Match all bytes fields. Specially useful in `no_std` contexts.
config.bytes(&["."]);
// Match all bytes fields in a nested message.
config.bytes(&[".my_messages.MyMessageType.MyNestedMessageType"]);
// Match all fields named 'my_bytes_field'.
config.bytes(&["my_bytes_field"]);
// Match all fields named 'my_bytes_field' in messages named 'MyMessageType', regardless of
// package or nesting.
config.bytes(&["MyMessageType.my_bytes_field"]);
// Match all fields named 'my_bytes_field', and all fields in the 'foo.bar' package.
config.bytes(&["my_bytes_field", ".foo.bar"]);
sourcepub fn field_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
pub fn field_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
Add additional attribute to matched fields.
§Arguments
path
- a path matching any number of fields. These fields get the attribute.
For details about matching fields see btree_map
.
attribute
- an arbitrary string that’ll be placed before each matched field. The
expected usage are additional attributes, usually in concert with whole-type
attributes set with type_attribute
, but it is not
checked and anything can be put there.
Note that the calls to this method are cumulative ‒ if multiple paths from multiple calls match the same field, the field gets all the corresponding attributes.
§Examples
// Prost renames fields named `in` to `in_`. But if serialized through serde,
// they should as `in`.
config.field_attribute("in", "#[serde(rename = \"in\")]");
sourcepub fn type_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
pub fn type_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
Add additional attribute to matched messages, enums and one-ofs.
§Arguments
paths
- a path matching any number of types. It works the same way as in
btree_map
, just with the field name omitted.
attribute
- an arbitrary string to be placed before each matched type. The
expected usage are additional attributes, but anything is allowed.
The calls to this method are cumulative. They don’t overwrite previous calls and if a type is matched by multiple calls of the method, all relevant attributes are added to it.
For things like serde it might be needed to combine with field attributes.
§Examples
// Nothing around uses floats, so we can derive real `Eq` in addition to `PartialEq`.
config.type_attribute(".", "#[derive(Eq)]");
// Some messages want to be serializable with serde as well.
config.type_attribute("my_messages.MyMessageType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
config.type_attribute("my_messages.MyMessageType.MyNestedMessageType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
§Oneof fields
The oneof
fields don’t have a type name of their own inside Protobuf. Therefore, the
field name can be used both with type_attribute
and field_attribute
‒ the first is
placed before the enum
type definition, the other before the field inside corresponding
message struct
.
In other words, to place an attribute on the enum
implementing the oneof
, the match
would look like my_messages.MyMessageType.oneofname
.
sourcepub fn message_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
pub fn message_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
Add additional attribute to matched messages.
§Arguments
paths
- a path matching any number of types. It works the same way as in
btree_map
, just with the field name omitted.
attribute
- an arbitrary string to be placed before each matched type. The
expected usage are additional attributes, but anything is allowed.
The calls to this method are cumulative. They don’t overwrite previous calls and if a type is matched by multiple calls of the method, all relevant attributes are added to it.
For things like serde it might be needed to combine with field attributes.
§Examples
// Nothing around uses floats, so we can derive real `Eq` in addition to `PartialEq`.
config.message_attribute(".", "#[derive(Eq)]");
// Some messages want to be serializable with serde as well.
config.message_attribute("my_messages.MyMessageType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
config.message_attribute("my_messages.MyMessageType.MyNestedMessageType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
sourcepub fn enum_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
pub fn enum_attribute<P, A>(&mut self, path: P, attribute: A) -> &mut Config
Add additional attribute to matched enums and one-ofs.
§Arguments
paths
- a path matching any number of types. It works the same way as in
btree_map
, just with the field name omitted.
attribute
- an arbitrary string to be placed before each matched type. The
expected usage are additional attributes, but anything is allowed.
The calls to this method are cumulative. They don’t overwrite previous calls and if a type is matched by multiple calls of the method, all relevant attributes are added to it.
For things like serde it might be needed to combine with field attributes.
§Examples
// Nothing around uses floats, so we can derive real `Eq` in addition to `PartialEq`.
config.enum_attribute(".", "#[derive(Eq)]");
// Some messages want to be serializable with serde as well.
config.enum_attribute("my_messages.MyEnumType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
config.enum_attribute("my_messages.MyMessageType.MyNestedEnumType",
"#[derive(Serialize)] #[serde(rename_all = \"snake_case\")]");
§Oneof fields
The oneof
fields don’t have a type name of their own inside Protobuf. Therefore, the
field name can be used both with enum_attribute
and field_attribute
‒ the first is
placed before the enum
type definition, the other before the field inside corresponding
message struct
.
In other words, to place an attribute on the enum
implementing the oneof
, the match
would look like my_messages.MyNestedMessageType.oneofname
.
sourcepub fn service_generator(
&mut self,
service_generator: Box<dyn ServiceGenerator>,
) -> &mut Config
pub fn service_generator( &mut self, service_generator: Box<dyn ServiceGenerator>, ) -> &mut Config
Configures the code generator to use the provided service generator.
sourcepub fn compile_well_known_types(&mut self) -> &mut Config
pub fn compile_well_known_types(&mut self) -> &mut Config
Configures the code generator to not use the prost_types
crate for Protobuf well-known
types, and instead generate Protobuf well-known types from their .proto
definitions.
sourcepub fn disable_comments<I, S>(&mut self, paths: I) -> &mut Config
pub fn disable_comments<I, S>(&mut self, paths: I) -> &mut Config
Configures the code generator to omit documentation comments on generated Protobuf types.
§Example
Occasionally .proto
files contain code blocks which are not valid Rust. To avoid doctest
failures, annotate the invalid code blocks with an ignore
or no_run
attribute, or
disable doctests for the crate with a Cargo.toml entry. If neither of these options
are possible, then omit comments on generated code during doctest builds:
let mut config = prost_build::Config::new();
config.disable_comments(&["."]);
config.compile_protos(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
As with other options which take a set of paths, comments can be disabled on a per-package or per-symbol basis.
sourcepub fn skip_debug<I, S>(&mut self, paths: I) -> &mut Config
pub fn skip_debug<I, S>(&mut self, paths: I) -> &mut Config
Skips generating impl Debug
for types
sourcepub fn extern_path<P1, P2>(
&mut self,
proto_path: P1,
rust_path: P2,
) -> &mut Config
pub fn extern_path<P1, P2>( &mut self, proto_path: P1, rust_path: P2, ) -> &mut Config
Declare an externally provided Protobuf package or type.
extern_path
allows prost
types in external crates to be referenced in generated code.
When prost
compiles a .proto
which includes an import of another .proto
, it will
automatically recursively compile the imported file as well. extern_path
can be used
to instead substitute types from an external crate.
§Example
As an example, consider a crate, uuid
, with a prost
-generated Uuid
type:
// uuid.proto
syntax = "proto3";
package uuid;
message Uuid {
string uuid_str = 1;
}
The uuid
crate implements some traits for Uuid
, and publicly exports it:
// lib.rs in the uuid crate
include!(concat!(env!("OUT_DIR"), "/uuid.rs"));
pub trait DoSomething {
fn do_it(&self);
}
impl DoSomething for Uuid {
fn do_it(&self) {
println!("Done");
}
}
A separate crate, my_application
, uses prost
to generate message types which reference
Uuid
:
// my_application.proto
syntax = "proto3";
package my_application;
import "uuid.proto";
message MyMessage {
uuid.Uuid message_id = 1;
string some_payload = 2;
}
Additionally, my_application
depends on the trait impls provided by the uuid
crate:
// `main.rs` of `my_application`
use uuid::{DoSomething, Uuid};
include!(concat!(env!("OUT_DIR"), "/my_application.rs"));
pub fn process_message(msg: MyMessage) {
if let Some(uuid) = msg.message_id {
uuid.do_it();
}
}
Without configuring uuid
as an external path in my_application
’s build.rs
, prost
would compile a completely separate version of the Uuid
type, and process_message
would
fail to compile. However, if my_application
configures uuid
as an extern path with a
call to .extern_path(".uuid", "::uuid")
, prost
will use the external type instead of
compiling a new version of Uuid
. Note that the configuration could also be specified as
.extern_path(".uuid.Uuid", "::uuid::Uuid")
if only the Uuid
type were externally
provided, and not the whole uuid
package.
§Usage
extern_path
takes a fully-qualified Protobuf path, and the corresponding Rust path that
it will be substituted with in generated code. The Protobuf path can refer to a package or
a type, and the Rust path should correspondingly refer to a Rust module or type.
// Declare the `uuid` Protobuf package and all nested packages and types as externally
// provided by the `uuid` crate.
config.extern_path(".uuid", "::uuid");
// Declare the `foo.bar.baz` Protobuf package and all nested packages and types as
// externally provided by the `foo_bar_baz` crate.
config.extern_path(".foo.bar.baz", "::foo_bar_baz");
// Declare the `uuid.Uuid` Protobuf type (and all nested types) as externally provided
// by the `uuid` crate's `Uuid` type.
config.extern_path(".uuid.Uuid", "::uuid::Uuid");
sourcepub fn file_descriptor_set_path<P>(&mut self, path: P) -> &mut Config
pub fn file_descriptor_set_path<P>(&mut self, path: P) -> &mut Config
When set, the FileDescriptorSet
generated by protoc
is written to the provided
filesystem path.
This option can be used in conjunction with the include_bytes!
macro and the types in
the prost-types
crate for implementing reflection capabilities, among other things.
§Example
In build.rs
:
config.file_descriptor_set_path(
PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"))
.join("file_descriptor_set.bin"));
In lib.rs
:
let file_descriptor_set_bytes = include_bytes!(concat!(env!("OUT_DIR"), "/file_descriptor_set.bin"));
let file_descriptor_set = prost_types::FileDescriptorSet::decode(&file_descriptor_set_bytes[..]).unwrap();
sourcepub fn skip_protoc_run(&mut self) -> &mut Config
pub fn skip_protoc_run(&mut self) -> &mut Config
In combination with with file_descriptor_set_path
, this can be used to provide a file
descriptor set as an input file, rather than having prost-build generate the file by calling
protoc.
In build.rs
:
config.file_descriptor_set_path("path/from/build/system")
.skip_protoc_run()
.compile_protos(&["src/items.proto"], &["src/"]);
sourcepub fn retain_enum_prefix(&mut self) -> &mut Config
pub fn retain_enum_prefix(&mut self) -> &mut Config
Configures the code generator to not strip the enum name from variant names.
Protobuf enum definitions commonly include the enum name as a prefix of every variant name.
This style is non-idiomatic in Rust, so by default prost
strips the enum name prefix from
variants which include it. Configuring this option prevents prost
from stripping the
prefix.
sourcepub fn out_dir<P>(&mut self, path: P) -> &mut Config
pub fn out_dir<P>(&mut self, path: P) -> &mut Config
Configures the output directory where generated Rust files will be written.
If unset, defaults to the OUT_DIR
environment variable. OUT_DIR
is set by Cargo when
executing build scripts, so out_dir
typically does not need to be configured.
sourcepub fn default_package_filename<S>(&mut self, filename: S) -> &mut Config
pub fn default_package_filename<S>(&mut self, filename: S) -> &mut Config
Configures what filename protobufs with no package definition are written to.
The filename will be appended with the .rs
extension.
sourcepub fn enable_type_names(&mut self) -> &mut Config
pub fn enable_type_names(&mut self) -> &mut Config
Configures the code generator to include type names.
Message types will implement Name
trait, which provides type and package name.
This is needed for encoding messages as Any
type.
sourcepub fn type_name_domain<I, S, D>(&mut self, paths: I, domain: D) -> &mut Config
pub fn type_name_domain<I, S, D>(&mut self, paths: I, domain: D) -> &mut Config
Specify domain names to use with message type URLs.
§Domains
paths
- a path matching any number of types. It works the same way as in
btree_map
, just with the field name omitted.
domain
- an arbitrary string to be used as a prefix for type URLs.
§Examples
// Full type URL of the message `google.profile.Person`,
// will be `type.googleapis.com/google.profile.Person`.
config.type_name_domain(&["."], "type.googleapis.com");
sourcepub fn prost_path<S>(&mut self, path: S) -> &mut Config
pub fn prost_path<S>(&mut self, path: S) -> &mut Config
Configures the path that’s used for deriving Message
for generated messages.
This is mainly useful for generating crates that wish to re-export prost.
Defaults to ::prost::Message
if not specified.
sourcepub fn protoc_arg<S>(&mut self, arg: S) -> &mut Config
pub fn protoc_arg<S>(&mut self, arg: S) -> &mut Config
Add an argument to the protoc
protobuf compilation invocation.
§Example build.rs
fn main() -> Result<()> {
let mut prost_build = prost_build::Config::new();
// Enable a protoc experimental feature.
prost_build.protoc_arg("--experimental_allow_proto3_optional");
prost_build.compile_protos(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
Ok(())
}
sourcepub fn protoc_executable<S>(&mut self, executable: S) -> &mut Config
pub fn protoc_executable<S>(&mut self, executable: S) -> &mut Config
Set the path to protoc
executable to be used by prost-build
Use the provided path to find protoc
. This can either be a file name which is
searched for in the PATH
or an aboslute path to use a specific executable.
§Example build.rs
fn main() -> Result<()> {
let mut prost_build = prost_build::Config::new();
prost_build.protoc_executable("protoc-27.1");
prost_build.compile_protos(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
Ok(())
}
sourcepub fn include_file<P>(&mut self, path: P) -> &mut Config
pub fn include_file<P>(&mut self, path: P) -> &mut Config
Configures the optional module filename for easy inclusion of all generated Rust files
If set, generates a file (inside the OUT_DIR
or out_dir()
as appropriate) which contains
a set of pub mod XXX
statements combining to load all Rust files generated. This can allow
for a shortcut where multiple related proto files have been compiled together resulting in
a semi-complex set of includes.
Turning a need for:
pub mod Foo {
pub mod Bar {
include!(concat!(env!("OUT_DIR"), "/foo.bar.rs"));
}
pub mod Baz {
include!(concat!(env!("OUT_DIR"), "/foo.baz.rs"));
}
}
Into the simpler:
include!(concat!(env!("OUT_DIR"), "/_includes.rs"));
sourcepub fn format(&mut self, enabled: bool) -> &mut Config
Available on crate feature format
only.
pub fn format(&mut self, enabled: bool) -> &mut Config
format
only.Configures the code generator to format the output code via prettyplease
.
By default, this is enabled but if the format
feature is not enabled this does
nothing.
sourcepub fn compile_fds(&mut self, fds: FileDescriptorSet) -> Result<(), Error>
pub fn compile_fds(&mut self, fds: FileDescriptorSet) -> Result<(), Error>
Compile a FileDescriptorSet
into Rust files during a Cargo build with
additional code generator configuration options.
This method is like compile_protos
function except it does not invoke protoc
and instead requires the user to supply a FileDescriptorSet
.
§Example build.rs
fn main() -> std::io::Result<()> {
let file_descriptor_set = fds();
prost_build::Config::new()
.compile_fds(file_descriptor_set)
}
sourcepub fn load_fds(
&mut self,
protos: &[impl AsRef<Path>],
includes: &[impl AsRef<Path>],
) -> Result<FileDescriptorSet, Error>
pub fn load_fds( &mut self, protos: &[impl AsRef<Path>], includes: &[impl AsRef<Path>], ) -> Result<FileDescriptorSet, Error>
Loads .proto
files as a FileDescriptorSet
. This allows inspection of the descriptors
before calling Config::compile_fds
. This could be used to change Config
attributes after introspecting what is actually present in the .proto
files.
§Example build.rs
fn main() -> std::io::Result<()> {
let mut config = Config::new();
let file_descriptor_set = config.load_fds(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
// Add custom attributes to messages that are service inputs or outputs.
for file in &file_descriptor_set.file {
for service in &file.service {
for method in &service.method {
if let Some(input) = &method.input_type {
config.message_attribute(input, "#[derive(custom_proto::Input)]");
}
if let Some(output) = &method.output_type {
config.message_attribute(output, "#[derive(custom_proto::Output)]");
}
}
}
}
config.compile_fds(file_descriptor_set)
}
sourcepub fn compile_protos(
&mut self,
protos: &[impl AsRef<Path>],
includes: &[impl AsRef<Path>],
) -> Result<(), Error>
pub fn compile_protos( &mut self, protos: &[impl AsRef<Path>], includes: &[impl AsRef<Path>], ) -> Result<(), Error>
Compile .proto
files into Rust files during a Cargo build with additional code generator
configuration options.
This method is like the prost_build::compile_protos
function, with the added ability to
specify non-default code generation options. See that function for more information about
the arguments and generated outputs.
The protos
and includes
arguments are ignored if skip_protoc_run
is specified.
§Example build.rs
fn main() -> Result<()> {
let mut prost_build = prost_build::Config::new();
prost_build.btree_map(&["."]);
prost_build.compile_protos(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
Ok(())
}
sourcepub fn generate(
&mut self,
requests: Vec<(Module, FileDescriptorProto)>,
) -> Result<HashMap<Module, String>, Error>
pub fn generate( &mut self, requests: Vec<(Module, FileDescriptorProto)>, ) -> Result<HashMap<Module, String>, Error>
Processes a set of modules and file descriptors, returning a map of modules to generated code contents.
This is generally used when control over the output should not be managed by Prost,
such as in a flow for a protoc
code generating plugin. When compiling as part of a
build.rs
file, instead use Self::compile_protos()
.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Config
impl !RefUnwindSafe for Config
impl !Send for Config
impl !Sync for Config
impl Unpin for Config
impl !UnwindSafe for Config
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more