tonic/
macros.rs

1/// Include generated proto server and client items.
2///
3/// You must specify the gRPC package name.
4///
5/// ```rust,ignore
6/// mod pb {
7///     tonic::include_proto!("helloworld");
8/// }
9/// ```
10///
11/// # Note:
12/// **This only works if the tonic-build output directory has been unmodified**.
13/// The default output directory is set to the [`OUT_DIR`] environment variable.
14/// If the output directory has been modified, the following pattern may be used
15/// instead of this macro.
16///
17/// ```rust,ignore
18/// mod pb {
19///     include!("/relative/protobuf/directory/helloworld.rs");
20/// }
21/// ```
22/// You can also use a custom environment variable using the following pattern.
23/// ```rust,ignore
24/// mod pb {
25///     include!(concat!(env!("PROTOBUFS"), "/helloworld.rs"));
26/// }
27/// ```
28///
29/// [`OUT_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
30#[macro_export]
31macro_rules! include_proto {
32    ($package: tt) => {
33        include!(concat!(env!("OUT_DIR"), concat!("/", $package, ".rs")));
34    };
35}
36
37/// Include an encoded `prost_types::FileDescriptorSet` as a `&'static [u8]`. The parameter must be
38/// the stem of the filename passed to `file_descriptor_set_path` for the `tonic-build::Builder`,
39/// excluding the `.bin` extension.
40///
41/// For example, a file descriptor set compiled like this in `build.rs`:
42///
43/// ```rust,ignore
44/// let descriptor_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("my_descriptor.bin")
45/// tonic_build::configure()
46///     .file_descriptor_set_path(&descriptor_path)
47///     .format(true)
48///     .compile(&["proto/reflection.proto"], &["proto/"])?;
49/// ```
50///
51/// Can be included like this:
52///
53/// ```rust,ignore
54/// mod pb {
55///     pub(crate) const FILE_DESCRIPTOR_SET: &[u8] = tonic::include_file_descriptor_set!("my_descriptor");
56/// }
57/// ```
58///
59/// # Note:
60/// **This only works if the tonic-build output directory has been unmodified**.
61/// The default output directory is set to the [`OUT_DIR`] environment variable.
62/// If the output directory has been modified, the following pattern may be used
63/// instead of this macro.
64///
65/// ```rust,ignore
66/// mod pb {
67///     pub(crate) const FILE_DESCRIPTOR_SET: &[u8] = include_bytes!("/relative/protobuf/directory/descriptor_name.bin");
68/// }
69/// ```
70///
71/// [`OUT_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
72#[macro_export]
73macro_rules! include_file_descriptor_set {
74    ($package: tt) => {
75        include_bytes!(concat!(env!("OUT_DIR"), concat!("/", $package, ".bin")))
76    };
77}