nativeview_codegen/embedded_templates/
mod.rs1mod files;
11
12use std::fmt;
13use std::path::{Path, PathBuf};
14
15use crate::CodegenError;
16
17include!(concat!(env!("OUT_DIR"), "/embedded_templates.generated.rs"));
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct TemplateDrift {
22 pub dir: PathBuf,
24 pub changed: Vec<String>,
26 pub not_embedded: Vec<String>,
28 pub removed: Vec<String>,
30}
31
32impl fmt::Display for TemplateDrift {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(
35 f,
36 "this nativeview-codegen build was compiled from other templates than {}",
37 self.dir.display()
38 )?;
39 for (label, files) in [
40 ("changed", &self.changed),
41 ("not embedded", &self.not_embedded),
42 ("removed on disk", &self.removed),
43 ] {
44 if !files.is_empty() {
45 write!(f, "; {label}: {}", files.join(", "))?;
46 }
47 }
48 write!(
49 f,
50 ". A compiler cache or a CARGO_TARGET_DIR shared with another checkout served a stale \
51 build: rebuild with this worktree's own CARGO_TARGET_DIR and \
52 `RUSTC_WRAPPER= CARGO_INCREMENTAL=0 cargo …` (docs/iteration-speed.md)"
53 )
54 }
55}
56
57pub fn verify_embedded_templates(templates_dir: &Path) -> Result<(), CodegenError> {
60 template_drift(EMBEDDED_TEMPLATES, templates_dir)?
61 .map_or(Ok(()), |drift| Err(CodegenError::StaleTemplates(drift)))
62}
63
64fn template_drift(
65 embedded: &[(&str, &[u8])],
66 dir: &Path,
67) -> Result<Option<TemplateDrift>, CodegenError> {
68 let on_disk =
69 files::template_files(dir).map_err(|e| CodegenError::io(dir.display().to_string(), e))?;
70 let mut drift = TemplateDrift {
71 dir: dir.to_path_buf(),
72 changed: Vec::new(),
73 not_embedded: Vec::new(),
74 removed: Vec::new(),
75 };
76 for &(name, bytes) in embedded {
77 if on_disk
78 .binary_search_by(|file| file.as_str().cmp(name))
79 .is_err()
80 {
81 drift.removed.push(name.to_owned());
82 continue;
83 }
84 let path = dir.join(name);
85 let disk =
86 std::fs::read(&path).map_err(|e| CodegenError::io(path.display().to_string(), e))?;
87 if disk != bytes {
88 drift.changed.push(name.to_owned());
89 }
90 }
91 drift.not_embedded = on_disk
92 .into_iter()
93 .filter(|file| !embedded.iter().any(|&(name, _)| name == file))
94 .collect();
95 let clean =
96 drift.changed.is_empty() && drift.not_embedded.is_empty() && drift.removed.is_empty();
97 Ok((!clean).then_some(drift))
98}
99
100#[cfg(test)]
101mod tests;