acton_service/
build_utils.rs1use std::path::{Path, PathBuf};
40
41#[derive(Debug)]
43pub enum BuildError {
44 Io(std::io::Error),
45 ProtoBuild(Box<dyn std::error::Error>),
46 NoProtoFiles(PathBuf),
47 InvalidProtoDir(PathBuf),
48}
49
50impl std::fmt::Display for BuildError {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 match self {
53 BuildError::Io(e) => write!(f, "IO error: {}", e),
54 BuildError::ProtoBuild(e) => write!(f, "Proto compilation error: {}", e),
55 BuildError::NoProtoFiles(dir) => {
56 write!(f, "No .proto files found in directory: {}", dir.display())
57 }
58 BuildError::InvalidProtoDir(dir) => write!(
59 f,
60 "Proto directory does not exist or is not a directory: {}",
61 dir.display()
62 ),
63 }
64 }
65}
66
67impl std::error::Error for BuildError {}
68
69impl From<std::io::Error> for BuildError {
70 fn from(e: std::io::Error) -> Self {
71 BuildError::Io(e)
72 }
73}
74
75pub type BuildResult<T> = Result<T, BuildError>;
76
77pub fn compile_protos_from_dir<P: AsRef<Path>>(proto_dir: P) -> BuildResult<()> {
99 let proto_dir = proto_dir.as_ref();
100
101 if !proto_dir.exists() || !proto_dir.is_dir() {
103 return Err(BuildError::InvalidProtoDir(proto_dir.to_path_buf()));
104 }
105
106 let proto_files: Vec<PathBuf> = discover_proto_files(proto_dir)?;
108
109 if proto_files.is_empty() {
110 return Err(BuildError::NoProtoFiles(proto_dir.to_path_buf()));
111 }
112
113 let out_dir = std::env::var("OUT_DIR").map_err(|e| {
115 BuildError::ProtoBuild(Box::new(std::io::Error::new(
116 std::io::ErrorKind::NotFound,
117 format!("OUT_DIR not set: {}", e),
118 )))
119 })?;
120
121 let pkg_name = std::env::var("CARGO_PKG_NAME")
122 .map_err(|e| {
123 BuildError::ProtoBuild(Box::new(std::io::Error::new(
124 std::io::ErrorKind::NotFound,
125 format!("CARGO_PKG_NAME not set: {}", e),
126 )))
127 })?
128 .replace('-', "_");
129
130 let descriptor_path = format!("{}/{}_descriptor.bin", out_dir, pkg_name);
132
133 println!(
134 "cargo:warning=Compiling {} proto files from {}",
135 proto_files.len(),
136 proto_dir.display()
137 );
138 for proto_file in &proto_files {
139 println!("cargo:warning= - {}", proto_file.display());
140 }
141
142 compile_protos_with_descriptor(&proto_files, proto_dir, &descriptor_path)?;
144
145 println!("cargo:warning=Generated descriptor: {}", descriptor_path);
146
147 Ok(())
148}
149
150pub fn compile_service_protos() -> BuildResult<()> {
173 let proto_dir = std::env::var("ACTON_PROTO_DIR").unwrap_or_else(|_| "proto".to_string());
174
175 println!("cargo:warning=Using proto directory: {}", proto_dir);
176
177 compile_protos_from_dir(proto_dir)
178}
179
180fn discover_proto_files(dir: &Path) -> BuildResult<Vec<PathBuf>> {
182 let mut proto_files = Vec::new();
183
184 for entry in std::fs::read_dir(dir)? {
185 let entry = entry?;
186 let path = entry.path();
187
188 if path.is_file() {
189 if let Some(ext) = path.extension() {
190 if ext == "proto" {
191 proto_files.push(path);
192 }
193 }
194 } else if path.is_dir() {
195 proto_files.extend(discover_proto_files(&path)?);
197 }
198 }
199
200 proto_files.sort();
202
203 Ok(proto_files)
204}
205
206fn compile_protos_with_descriptor(
208 proto_files: &[PathBuf],
209 proto_include_dir: &Path,
210 descriptor_path: &str,
211) -> BuildResult<()> {
212 let proto_paths: Vec<&str> = proto_files
214 .iter()
215 .map(|p| p.to_str().expect("Invalid UTF-8 in proto path"))
216 .collect();
217
218 let include_dirs = vec![proto_include_dir
219 .to_str()
220 .expect("Invalid UTF-8 in include path")];
221
222 #[cfg(feature = "grpc")]
224 {
225 tonic_prost_build::configure()
226 .file_descriptor_set_path(descriptor_path)
227 .compile_protos(&proto_paths, &include_dirs)
228 .map_err(|e| BuildError::ProtoBuild(Box::new(e)))?;
229 Ok(())
230 }
231
232 #[cfg(not(feature = "grpc"))]
233 {
234 let _ = (proto_paths, include_dirs, descriptor_path);
235 Err(BuildError::ProtoBuild(Box::new(std::io::Error::other(
236 "grpc feature not enabled",
237 ))))
238 }
239}
240
241pub fn compile_specific_protos<P: AsRef<Path>>(
259 proto_files: &[P],
260 include_dirs: &[P],
261 descriptor_name: &str,
262) -> BuildResult<()> {
263 let out_dir = std::env::var("OUT_DIR").map_err(|e| {
264 BuildError::ProtoBuild(Box::new(std::io::Error::new(
265 std::io::ErrorKind::NotFound,
266 format!("OUT_DIR not set: {}", e),
267 )))
268 })?;
269
270 let descriptor_path = format!("{}/{}", out_dir, descriptor_name);
271
272 let proto_paths: Vec<&str> = proto_files
273 .iter()
274 .map(|p| p.as_ref().to_str().expect("Invalid UTF-8 in proto path"))
275 .collect();
276
277 let include_paths: Vec<&str> = include_dirs
278 .iter()
279 .map(|p| p.as_ref().to_str().expect("Invalid UTF-8 in include path"))
280 .collect();
281
282 compile_protos_with_descriptor(
283 &proto_paths.iter().map(PathBuf::from).collect::<Vec<_>>(),
284 Path::new(include_paths[0]),
285 &descriptor_path,
286 )?;
287
288 Ok(())
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn test_discover_proto_files() {
297 let _result: BuildResult<Vec<PathBuf>> = discover_proto_files(Path::new("nonexistent"));
300 }
301}