trapeze_codegen/lib.rs
1use std::io::Result;
2use std::ops::{Deref, DerefMut};
3use std::path::Path;
4
5#[doc(hidden)]
6pub mod prost_build {
7 pub use prost_build::*;
8}
9
10mod service_generator;
11
12pub use service_generator::TtrpcServiceGenerator;
13
14/// Compile `.proto` files into Rust files during a Cargo build.
15///
16/// The generated `.rs` files are written to the Cargo `OUT_DIR` directory, suitable for use with
17/// the [include!][1] macro. See the [Cargo `build.rs` code generation][2] example for more info.
18///
19/// This function should be called in a project's `build.rs`.
20///
21/// # Arguments
22///
23/// **`protos`** - Paths to `.proto` files to compile. Any transitively [imported][3] `.proto`
24/// files are automatically be included.
25///
26/// **`includes`** - Paths to directories in which to search for imports. Directories are searched
27/// in order. The `.proto` files passed in **`protos`** must be found in one of the provided
28/// include directories.
29///
30/// # Errors
31///
32/// This function can fail for a number of reasons:
33///
34/// - Failure to locate or download `protoc`.
35/// - Failure to parse the `.proto`s.
36/// - Failure to locate an imported `.proto`.
37/// - Failure to compile a `.proto` without a [package specifier][4].
38///
39/// It's expected that this function call be `unwrap`ed in a `build.rs`; there is typically no
40/// reason to gracefully recover from errors during a build.
41///
42/// # Example `build.rs`
43///
44/// ```rust,no_run
45/// # use std::io::Result;
46/// fn main() -> Result<()> {
47/// trapeze_codegen::compile_protos(&["src/frontend.proto", "src/backend.proto"], &["src"])?;
48/// Ok(())
49/// }
50/// ```
51///
52/// [1]: https://doc.rust-lang.org/std/macro.include.html
53/// [2]: http://doc.crates.io/build-script.html#case-study-code-generation
54/// [3]: https://developers.google.com/protocol-buffers/docs/proto3#importing-definitions
55/// [4]: https://developers.google.com/protocol-buffers/docs/proto#packages
56pub fn compile_protos(protos: &[impl AsRef<Path>], includes: &[impl AsRef<Path>]) -> Result<()> {
57 Config::new().compile_protos(protos, includes)
58}
59
60/// Configuration options for Protobuf code generation.
61///
62/// This configuration builder can be used to set non-default code generation options.
63pub struct Config(prost_build::Config);
64
65impl Config {
66 /// Creates a new code generator configuration with default options.
67 #[must_use]
68 pub fn new() -> Self {
69 Self::default()
70 }
71}
72
73impl Default for Config {
74 fn default() -> Self {
75 let mut cfg = prost_build::Config::new();
76 cfg.service_generator(Box::new(TtrpcServiceGenerator));
77 Self(cfg)
78 }
79}
80
81impl Deref for Config {
82 type Target = prost_build::Config;
83
84 fn deref(&self) -> &Self::Target {
85 &self.0
86 }
87}
88
89impl DerefMut for Config {
90 fn deref_mut(&mut self) -> &mut Self::Target {
91 &mut self.0
92 }
93}