#![deny(missing_docs)]
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fmt::{self, Write as _};
use std::fs;
use std::path::{Component, Path, PathBuf};
use protox::prost::Message as _;
pub const DEFAULT_INCLUDE_FILE: &str = "prost_include.rs";
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Io {
path: Option<PathBuf>,
source: std::io::Error,
},
MissingOutDir,
NoProtoFiles(PathBuf),
SymlinkRefused(PathBuf),
InvalidIncludeFile(PathBuf),
Protox(protox::Error),
Prost(std::io::Error),
#[cfg(feature = "pbjson")]
Pbjson(std::io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io {
path: Some(path),
source,
} => write!(f, "I/O error at {}: {source}", path.display()),
Self::Io { path: None, source } => write!(f, "I/O error: {source}"),
Self::MissingOutDir => write!(
f,
"OUT_DIR is not set; invoke from a Cargo build script or call Config::out_dir"
),
Self::NoProtoFiles(dir) => {
write!(f, "no `.proto` files found under {}", dir.display())
}
Self::SymlinkRefused(path) => {
write!(f, "refusing to follow symlink {}", path.display())
}
Self::InvalidIncludeFile(path) => write!(
f,
"include_file `{}` must be a single plain filename inside out_dir",
path.display()
),
Self::Protox(err) => write!(f, "protox failed to compile protobuf schema: {err}"),
Self::Prost(err) => write!(f, "prost-build failed: {err}"),
#[cfg(feature = "pbjson")]
Self::Pbjson(err) => write!(f, "pbjson-build failed: {err}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } | Self::Prost(source) => Some(source),
Self::Protox(err) => Some(err),
#[cfg(feature = "pbjson")]
Self::Pbjson(err) => Some(err),
Self::MissingOutDir
| Self::NoProtoFiles(_)
| Self::SymlinkRefused(_)
| Self::InvalidIncludeFile(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct BuildOutput {
pub proto_files: Vec<PathBuf>,
pub out_dir: PathBuf,
pub include_file: Option<PathBuf>,
pub has_dependencies: bool,
pub rerun_directives: Vec<String>,
}
pub struct Config {
prost: prost_build::Config,
out_dir: Option<PathBuf>,
include_file: Option<PathBuf>,
file_descriptor_set_path: Option<PathBuf>,
emit_rerun_if_changed: bool,
#[cfg(feature = "pbjson")]
pbjson: bool,
#[cfg(feature = "pbjson")]
pbjson_builder: pbjson_build::Builder,
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("Config");
s.field("prost", &self.prost)
.field("out_dir", &self.out_dir)
.field("include_file", &self.include_file)
.field("file_descriptor_set_path", &self.file_descriptor_set_path)
.field("emit_rerun_if_changed", &self.emit_rerun_if_changed);
#[cfg(feature = "pbjson")]
s.field("pbjson", &self.pbjson);
s.finish_non_exhaustive()
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl Config {
#[must_use]
pub fn new() -> Self {
Self {
prost: prost_build::Config::new(),
out_dir: None,
include_file: Some(PathBuf::from(DEFAULT_INCLUDE_FILE)),
file_descriptor_set_path: None,
emit_rerun_if_changed: true,
#[cfg(feature = "pbjson")]
pbjson: false,
#[cfg(feature = "pbjson")]
pbjson_builder: pbjson_build::Builder::new(),
}
}
#[must_use]
pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.out_dir = Some(dir.into());
self
}
#[must_use]
pub fn include_file(mut self, name: impl Into<PathBuf>) -> Self {
self.include_file = Some(name.into());
self
}
#[must_use]
pub fn no_include_file(mut self) -> Self {
self.include_file = None;
self
}
#[must_use]
pub fn file_descriptor_set_path(mut self, path: impl Into<PathBuf>) -> Self {
self.file_descriptor_set_path = Some(path.into());
self
}
#[must_use]
pub const fn emit_rerun_if_changed(mut self, enabled: bool) -> Self {
self.emit_rerun_if_changed = enabled;
self
}
pub fn prost_config(&mut self) -> &mut prost_build::Config {
&mut self.prost
}
#[must_use]
pub fn with_prost_config(mut self, configure: impl FnOnce(&mut prost_build::Config)) -> Self {
configure(&mut self.prost);
self
}
#[cfg(feature = "pbjson")]
#[must_use]
pub const fn pbjson(mut self, enabled: bool) -> Self {
self.pbjson = enabled;
self
}
#[cfg(feature = "pbjson")]
pub fn pbjson_builder(&mut self) -> &mut pbjson_build::Builder {
&mut self.pbjson_builder
}
#[cfg(feature = "pbjson")]
#[must_use]
pub fn with_pbjson_builder(
mut self,
configure: impl FnOnce(&mut pbjson_build::Builder),
) -> Self {
self.pbjson = true;
configure(&mut self.pbjson_builder);
self
}
#[allow(clippy::too_many_lines)]
pub fn compile_protos(mut self, proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
let proto_dir = proto_dir.as_ref();
if let Some(include_name) = &self.include_file {
validate_include_file_name(include_name)?;
}
let (proto_files, visited_dirs) = discover_protos_and_dirs(proto_dir)?;
let out_dir = match self.out_dir {
Some(dir) => dir,
None => PathBuf::from(env::var_os("OUT_DIR").ok_or(Error::MissingOutDir)?),
};
fs::create_dir_all(&out_dir).map_err(|source| Error::Io {
path: Some(out_dir.clone()),
source,
})?;
let mut rerun_directives = Vec::with_capacity(visited_dirs.len() + proto_files.len());
for dir in &visited_dirs {
rerun_directives.push(format!("cargo:rerun-if-changed={}", dir.display()));
}
for file in &proto_files {
rerun_directives.push(format!("cargo:rerun-if-changed={}", file.display()));
}
if self.emit_rerun_if_changed {
for directive in &rerun_directives {
println!("{directive}");
}
}
let descriptors = protox::compile(&proto_files, [proto_dir]).map_err(Error::Protox)?;
let encoded_descriptors = descriptors.encode_to_vec();
if let Some(fds_path) = &self.file_descriptor_set_path {
if let Some(parent) = fds_path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent).map_err(|source| Error::Io {
path: Some(parent.to_path_buf()),
source,
})?;
}
write_if_changed(fds_path, &encoded_descriptors)?;
}
let discovered_rel_files: BTreeSet<String> = proto_files
.iter()
.map(|path| rel_proto_path(proto_dir, path))
.collect();
let has_dependencies = proto_files
.iter()
.any(|path| !is_root_major_proto(proto_dir, path));
let package_by_file: BTreeMap<String, String> = descriptors
.file
.iter()
.filter_map(|file| {
let name = file.name.as_deref()?;
if !discovered_rel_files.contains(name) {
return None;
}
let pkg = file.package.as_deref().unwrap_or_default();
Some((name.to_string(), pkg.to_string()))
})
.collect();
#[cfg(feature = "pbjson")]
let pbjson_enabled = self.pbjson;
#[cfg(not(feature = "pbjson"))]
let pbjson_enabled = false;
#[cfg(feature = "pbjson")]
if pbjson_enabled {
for file in &descriptors.file {
if file.package.as_deref().is_none_or(str::is_empty) {
let name = file.name.as_deref().unwrap_or("<unnamed>");
return Err(Error::Pbjson(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"protobuf file `{name}` has no `package` declaration, which is \
required when `pbjson` is enabled"
),
)));
}
}
}
#[cfg(feature = "pbjson")]
let pbjson_prefixes = collect_pbjson_prefixes(&package_by_file);
self.prost.out_dir(&out_dir);
let include_path = self.include_file.as_ref().map(|name| out_dir.join(name));
let raw_prost_include = if let Some(include_name) = &self.include_file {
if !has_dependencies || pbjson_enabled {
let scratch_name =
PathBuf::from(format!(".{}.prost", include_name.to_string_lossy()));
self.prost.include_file(&scratch_name);
Some(out_dir.join(scratch_name))
} else {
self.prost.include_file(include_name);
None
}
} else {
None
};
let _raw_include_cleanup = TempFileGuard(raw_prost_include.clone());
self.prost.compile_fds(descriptors).map_err(Error::Prost)?;
#[cfg(feature = "pbjson")]
let serde_by_pkg: BTreeMap<String, String> = if pbjson_enabled {
let prefix_refs: Vec<&str> = pbjson_prefixes.iter().map(String::as_str).collect();
let generated = self
.pbjson_builder
.register_descriptors(&encoded_descriptors)
.map_err(Error::Pbjson)?
.generate(&prefix_refs, |_| Ok(Vec::<u8>::new()))
.map_err(Error::Pbjson)?;
let mut emitted_by_pkg = BTreeMap::new();
let mut written_files = BTreeSet::new();
for (package, bytes) in generated {
let raw_pkg = package
.path()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(".");
let serde_name = format!("{package}.serde.rs");
write_if_changed(&out_dir.join(&serde_name), &bytes)?;
written_files.insert(serde_name.clone());
emitted_by_pkg.insert(raw_pkg, serde_name);
}
for pkg in package_by_file.values() {
if !emitted_by_pkg.contains_key(pkg) {
for candidate in pbjson_candidate_file_names(pkg) {
if !written_files.contains(&candidate) {
let stale = out_dir.join(&candidate);
if stale.is_file() {
let _ = fs::remove_file(stale);
}
}
}
}
}
emitted_by_pkg
} else {
BTreeMap::new()
};
if let Some(include_path) = &include_path {
if has_dependencies {
#[cfg(feature = "pbjson")]
if pbjson_enabled && let Some(raw_path) = &raw_prost_include {
let spliced =
splice_pbjson_includes(raw_path, &package_by_file, &serde_by_pkg)?;
write_if_changed(include_path, spliced.as_bytes())?;
}
#[cfg(not(feature = "pbjson"))]
let _ = raw_prost_include;
} else {
let (emitted_prost_files, root_level_file) = raw_prost_include
.as_deref()
.map(extract_prost_include_files)
.transpose()?
.unwrap_or_default();
write_standalone_include(
&proto_files,
proto_dir,
&package_by_file,
&out_dir,
&emitted_prost_files,
root_level_file.as_deref(),
include_path,
#[cfg(feature = "pbjson")]
&serde_by_pkg,
pbjson_enabled,
)?;
}
}
Ok(BuildOutput {
proto_files,
out_dir,
include_file: include_path,
has_dependencies,
rerun_directives,
})
}
}
pub fn discover_protos(proto_dir: impl AsRef<Path>) -> Result<Vec<PathBuf>, Error> {
let (files, _) = discover_protos_and_dirs(proto_dir.as_ref())?;
Ok(files)
}
pub fn compile_protos(proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
Config::new().compile_protos(proto_dir)
}
struct TempFileGuard(Option<PathBuf>);
impl Drop for TempFileGuard {
fn drop(&mut self) {
if let Some(path) = &self.0 {
let _ = fs::remove_file(path);
}
}
}
fn validate_include_file_name(name: &Path) -> Result<(), Error> {
if name.as_os_str().as_encoded_bytes().contains(&b'\\') {
return Err(Error::InvalidIncludeFile(name.to_path_buf()));
}
let mut components = name.components();
match (components.next(), components.next()) {
(Some(Component::Normal(part)), None) if !part.is_empty() && name.as_os_str() == part => {
Ok(())
}
_ => Err(Error::InvalidIncludeFile(name.to_path_buf())),
}
}
fn discover_protos_and_dirs(proto_dir: &Path) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Error> {
let normalized_root: PathBuf = proto_dir.components().collect();
let root_meta = fs::symlink_metadata(&normalized_root).map_err(|source| Error::Io {
path: Some(proto_dir.to_path_buf()),
source,
})?;
if root_meta.file_type().is_symlink() {
return Err(Error::SymlinkRefused(proto_dir.to_path_buf()));
}
let mut files = Vec::new();
let mut dirs = vec![proto_dir.to_path_buf()];
collect_protos_recursive(proto_dir, &mut files, &mut dirs)?;
files.sort();
dirs.sort();
if files.is_empty() {
return Err(Error::NoProtoFiles(proto_dir.to_path_buf()));
}
Ok((files, dirs))
}
fn collect_protos_recursive(
dir: &Path,
out_files: &mut Vec<PathBuf>,
out_dirs: &mut Vec<PathBuf>,
) -> Result<(), Error> {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)
.map_err(|source| Error::Io {
path: Some(dir.to_path_buf()),
source,
})?
.map(|entry| {
entry.map(|item| item.path()).map_err(|source| Error::Io {
path: Some(dir.to_path_buf()),
source,
})
})
.collect::<Result<Vec<_>, _>>()?;
entries.sort();
for path in entries {
let meta = fs::symlink_metadata(&path).map_err(|source| Error::Io {
path: Some(path.clone()),
source,
})?;
if meta.file_type().is_symlink() {
return Err(Error::SymlinkRefused(path));
}
if meta.is_dir() {
out_dirs.push(path.clone());
collect_protos_recursive(&path, out_files, out_dirs)?;
} else if meta.is_file()
&& path
.extension()
.and_then(std::ffi::OsStr::to_str)
.is_some_and(|ext| ext.eq_ignore_ascii_case("proto"))
{
out_files.push(path);
}
}
Ok(())
}
fn is_root_major_proto(proto_dir: &Path, path: &Path) -> bool {
let Ok(rel) = path.strip_prefix(proto_dir) else {
return false;
};
if rel.components().count() != 1 {
return false;
}
let Some(name) = rel.file_name().and_then(std::ffi::OsStr::to_str) else {
return false;
};
parse_root_major(name).is_some()
}
fn parse_root_major(file_name: &str) -> Option<u64> {
let dot = file_name.rfind('.')?;
if !file_name[dot + 1..].eq_ignore_ascii_case("proto") {
return None;
}
let stem = &file_name[..dot];
let digits = stem.strip_prefix('v')?;
if digits.is_empty()
|| !digits.bytes().all(|b| b.is_ascii_digit())
|| (digits.len() > 1 && digits.starts_with('0'))
{
return None;
}
digits.parse().ok()
}
fn prost_file_name(pkg: &str) -> String {
prost_build::Module::from_protobuf_package_name(pkg).to_file_name_or("_")
}
#[cfg(feature = "pbjson")]
fn pbjson_candidate_file_names(pkg: &str) -> Vec<String> {
let module = prost_build::Module::from_protobuf_package_name(pkg);
let prost_stem = if module.is_empty() {
"_".to_string()
} else {
module.parts().collect::<Vec<_>>().join(".")
};
let primary = format!("{prost_stem}.serde.rs");
let compat_stem = module
.parts()
.map(|part| match part {
"r#gen" => "gen",
"__" => "_",
other => other,
})
.collect::<Vec<_>>()
.join(".");
let fallback = format!("{compat_stem}.serde.rs");
if fallback == primary {
vec![primary]
} else {
vec![primary, fallback]
}
}
#[cfg(feature = "pbjson")]
fn collect_pbjson_prefixes(package_by_file: &BTreeMap<String, String>) -> BTreeSet<String> {
let mut prefixes = BTreeSet::new();
for pkg in package_by_file.values() {
if !pkg.is_empty() {
prefixes.insert(format!(".{pkg}"));
}
}
prefixes
}
fn rel_proto_path(proto_dir: &Path, path: &Path) -> String {
path.strip_prefix(proto_dir)
.unwrap_or(path)
.components()
.filter_map(|component| match component {
Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
_ => None,
})
.collect::<Vec<_>>()
.join("/")
}
fn extract_prost_include_files(
raw_include_path: &Path,
) -> Result<(BTreeSet<String>, Option<String>), Error> {
let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
path: Some(raw_include_path.to_path_buf()),
source,
})?;
let mut files = BTreeSet::new();
let mut root_level_file = None;
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("include!(\"")
&& let Some(file_name) = rest.strip_suffix("\");")
{
if line.starts_with("include!(\"") && root_level_file.is_none() {
root_level_file = Some(file_name.to_string());
}
files.insert(file_name.to_string());
}
}
Ok((files, root_level_file))
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<(), Error> {
if let Ok(existing) = fs::read(path)
&& existing == bytes
{
return Ok(());
}
fs::write(path, bytes).map_err(|source| Error::Io {
path: Some(path.to_path_buf()),
source,
})
}
#[allow(clippy::too_many_arguments)]
fn write_standalone_include(
proto_files: &[PathBuf],
proto_dir: &Path,
package_by_file: &BTreeMap<String, String>,
out_dir: &Path,
emitted_prost_files: &BTreeSet<String>,
root_level_file: Option<&str>,
include_path: &Path,
#[cfg(feature = "pbjson")] serde_by_pkg: &BTreeMap<String, String>,
pbjson_enabled: bool,
) -> Result<(), Error> {
#[cfg(not(feature = "pbjson"))]
let _ = pbjson_enabled;
let mut majors: BTreeMap<u64, (String, PathBuf)> = BTreeMap::new();
for path in proto_files {
let rel = rel_proto_path(proto_dir, path);
if let Some(file_name) = path.file_name().and_then(std::ffi::OsStr::to_str)
&& let Some(major) = parse_root_major(file_name)
{
let pkg = package_by_file.get(&rel).cloned().unwrap_or_default();
if let Some((_, existing)) = majors.insert(major, (pkg, path.clone())) {
return Err(Error::Io {
path: Some(path.clone()),
source: std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate root major proto for `v{major}`: `{}` conflicts with `{}`",
path.display(),
existing.display()
),
),
});
}
}
}
let mut out = String::from("// @generated by witforge-build; do not edit.\n");
for (major, (pkg, _)) in majors {
let rs_name = if pkg.is_empty() {
root_level_file.map_or_else(|| prost_file_name(""), ToString::to_string)
} else {
prost_file_name(&pkg)
};
let _ = writeln!(out);
if emitted_prost_files.contains(&rs_name) {
let _ = writeln!(out, "pub mod v{major} {{");
let _ = writeln!(out, " include!({rs_name:?});");
#[cfg(feature = "pbjson")]
if pbjson_enabled && let Some(serde_name) = serde_by_pkg.get(&pkg) {
let _ = writeln!(out, " include!({serde_name:?});");
}
let _ = writeln!(out, "}}");
} else {
let stale = out_dir.join(&rs_name);
if stale.is_file() {
let _ = fs::remove_file(stale);
}
let _ = writeln!(out, "pub mod v{major} {{}}");
}
}
write_if_changed(include_path, out.as_bytes())
}
#[cfg(feature = "pbjson")]
fn splice_pbjson_includes(
raw_include_path: &Path,
package_by_file: &BTreeMap<String, String>,
serde_by_pkg: &BTreeMap<String, String>,
) -> Result<String, Error> {
let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
path: Some(raw_include_path.to_path_buf()),
source,
})?;
let mut serde_by_prost_file: BTreeMap<String, String> = BTreeMap::new();
for pkg in package_by_file.values() {
let prost_name = prost_file_name(pkg);
if let Some(serde_name) = serde_by_pkg.get(pkg) {
serde_by_prost_file.insert(prost_name, serde_name.clone());
}
}
let mut out = String::with_capacity(text.len() + serde_by_prost_file.len() * 48);
for line in text.lines() {
out.push_str(line);
out.push('\n');
let trimmed = line.trim_start();
let indent = &line[..line.len() - trimmed.len()];
if let Some(rest) = trimmed.strip_prefix("include!(\"")
&& let Some(prost_name) = rest.strip_suffix("\");")
&& let Some(serde_name) = serde_by_prost_file.get(prost_name)
{
let _ = writeln!(out, "{indent}include!({serde_name:?});");
}
}
Ok(out)
}