mod files;
use std::fmt;
use std::path::{Path, PathBuf};
use crate::CodegenError;
include!(concat!(env!("OUT_DIR"), "/embedded_templates.generated.rs"));
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateDrift {
pub dir: PathBuf,
pub changed: Vec<String>,
pub not_embedded: Vec<String>,
pub removed: Vec<String>,
}
impl fmt::Display for TemplateDrift {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"this nativeview-codegen build was compiled from other templates than {}",
self.dir.display()
)?;
for (label, files) in [
("changed", &self.changed),
("not embedded", &self.not_embedded),
("removed on disk", &self.removed),
] {
if !files.is_empty() {
write!(f, "; {label}: {}", files.join(", "))?;
}
}
write!(
f,
". A compiler cache or a CARGO_TARGET_DIR shared with another checkout served a stale \
build: rebuild with this worktree's own CARGO_TARGET_DIR and \
`RUSTC_WRAPPER= CARGO_INCREMENTAL=0 cargo …` (docs/iteration-speed.md)"
)
}
}
pub fn verify_embedded_templates(templates_dir: &Path) -> Result<(), CodegenError> {
template_drift(EMBEDDED_TEMPLATES, templates_dir)?
.map_or(Ok(()), |drift| Err(CodegenError::StaleTemplates(drift)))
}
fn template_drift(
embedded: &[(&str, &[u8])],
dir: &Path,
) -> Result<Option<TemplateDrift>, CodegenError> {
let on_disk =
files::template_files(dir).map_err(|e| CodegenError::io(dir.display().to_string(), e))?;
let mut drift = TemplateDrift {
dir: dir.to_path_buf(),
changed: Vec::new(),
not_embedded: Vec::new(),
removed: Vec::new(),
};
for &(name, bytes) in embedded {
if on_disk
.binary_search_by(|file| file.as_str().cmp(name))
.is_err()
{
drift.removed.push(name.to_owned());
continue;
}
let path = dir.join(name);
let disk =
std::fs::read(&path).map_err(|e| CodegenError::io(path.display().to_string(), e))?;
if disk != bytes {
drift.changed.push(name.to_owned());
}
}
drift.not_embedded = on_disk
.into_iter()
.filter(|file| !embedded.iter().any(|&(name, _)| name == file))
.collect();
let clean =
drift.changed.is_empty() && drift.not_embedded.is_empty() && drift.removed.is_empty();
Ok((!clean).then_some(drift))
}
#[cfg(test)]
mod tests;