layline-codegen 0.5.0

Rust source generation for layline.
Documentation
//! Writing generated files to disk and checking them.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// The files a generator writes, and the command that regenerates them.
///
/// [`update`](Self::update) writes the files. [`check`](Self::check) compares them with disk.
///
/// ```no_run
/// use layline_codegen::emit::{Committed, Module, generate};
///
/// /// Regenerates the artifact.
/// const COMMAND: &str = "cargo codegen";
///
/// fn committed() -> Committed {
///     let module = Module::new(vec![]).with_doc(vec![format!("Regenerate with `{COMMAND}`.")]);
///     Committed::by(COMMAND).file("src/generated/wire.rs", generate(&module).unwrap().source)
/// }
///
/// fn main() {
///     for change in committed().update().expect("write the artifact") {
///         println!("{change}");
///     }
/// }
///
/// #[test]
/// fn the_committed_source_is_what_the_emitter_writes() {
///     committed().check().expect("the committed artifact is current");
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Committed {
    command: String,
    files: BTreeMap<PathBuf, String>,
    owned: BTreeSet<PathBuf>,
}

impl Committed {
    /// An empty set of files, regenerated by `command`.
    ///
    /// Failures quote `command`, so it should run from the repository root.
    #[must_use]
    pub fn by(command: impl Into<String>) -> Self {
        Self { command: command.into(), files: BTreeMap::new(), owned: BTreeSet::new() }
    }

    /// Adds a file. A later call for the same path replaces it.
    #[must_use]
    pub fn file(mut self, path: impl Into<PathBuf>, contents: impl Into<String>) -> Self {
        self.files.insert(path.into(), contents.into());
        self
    }

    /// Adds a directory whose `.rs` files must be exactly `files`, as (name, contents) pairs.
    ///
    /// Other `.rs` files in `dir` are reported and deleted. Everything else is left alone.
    #[must_use]
    pub fn dir<N, C>(
        mut self,
        dir: impl Into<PathBuf>,
        files: impl IntoIterator<Item = (N, C)>,
    ) -> Self
    where
        N: AsRef<Path>,
        C: Into<String>,
    {
        let dir = dir.into();
        for (name, contents) in files {
            self.files.insert(dir.join(name), contents.into());
        }
        self.owned.insert(dir);
        self
    }

    /// Writes changed files, creating parent directories, and deletes extra ones.
    ///
    /// Returns the changes in path order.
    ///
    /// # Errors
    ///
    /// The first filesystem error.
    pub fn update(&self) -> std::io::Result<Vec<Change>> {
        let mut changes = Vec::new();
        for (path, contents) in &self.files {
            let want = normalize_newlines(contents);
            if reads_as(path, &want) {
                continue;
            }
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(path, &want)?;
            changes.push(Change::Wrote(path.clone()));
        }
        for extra in self.extra()? {
            std::fs::remove_file(&extra)?;
            changes.push(Change::Removed(extra));
        }
        Ok(changes)
    }

    /// Checks the files on disk without changing them.
    ///
    /// An unreadable file counts as [`Drift::Missing`].
    ///
    /// # Errors
    ///
    /// [`Drifted`], listing every mismatched path and the command that fixes it.
    pub fn check(&self) -> Result<(), Drifted> {
        let mut paths = Vec::new();
        for (path, contents) in &self.files {
            match std::fs::read_to_string(path) {
                Ok(have) if normalize_newlines(&have) == normalize_newlines(contents) => {}
                Ok(_) => paths.push((path.clone(), Drift::Stale)),
                Err(_) => paths.push((path.clone(), Drift::Missing)),
            }
        }
        for extra in self.extra().unwrap_or_default() {
            paths.push((extra, Drift::Extra));
        }
        if paths.is_empty() {
            return Ok(());
        }
        Err(Drifted { command: self.command.clone(), ci: std::env::var_os("CI").is_some(), paths })
    }

    /// `.rs` files in an owned directory that the generator does not write.
    fn extra(&self) -> std::io::Result<Vec<PathBuf>> {
        let mut extra = Vec::new();
        for dir in &self.owned {
            for entry in std::fs::read_dir(dir)? {
                let path = entry?.path();
                if path.extension().is_some_and(|e| e == "rs")
                    && path.is_file()
                    && !self.files.contains_key(&path)
                {
                    extra.push(path);
                }
            }
        }
        extra.sort();
        Ok(extra)
    }
}

/// A change made by [`Committed::update`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
    /// The file was written.
    Wrote(PathBuf),
    /// The file was deleted from an owned directory.
    Removed(PathBuf),
}

impl std::fmt::Display for Change {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Wrote(p) => write!(f, "wrote   {}", p.display()),
            Self::Removed(p) => write!(f, "removed {} (no longer generated)", p.display()),
        }
    }
}

/// How a path differs from the generator's output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Drift {
    /// The contents differ.
    Stale,
    /// The file is absent or unreadable.
    Missing,
    /// The file is in an [owned](Committed::dir) directory but not generated.
    Extra,
}

impl Drift {
    const fn label(self) -> &'static str {
        match self {
            Self::Stale => "stale  ",
            Self::Missing => "missing",
            Self::Extra => "extra  ",
        }
    }
}

/// Files on disk differ from the generator's output.
///
/// `Debug` prints the same text as `Display`.
#[derive(Clone)]
pub struct Drifted {
    command: String,
    ci: bool,
    paths: Vec<(PathBuf, Drift)>,
}

impl Drifted {
    /// Each mismatched path, and how it differs.
    #[must_use]
    pub fn paths(&self) -> &[(PathBuf, Drift)] {
        &self.paths
    }

    /// The command that regenerates the files.
    #[must_use]
    pub fn command(&self) -> &str {
        &self.command
    }
}

impl std::fmt::Display for Drifted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let n = self.paths.len();
        let s = if n == 1 { "" } else { "s" };
        writeln!(f, "{n} path{s} out of date:")?;
        for (path, how) in &self.paths {
            writeln!(f, "  {}  {}", how.label(), path.display())?;
        }
        write!(f, "\nRun `{}` and review the diff. It changes the wire format.", self.command)?;
        if self.ci {
            write!(f, "\n    NOTE: run `{}` locally and commit the updated files.", self.command)?;
        }
        Ok(())
    }
}

impl std::fmt::Debug for Drifted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl core::error::Error for Drifted {}

fn normalize_newlines(s: &str) -> String {
    s.replace("\r\n", "\n")
}

fn reads_as(path: &Path, contents: &str) -> bool {
    std::fs::read_to_string(path).is_ok_and(|old| normalize_newlines(&old) == contents)
}