1#![deny(missing_docs)]
2
3use std::collections::{BTreeMap, BTreeSet};
29use std::env;
30use std::fmt::{self, Write as _};
31use std::fs;
32use std::path::{Component, Path, PathBuf};
33
34use protox::prost::Message as _;
35
36pub const DEFAULT_INCLUDE_FILE: &str = "prost_include.rs";
38
39#[derive(Debug)]
41#[non_exhaustive]
42pub enum Error {
43 Io {
45 path: Option<PathBuf>,
47 source: std::io::Error,
49 },
50 MissingOutDir,
52 NoProtoFiles(PathBuf),
54 SymlinkRefused(PathBuf),
56 InvalidIncludeFile(PathBuf),
58 Protox(protox::Error),
60 Prost(std::io::Error),
62 #[cfg(feature = "pbjson")]
64 Pbjson(std::io::Error),
65}
66
67impl fmt::Display for Error {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 match self {
70 Self::Io {
71 path: Some(path),
72 source,
73 } => write!(f, "I/O error at {}: {source}", path.display()),
74 Self::Io { path: None, source } => write!(f, "I/O error: {source}"),
75 Self::MissingOutDir => write!(
76 f,
77 "OUT_DIR is not set; invoke from a Cargo build script or call Config::out_dir"
78 ),
79 Self::NoProtoFiles(dir) => {
80 write!(f, "no `.proto` files found under {}", dir.display())
81 }
82 Self::SymlinkRefused(path) => {
83 write!(f, "refusing to follow symlink {}", path.display())
84 }
85 Self::InvalidIncludeFile(path) => write!(
86 f,
87 "include_file `{}` must be a single plain filename inside out_dir",
88 path.display()
89 ),
90 Self::Protox(err) => write!(f, "protox failed to compile protobuf schema: {err}"),
91 Self::Prost(err) => write!(f, "prost-build failed: {err}"),
92 #[cfg(feature = "pbjson")]
93 Self::Pbjson(err) => write!(f, "pbjson-build failed: {err}"),
94 }
95 }
96}
97
98impl std::error::Error for Error {
99 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
100 match self {
101 Self::Io { source, .. } | Self::Prost(source) => Some(source),
102 Self::Protox(err) => Some(err),
103 #[cfg(feature = "pbjson")]
104 Self::Pbjson(err) => Some(err),
105 Self::MissingOutDir
106 | Self::NoProtoFiles(_)
107 | Self::SymlinkRefused(_)
108 | Self::InvalidIncludeFile(_) => None,
109 }
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
115#[non_exhaustive]
116pub struct BuildOutput {
117 pub proto_files: Vec<PathBuf>,
119 pub out_dir: PathBuf,
121 pub include_file: Option<PathBuf>,
123 pub has_dependencies: bool,
125 pub rerun_directives: Vec<String>,
128}
129
130pub struct Config {
132 prost: prost_build::Config,
133 out_dir: Option<PathBuf>,
134 include_file: Option<PathBuf>,
135 file_descriptor_set_path: Option<PathBuf>,
136 emit_rerun_if_changed: bool,
137 #[cfg(feature = "pbjson")]
138 pbjson: bool,
139 #[cfg(feature = "pbjson")]
140 pbjson_builder: pbjson_build::Builder,
141}
142
143impl fmt::Debug for Config {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 let mut s = f.debug_struct("Config");
146 s.field("prost", &self.prost)
147 .field("out_dir", &self.out_dir)
148 .field("include_file", &self.include_file)
149 .field("file_descriptor_set_path", &self.file_descriptor_set_path)
150 .field("emit_rerun_if_changed", &self.emit_rerun_if_changed);
151 #[cfg(feature = "pbjson")]
152 s.field("pbjson", &self.pbjson);
153 s.finish_non_exhaustive()
154 }
155}
156
157impl Default for Config {
158 fn default() -> Self {
159 Self::new()
160 }
161}
162
163impl Config {
164 #[must_use]
167 pub fn new() -> Self {
168 Self {
169 prost: prost_build::Config::new(),
170 out_dir: None,
171 include_file: Some(PathBuf::from(DEFAULT_INCLUDE_FILE)),
172 file_descriptor_set_path: None,
173 emit_rerun_if_changed: true,
174 #[cfg(feature = "pbjson")]
175 pbjson: false,
176 #[cfg(feature = "pbjson")]
177 pbjson_builder: pbjson_build::Builder::new(),
178 }
179 }
180
181 #[must_use]
183 pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
184 self.out_dir = Some(dir.into());
185 self
186 }
187
188 #[must_use]
193 pub fn include_file(mut self, name: impl Into<PathBuf>) -> Self {
194 self.include_file = Some(name.into());
195 self
196 }
197
198 #[must_use]
200 pub fn no_include_file(mut self) -> Self {
201 self.include_file = None;
202 self
203 }
204
205 #[must_use]
207 pub fn file_descriptor_set_path(mut self, path: impl Into<PathBuf>) -> Self {
208 self.file_descriptor_set_path = Some(path.into());
209 self
210 }
211
212 #[must_use]
214 pub const fn emit_rerun_if_changed(mut self, enabled: bool) -> Self {
215 self.emit_rerun_if_changed = enabled;
216 self
217 }
218
219 pub fn prost_config(&mut self) -> &mut prost_build::Config {
224 &mut self.prost
225 }
226
227 #[must_use]
232 pub fn with_prost_config(mut self, configure: impl FnOnce(&mut prost_build::Config)) -> Self {
233 configure(&mut self.prost);
234 self
235 }
236
237 #[cfg(feature = "pbjson")]
242 #[must_use]
243 pub const fn pbjson(mut self, enabled: bool) -> Self {
244 self.pbjson = enabled;
245 self
246 }
247
248 #[cfg(feature = "pbjson")]
254 pub fn pbjson_builder(&mut self) -> &mut pbjson_build::Builder {
255 &mut self.pbjson_builder
256 }
257
258 #[cfg(feature = "pbjson")]
261 #[must_use]
262 pub fn with_pbjson_builder(
263 mut self,
264 configure: impl FnOnce(&mut pbjson_build::Builder),
265 ) -> Self {
266 self.pbjson = true;
267 configure(&mut self.pbjson_builder);
268 self
269 }
270
271 #[allow(clippy::too_many_lines)]
279 pub fn compile_protos(mut self, proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
280 let proto_dir = proto_dir.as_ref();
281 if let Some(include_name) = &self.include_file {
282 validate_include_file_name(include_name)?;
283 }
284
285 let (proto_files, visited_dirs) = discover_protos_and_dirs(proto_dir)?;
286 let out_dir = match self.out_dir {
287 Some(dir) => dir,
288 None => PathBuf::from(env::var_os("OUT_DIR").ok_or(Error::MissingOutDir)?),
289 };
290 fs::create_dir_all(&out_dir).map_err(|source| Error::Io {
291 path: Some(out_dir.clone()),
292 source,
293 })?;
294
295 let mut rerun_directives = Vec::with_capacity(visited_dirs.len() + proto_files.len());
296 for dir in &visited_dirs {
297 rerun_directives.push(format!("cargo:rerun-if-changed={}", dir.display()));
298 }
299 for file in &proto_files {
300 rerun_directives.push(format!("cargo:rerun-if-changed={}", file.display()));
301 }
302 if self.emit_rerun_if_changed {
303 for directive in &rerun_directives {
304 println!("{directive}");
305 }
306 }
307
308 let descriptors = protox::compile(&proto_files, [proto_dir]).map_err(Error::Protox)?;
309 let encoded_descriptors = descriptors.encode_to_vec();
310 if let Some(fds_path) = &self.file_descriptor_set_path {
311 if let Some(parent) = fds_path.parent()
312 && !parent.as_os_str().is_empty()
313 {
314 fs::create_dir_all(parent).map_err(|source| Error::Io {
315 path: Some(parent.to_path_buf()),
316 source,
317 })?;
318 }
319 write_if_changed(fds_path, &encoded_descriptors)?;
320 }
321
322 let discovered_rel_files: BTreeSet<String> = proto_files
323 .iter()
324 .map(|path| rel_proto_path(proto_dir, path))
325 .collect();
326 let has_dependencies = proto_files
327 .iter()
328 .any(|path| !is_root_major_proto(proto_dir, path));
329 let package_by_file: BTreeMap<String, String> = descriptors
330 .file
331 .iter()
332 .filter_map(|file| {
333 let name = file.name.as_deref()?;
334 if !discovered_rel_files.contains(name) {
335 return None;
336 }
337 let pkg = file.package.as_deref().unwrap_or_default();
338 Some((name.to_string(), pkg.to_string()))
339 })
340 .collect();
341
342 #[cfg(feature = "pbjson")]
343 let pbjson_enabled = self.pbjson;
344 #[cfg(not(feature = "pbjson"))]
345 let pbjson_enabled = false;
346
347 #[cfg(feature = "pbjson")]
348 if pbjson_enabled {
349 for file in &descriptors.file {
350 if file.package.as_deref().is_none_or(str::is_empty) {
351 let name = file.name.as_deref().unwrap_or("<unnamed>");
352 return Err(Error::Pbjson(std::io::Error::new(
353 std::io::ErrorKind::InvalidInput,
354 format!(
355 "protobuf file `{name}` has no `package` declaration, which is \
356 required when `pbjson` is enabled"
357 ),
358 )));
359 }
360 }
361 }
362
363 #[cfg(feature = "pbjson")]
364 let pbjson_prefixes = collect_pbjson_prefixes(&package_by_file);
365
366 self.prost.out_dir(&out_dir);
367 let include_path = self.include_file.as_ref().map(|name| out_dir.join(name));
368 let raw_prost_include = if let Some(include_name) = &self.include_file {
369 if !has_dependencies || pbjson_enabled {
370 let scratch_name =
371 PathBuf::from(format!(".{}.prost", include_name.to_string_lossy()));
372 self.prost.include_file(&scratch_name);
373 Some(out_dir.join(scratch_name))
374 } else {
375 self.prost.include_file(include_name);
376 None
377 }
378 } else {
379 None
380 };
381 let _raw_include_cleanup = TempFileGuard(raw_prost_include.clone());
382
383 self.prost.compile_fds(descriptors).map_err(Error::Prost)?;
384
385 #[cfg(feature = "pbjson")]
386 let serde_by_pkg: BTreeMap<String, String> = if pbjson_enabled {
387 let prefix_refs: Vec<&str> = pbjson_prefixes.iter().map(String::as_str).collect();
388 let generated = self
389 .pbjson_builder
390 .register_descriptors(&encoded_descriptors)
391 .map_err(Error::Pbjson)?
392 .generate(&prefix_refs, |_| Ok(Vec::<u8>::new()))
393 .map_err(Error::Pbjson)?;
394 let mut emitted_by_pkg = BTreeMap::new();
395 let mut written_files = BTreeSet::new();
396 for (package, bytes) in generated {
397 let raw_pkg = package
398 .path()
399 .iter()
400 .map(ToString::to_string)
401 .collect::<Vec<_>>()
402 .join(".");
403 let serde_name = format!("{package}.serde.rs");
404 write_if_changed(&out_dir.join(&serde_name), &bytes)?;
405 written_files.insert(serde_name.clone());
406 emitted_by_pkg.insert(raw_pkg, serde_name);
407 }
408 for pkg in package_by_file.values() {
409 if !emitted_by_pkg.contains_key(pkg) {
410 for candidate in pbjson_candidate_file_names(pkg) {
411 if !written_files.contains(&candidate) {
412 let stale = out_dir.join(&candidate);
413 if stale.is_file() {
414 let _ = fs::remove_file(stale);
415 }
416 }
417 }
418 }
419 }
420 emitted_by_pkg
421 } else {
422 BTreeMap::new()
423 };
424
425 if let Some(include_path) = &include_path {
426 if has_dependencies {
427 #[cfg(feature = "pbjson")]
428 if pbjson_enabled && let Some(raw_path) = &raw_prost_include {
429 let spliced =
430 splice_pbjson_includes(raw_path, &package_by_file, &serde_by_pkg)?;
431 write_if_changed(include_path, spliced.as_bytes())?;
432 }
433 #[cfg(not(feature = "pbjson"))]
434 let _ = raw_prost_include;
435 } else {
436 let (emitted_prost_files, root_level_file) = raw_prost_include
437 .as_deref()
438 .map(extract_prost_include_files)
439 .transpose()?
440 .unwrap_or_default();
441 write_standalone_include(
442 &proto_files,
443 proto_dir,
444 &package_by_file,
445 &out_dir,
446 &emitted_prost_files,
447 root_level_file.as_deref(),
448 include_path,
449 #[cfg(feature = "pbjson")]
450 &serde_by_pkg,
451 pbjson_enabled,
452 )?;
453 }
454 }
455
456 Ok(BuildOutput {
457 proto_files,
458 out_dir,
459 include_file: include_path,
460 has_dependencies,
461 rerun_directives,
462 })
463 }
464}
465
466pub fn discover_protos(proto_dir: impl AsRef<Path>) -> Result<Vec<PathBuf>, Error> {
474 let (files, _) = discover_protos_and_dirs(proto_dir.as_ref())?;
475 Ok(files)
476}
477
478pub fn compile_protos(proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
484 Config::new().compile_protos(proto_dir)
485}
486
487struct TempFileGuard(Option<PathBuf>);
488
489impl Drop for TempFileGuard {
490 fn drop(&mut self) {
491 if let Some(path) = &self.0 {
492 let _ = fs::remove_file(path);
493 }
494 }
495}
496
497fn validate_include_file_name(name: &Path) -> Result<(), Error> {
498 if name.as_os_str().as_encoded_bytes().contains(&b'\\') {
499 return Err(Error::InvalidIncludeFile(name.to_path_buf()));
500 }
501 let mut components = name.components();
502 match (components.next(), components.next()) {
503 (Some(Component::Normal(part)), None) if !part.is_empty() && name.as_os_str() == part => {
504 Ok(())
505 }
506 _ => Err(Error::InvalidIncludeFile(name.to_path_buf())),
507 }
508}
509
510fn discover_protos_and_dirs(proto_dir: &Path) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Error> {
511 let normalized_root: PathBuf = proto_dir.components().collect();
512 let root_meta = fs::symlink_metadata(&normalized_root).map_err(|source| Error::Io {
513 path: Some(proto_dir.to_path_buf()),
514 source,
515 })?;
516 if root_meta.file_type().is_symlink() {
517 return Err(Error::SymlinkRefused(proto_dir.to_path_buf()));
518 }
519
520 let mut files = Vec::new();
521 let mut dirs = vec![proto_dir.to_path_buf()];
522 collect_protos_recursive(proto_dir, &mut files, &mut dirs)?;
523 files.sort();
524 dirs.sort();
525 if files.is_empty() {
526 return Err(Error::NoProtoFiles(proto_dir.to_path_buf()));
527 }
528 Ok((files, dirs))
529}
530
531fn collect_protos_recursive(
532 dir: &Path,
533 out_files: &mut Vec<PathBuf>,
534 out_dirs: &mut Vec<PathBuf>,
535) -> Result<(), Error> {
536 let mut entries: Vec<PathBuf> = fs::read_dir(dir)
537 .map_err(|source| Error::Io {
538 path: Some(dir.to_path_buf()),
539 source,
540 })?
541 .map(|entry| {
542 entry.map(|item| item.path()).map_err(|source| Error::Io {
543 path: Some(dir.to_path_buf()),
544 source,
545 })
546 })
547 .collect::<Result<Vec<_>, _>>()?;
548 entries.sort();
549
550 for path in entries {
551 let meta = fs::symlink_metadata(&path).map_err(|source| Error::Io {
552 path: Some(path.clone()),
553 source,
554 })?;
555 if meta.file_type().is_symlink() {
556 return Err(Error::SymlinkRefused(path));
557 }
558 if meta.is_dir() {
559 out_dirs.push(path.clone());
560 collect_protos_recursive(&path, out_files, out_dirs)?;
561 } else if meta.is_file()
562 && path
563 .extension()
564 .and_then(std::ffi::OsStr::to_str)
565 .is_some_and(|ext| ext.eq_ignore_ascii_case("proto"))
566 {
567 out_files.push(path);
568 }
569 }
570 Ok(())
571}
572
573fn is_root_major_proto(proto_dir: &Path, path: &Path) -> bool {
575 let Ok(rel) = path.strip_prefix(proto_dir) else {
576 return false;
577 };
578 if rel.components().count() != 1 {
579 return false;
580 }
581 let Some(name) = rel.file_name().and_then(std::ffi::OsStr::to_str) else {
582 return false;
583 };
584 parse_root_major(name).is_some()
585}
586
587fn parse_root_major(file_name: &str) -> Option<u64> {
588 let dot = file_name.rfind('.')?;
589 if !file_name[dot + 1..].eq_ignore_ascii_case("proto") {
590 return None;
591 }
592 let stem = &file_name[..dot];
593 let digits = stem.strip_prefix('v')?;
594 if digits.is_empty()
595 || !digits.bytes().all(|b| b.is_ascii_digit())
596 || (digits.len() > 1 && digits.starts_with('0'))
597 {
598 return None;
599 }
600 digits.parse().ok()
601}
602
603fn prost_file_name(pkg: &str) -> String {
604 prost_build::Module::from_protobuf_package_name(pkg).to_file_name_or("_")
605}
606
607#[cfg(feature = "pbjson")]
608fn pbjson_candidate_file_names(pkg: &str) -> Vec<String> {
609 let module = prost_build::Module::from_protobuf_package_name(pkg);
610 let prost_stem = if module.is_empty() {
611 "_".to_string()
612 } else {
613 module.parts().collect::<Vec<_>>().join(".")
614 };
615 let primary = format!("{prost_stem}.serde.rs");
616 let compat_stem = module
617 .parts()
618 .map(|part| match part {
619 "r#gen" => "gen",
620 "__" => "_",
621 other => other,
622 })
623 .collect::<Vec<_>>()
624 .join(".");
625 let fallback = format!("{compat_stem}.serde.rs");
626 if fallback == primary {
627 vec![primary]
628 } else {
629 vec![primary, fallback]
630 }
631}
632
633#[cfg(feature = "pbjson")]
634fn collect_pbjson_prefixes(package_by_file: &BTreeMap<String, String>) -> BTreeSet<String> {
635 let mut prefixes = BTreeSet::new();
636 for pkg in package_by_file.values() {
637 if !pkg.is_empty() {
638 prefixes.insert(format!(".{pkg}"));
639 }
640 }
641 prefixes
642}
643
644fn rel_proto_path(proto_dir: &Path, path: &Path) -> String {
645 path.strip_prefix(proto_dir)
646 .unwrap_or(path)
647 .components()
648 .filter_map(|component| match component {
649 Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
650 _ => None,
651 })
652 .collect::<Vec<_>>()
653 .join("/")
654}
655
656fn extract_prost_include_files(
657 raw_include_path: &Path,
658) -> Result<(BTreeSet<String>, Option<String>), Error> {
659 let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
660 path: Some(raw_include_path.to_path_buf()),
661 source,
662 })?;
663 let mut files = BTreeSet::new();
664 let mut root_level_file = None;
665 for line in text.lines() {
666 let trimmed = line.trim();
667 if let Some(rest) = trimmed.strip_prefix("include!(\"")
668 && let Some(file_name) = rest.strip_suffix("\");")
669 {
670 if line.starts_with("include!(\"") && root_level_file.is_none() {
671 root_level_file = Some(file_name.to_string());
672 }
673 files.insert(file_name.to_string());
674 }
675 }
676 Ok((files, root_level_file))
677}
678
679fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<(), Error> {
680 if let Ok(existing) = fs::read(path)
681 && existing == bytes
682 {
683 return Ok(());
684 }
685 fs::write(path, bytes).map_err(|source| Error::Io {
686 path: Some(path.to_path_buf()),
687 source,
688 })
689}
690
691#[allow(clippy::too_many_arguments)]
692fn write_standalone_include(
693 proto_files: &[PathBuf],
694 proto_dir: &Path,
695 package_by_file: &BTreeMap<String, String>,
696 out_dir: &Path,
697 emitted_prost_files: &BTreeSet<String>,
698 root_level_file: Option<&str>,
699 include_path: &Path,
700 #[cfg(feature = "pbjson")] serde_by_pkg: &BTreeMap<String, String>,
701 pbjson_enabled: bool,
702) -> Result<(), Error> {
703 #[cfg(not(feature = "pbjson"))]
704 let _ = pbjson_enabled;
705
706 let mut majors: BTreeMap<u64, (String, PathBuf)> = BTreeMap::new();
707 for path in proto_files {
708 let rel = rel_proto_path(proto_dir, path);
709 if let Some(file_name) = path.file_name().and_then(std::ffi::OsStr::to_str)
710 && let Some(major) = parse_root_major(file_name)
711 {
712 let pkg = package_by_file.get(&rel).cloned().unwrap_or_default();
713 if let Some((_, existing)) = majors.insert(major, (pkg, path.clone())) {
714 return Err(Error::Io {
715 path: Some(path.clone()),
716 source: std::io::Error::new(
717 std::io::ErrorKind::InvalidInput,
718 format!(
719 "duplicate root major proto for `v{major}`: `{}` conflicts with `{}`",
720 path.display(),
721 existing.display()
722 ),
723 ),
724 });
725 }
726 }
727 }
728
729 let mut out = String::from("// @generated by witforge-build; do not edit.\n");
730 for (major, (pkg, _)) in majors {
731 let rs_name = if pkg.is_empty() {
732 root_level_file.map_or_else(|| prost_file_name(""), ToString::to_string)
733 } else {
734 prost_file_name(&pkg)
735 };
736 let _ = writeln!(out);
737 if emitted_prost_files.contains(&rs_name) {
738 let _ = writeln!(out, "pub mod v{major} {{");
739 let _ = writeln!(out, " include!({rs_name:?});");
740 #[cfg(feature = "pbjson")]
741 if pbjson_enabled && let Some(serde_name) = serde_by_pkg.get(&pkg) {
742 let _ = writeln!(out, " include!({serde_name:?});");
743 }
744 let _ = writeln!(out, "}}");
745 } else {
746 let stale = out_dir.join(&rs_name);
747 if stale.is_file() {
748 let _ = fs::remove_file(stale);
749 }
750 let _ = writeln!(out, "pub mod v{major} {{}}");
751 }
752 }
753
754 write_if_changed(include_path, out.as_bytes())
755}
756
757#[cfg(feature = "pbjson")]
758fn splice_pbjson_includes(
759 raw_include_path: &Path,
760 package_by_file: &BTreeMap<String, String>,
761 serde_by_pkg: &BTreeMap<String, String>,
762) -> Result<String, Error> {
763 let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
764 path: Some(raw_include_path.to_path_buf()),
765 source,
766 })?;
767
768 let mut serde_by_prost_file: BTreeMap<String, String> = BTreeMap::new();
769 for pkg in package_by_file.values() {
770 let prost_name = prost_file_name(pkg);
771 if let Some(serde_name) = serde_by_pkg.get(pkg) {
772 serde_by_prost_file.insert(prost_name, serde_name.clone());
773 }
774 }
775
776 let mut out = String::with_capacity(text.len() + serde_by_prost_file.len() * 48);
777 for line in text.lines() {
778 out.push_str(line);
779 out.push('\n');
780 let trimmed = line.trim_start();
781 let indent = &line[..line.len() - trimmed.len()];
782 if let Some(rest) = trimmed.strip_prefix("include!(\"")
783 && let Some(prost_name) = rest.strip_suffix("\");")
784 && let Some(serde_name) = serde_by_prost_file.get(prost_name)
785 {
786 let _ = writeln!(out, "{indent}include!({serde_name:?});");
787 }
788 }
789 Ok(out)
790}