Skip to main content

generate_protos

Function generate_protos 

Source
pub fn generate_protos(config: Config) -> Result<(), Box<dyn Error>>
Expand description

Compile the bundled .proto definitions and write a proto.rs into your crate’s OUT_DIR.

Call this from your own build.rs to generate Rust types for all Controls gRPC services. The .proto files are shipped with this library, so you do not need to vendor them yourself.

§Setup

Add rust-grpc-lib with the build feature to your build dependencies:

[build-dependencies]
rust-grpc-lib = { git = "https://github.com/fermi-ad/rust-grpc-lib", tag = "vX.Y.Z", features = ["build"] }

Then create a build.rs at the root of your crate:

ⓘ
use rust_grpc_lib::build_support::{ Config, generate_protos };

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Config::new();
    // ... configure custom attributes for the generated code here
    // e.g., config = config.type_attribute(".some.package", "#[derive(my_custom_attr)]");
    generate_protos(config)?;
    Ok(())
}

§Using the generated types

The function writes a single file, proto.rs, into the directory given by the OUT_DIR environment variable (set automatically by Cargo). Include it wherever you want the generated module to live:

ⓘ
// src/proto.rs  — or inline in src/lib.rs
include!(concat!(env!("OUT_DIR"), "/proto.rs"));

After that, all generated message types and service clients are accessible through that module:

ⓘ
mod proto {
    include!(concat!(env!("OUT_DIR"), "/proto.rs"));
}

use proto::services::alarm_commands::alarm_commands_client::AlarmCommandsClient;

§Customizing generated attributes

The provided Config struct exposes functions to add custom attributes to the generated code.

Example — add serde derives to every type in the common.alarm package:

ⓘ
let mut config = Config::new();
config = config.type_attribute(".common.alarm", "#[derive(serde::Serialize, serde::Deserialize)]");

§Safety note

This function calls std::env::set_var to point PROTOC at the vendored protoc binary. That call is only safe when no other threads are reading the environment concurrently. Cargo runs build.rs in a single-threaded process, so this is safe in normal usage. Do not call this function from a multi-threaded context.

§Errors

Returns an error if:

  • the bundled .proto files cannot be read,
  • tonic-prost-build fails to compile the protos, or
  • OUT_DIR is not set (i.e. the function is called outside of a build script)