Skip to main content

nativeview_codegen/embedded_templates/
mod.rs

1//! Proof that this build's Askama code was compiled from the templates of the checkout it runs in.
2//!
3//! The templates are compiled into the crate, so a compiler cache (kache) or a `CARGO_TARGET_DIR`
4//! shared across worktrees can serve a build of another checkout whose templates differ: `nv
5//! codegen abi --check` then "verifies" the host files against the wrong templates. `build.rs`
6//! embeds the bytes of every template into the same compilation as the Askama code, so a replayed
7//! build carries the templates it was really compiled from, and [`verify_embedded_templates`]
8//! compares them with the checkout's `templates/` directory.
9
10mod 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/// The difference between the templates a build embeds and a `templates/` directory on disk.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct TemplateDrift {
22    /// The directory compared against.
23    pub dir: PathBuf,
24    /// Templates whose bytes differ.
25    pub changed: Vec<String>,
26    /// Templates on disk the build does not embed (added after it was compiled).
27    pub not_embedded: Vec<String>,
28    /// Templates the build embeds that are no longer on disk.
29    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
57/// Fails with [`CodegenError::StaleTemplates`] when the templates this build was compiled from
58/// differ from `templates_dir` (the checkout's `packages/core/codegen/templates`).
59pub 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;