xref: /tonic/tonic/src/macros.rs (revision a30f4c1e)
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]
31 macro_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 ///     .compile_protos(&["proto/reflection.proto"], &["proto/"])?;
48 /// ```
49 ///
50 /// Can be included like this:
51 ///
52 /// ```rust,ignore
53 /// mod pb {
54 ///     pub(crate) const FILE_DESCRIPTOR_SET: &[u8] = tonic::include_file_descriptor_set!("my_descriptor");
55 /// }
56 /// ```
57 ///
58 /// # Note:
59 /// **This only works if the tonic-build output directory has been unmodified**.
60 /// The default output directory is set to the [`OUT_DIR`] environment variable.
61 /// If the output directory has been modified, the following pattern may be used
62 /// instead of this macro.
63 ///
64 /// ```rust,ignore
65 /// mod pb {
66 ///     pub(crate) const FILE_DESCRIPTOR_SET: &[u8] = include_bytes!("/relative/protobuf/directory/descriptor_name.bin");
67 /// }
68 /// ```
69 ///
70 /// [`OUT_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
71 #[macro_export]
72 macro_rules! include_file_descriptor_set {
73     ($package: tt) => {
74         include_bytes!(concat!(env!("OUT_DIR"), concat!("/", $package, ".bin")))
75     };
76 }
77