nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
Documentation
//! Proof that this build's Askama code was compiled from the templates of the checkout it runs in.
//!
//! The templates are compiled into the crate, so a compiler cache (kache) or a `CARGO_TARGET_DIR`
//! shared across worktrees can serve a build of another checkout whose templates differ: `nv
//! codegen abi --check` then "verifies" the host files against the wrong templates. `build.rs`
//! embeds the bytes of every template into the same compilation as the Askama code, so a replayed
//! build carries the templates it was really compiled from, and [`verify_embedded_templates`]
//! compares them with the checkout's `templates/` directory.

mod files;

use std::fmt;
use std::path::{Path, PathBuf};

use crate::CodegenError;

include!(concat!(env!("OUT_DIR"), "/embedded_templates.generated.rs"));

/// The difference between the templates a build embeds and a `templates/` directory on disk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateDrift {
    /// The directory compared against.
    pub dir: PathBuf,
    /// Templates whose bytes differ.
    pub changed: Vec<String>,
    /// Templates on disk the build does not embed (added after it was compiled).
    pub not_embedded: Vec<String>,
    /// Templates the build embeds that are no longer on disk.
    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)"
        )
    }
}

/// Fails with [`CodegenError::StaleTemplates`] when the templates this build was compiled from
/// differ from `templates_dir` (the checkout's `packages/core/codegen/templates`).
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;