xref: /tonic/codegen/src/main.rs (revision d59fe0da)
1 use std::path::PathBuf;
2 
3 fn main() {
4     // tonic-health
5     codegen(
6         &PathBuf::from(std::env!("CARGO_MANIFEST_DIR"))
7             .parent()
8             .unwrap()
9             .join("tonic-health"),
10         &["proto/health.proto"],
11         &["proto"],
12         &PathBuf::from("src/generated"),
13         &PathBuf::from("src/generated/grpc_health_v1.bin"),
14         true,
15         true,
16     );
17 
18     // tonic-reflection
19     codegen(
20         &PathBuf::from(std::env!("CARGO_MANIFEST_DIR"))
21             .parent()
22             .unwrap()
23             .join("tonic-reflection"),
24         &["proto/reflection.proto"],
25         &["proto"],
26         &PathBuf::from("src/generated"),
27         &PathBuf::from("src/generated/reflection_v1alpha1.bin"),
28         true,
29         true,
30     );
31 
32     // tonic-types
33     codegen(
34         &PathBuf::from(std::env!("CARGO_MANIFEST_DIR"))
35             .parent()
36             .unwrap()
37             .join("tonic-types"),
38         &["proto/status.proto", "proto/error_details.proto"],
39         &["proto"],
40         &PathBuf::from("src/generated"),
41         &PathBuf::from("src/generated/types.bin"),
42         false,
43         false,
44     );
45 }
46 
47 fn codegen(
48     root_dir: &PathBuf,
49     iface_files: &[&str],
50     include_dirs: &[&str],
51     out_dir: &PathBuf,
52     file_descriptor_set_path: &PathBuf,
53     build_client: bool,
54     build_server: bool,
55 ) {
56     let tempdir = tempfile::Builder::new()
57         .prefix("tonic-codegen-")
58         .tempdir()
59         .unwrap();
60 
61     let iface_files: Vec<PathBuf> = iface_files
62         .into_iter()
63         .map(|&path| root_dir.join(path))
64         .collect();
65 
66     let include_dirs: Vec<PathBuf> = include_dirs
67         .into_iter()
68         .map(|&path| root_dir.join(path))
69         .collect();
70     let out_dir = root_dir.join(out_dir);
71     let file_descriptor_set_path = root_dir.join(file_descriptor_set_path);
72 
73     tonic_build::configure()
74         .build_client(build_client)
75         .build_server(build_server)
76         .out_dir(&tempdir)
77         .file_descriptor_set_path(file_descriptor_set_path)
78         .compile(&iface_files, &include_dirs)
79         .unwrap();
80 
81     for path in std::fs::read_dir(tempdir.path()).unwrap() {
82         let path = path.unwrap().path();
83         let to = out_dir.join(
84             path.file_name()
85                 .unwrap()
86                 .to_str()
87                 .unwrap()
88                 .strip_suffix(".rs")
89                 .unwrap()
90                 .replace('.', "_")
91                 + ".rs",
92         );
93         std::fs::copy(&path, &to).unwrap();
94     }
95 }
96