vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! The folder a plan works in: paths that stay inside it, patterns, and what it holds.

use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Write as _;
use std::fs;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;

use similar::TextDiff;

/// Whether a path stays inside the folder: not blank, not from the root, no drive and no `..` part.
pub fn inside(path: &str) -> bool {
    let bytes = path.as_bytes();
    let drive = bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic();
    let blank = path.trim().is_empty();
    let rooted = path.starts_with('/') || path.starts_with('\\');
    let up = path.split(['/', '\\']).any(|part| part == "..");
    !(blank || rooted || drive || up)
}

/// Whether a name matches a pattern, where `*` stands for any text.
pub fn matches(pattern: &str, name: &str) -> bool {
    let mut parts = pattern.split('*');
    let first = parts.next().unwrap_or_default();
    let Some(mut rest) = name.strip_prefix(first) else {
        return false;
    };
    let parts: Vec<&str> = parts.collect();
    let Some((last, middle)) = parts.split_last() else {
        return rest.is_empty();
    };
    for part in middle {
        match rest.find(part) {
            Some(at) => rest = &rest[at + part.len()..],
            None => return false,
        }
    }
    rest.len() >= last.len() && rest.ends_with(last)
}

fn entries(folder: &Path) -> Vec<PathBuf> {
    let mut entries: Vec<PathBuf> = fs::read_dir(folder)
        .map(|read| {
            read.filter_map(Result::ok)
                .map(|entry| entry.path())
                .collect()
        })
        .unwrap_or_default();
    entries.sort();
    entries
}

fn name(path: &Path) -> &str {
    path.file_name()
        .and_then(|name| name.to_str())
        .unwrap_or_default()
}

/// The files of the folder that match a pattern, where `*` stands for any text within a name.
pub fn files(folder: &Path, pattern: &str) -> Vec<PathBuf> {
    let parts: Vec<&str> = pattern
        .split('/')
        .filter(|part| !part.is_empty() && *part != ".")
        .collect();
    let Some((last, folders)) = parts.split_last() else {
        return Vec::new();
    };
    let mut places = vec![folder.to_owned()];
    for part in folders {
        places = places
            .iter()
            .flat_map(|place| {
                if part.contains('*') {
                    entries(place)
                        .into_iter()
                        .filter(|entry| entry.is_dir() && matches(part, name(entry)))
                        .collect()
                } else {
                    let next = place.join(part);
                    if next.is_dir() {
                        vec![next]
                    } else {
                        Vec::new()
                    }
                }
            })
            .collect();
    }
    places
        .iter()
        .flat_map(|place| {
            entries(place)
                .into_iter()
                .filter(|entry| entry.is_file() && matches(last, name(entry)))
        })
        .collect()
}

/// A fingerprint of everything the folder holds, leaving out the runner's own `.vpf` and `.git` folders.
pub fn digest(folder: &Path) -> u64 {
    fn walk(path: &Path, base: &Path, hasher: &mut DefaultHasher) {
        for entry in entries(path) {
            let entry_name = name(&entry);
            if entry_name == ".git" || (path == base && entry_name == ".vpf") {
                continue;
            }
            entry.strip_prefix(base).unwrap_or(&entry).hash(hasher);
            if entry.is_dir() {
                walk(&entry, base, hasher);
            } else {
                fs::read(&entry).unwrap_or_default().hash(hasher);
            }
        }
    }
    let mut hasher = DefaultHasher::new();
    walk(folder, folder, &mut hasher);
    hasher.finish()
}

/// The largest file whose text a snapshot keeps, in bytes.
const TEXT_LIMIT: u64 = 64 * 1024;
/// The most text one snapshot keeps, in bytes.
const TEXTS_LIMIT: u64 = 8 * 1024 * 1024;
/// The most lines of changes shown for one file.
const FILE_LINES: usize = 80;
/// The most lines of changes shown in all.
const ALL_LINES: usize = 400;

/// A file as a snapshot saw it: its size, when it last changed and, for a small text file, what it says.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Seen {
    size: u64,
    modified: Option<SystemTime>,
    text: Option<Arc<str>>,
}

/// What each file of the folder is now, by its path in the folder: its size, when it last changed and the text of
/// small text files, leaving out the runner's own `.vpf` and `.git` folders. Cheap enough to take before each piece of
/// work.
pub fn snapshot(folder: &Path) -> Snapshot {
    fn walk(path: &Path, base: &Path, files: &mut Snapshot, kept: &mut u64) {
        for entry in entries(path) {
            let entry_name = name(&entry);
            if entry_name == ".git" || (path == base && entry_name == ".vpf") {
                continue;
            }
            if entry.is_dir() {
                walk(&entry, base, files, kept);
            } else if let Ok(meta) = fs::metadata(&entry) {
                let relative = entry.strip_prefix(base).unwrap_or(&entry);
                let path = relative.to_string_lossy().replace('\\', "/");
                let text = (meta.len() <= TEXT_LIMIT && *kept + meta.len() <= TEXTS_LIMIT)
                    .then(|| fs::read(&entry).ok())
                    .flatten()
                    .filter(|bytes| !bytes.contains(&0))
                    .and_then(|bytes| String::from_utf8(bytes).ok())
                    .map(Arc::<str>::from);
                if let Some(text) = &text {
                    *kept += text.len() as u64;
                }
                files.insert(
                    path,
                    Seen {
                        size: meta.len(),
                        modified: meta.modified().ok(),
                        text,
                    },
                );
            }
        }
    }
    let mut files = Snapshot::new();
    walk(folder, folder, &mut files, &mut 0);
    files
}

/// Each file of a folder, by its path.
pub type Snapshot = BTreeMap<String, Seen>;

/// The paths of the files added, changed or removed since `before`, in order.
pub fn changed(before: &Snapshot, now: &Snapshot) -> Vec<String> {
    let mut paths: Vec<String> = now
        .iter()
        .filter(|(path, file)| before.get(*path) != Some(*file))
        .map(|(path, _)| path.clone())
        .chain(
            before
                .keys()
                .filter(|path| !now.contains_key(*path))
                .cloned(),
        )
        .collect();
    paths.sort();
    paths
}

/// The lines removed and added in the text files of `paths` between two snapshots, as a unified diff. A file that was
/// not text, or too large to keep, on either side is left out; so are lines past the limits, which are counted.
pub fn changes(before: &Snapshot, now: &Snapshot, paths: &[String]) -> String {
    let mut shown = String::new();
    let mut lines = 0;
    let mut left = 0;
    for path in paths {
        let text = |snapshot: &Snapshot| snapshot.get(path).map(|seen| seen.text.clone());
        let (old, new) = match (text(before), text(now)) {
            (Some(Some(old)), Some(Some(new))) => (old, new),
            (None, Some(Some(new))) => (Arc::from(""), new),
            (Some(Some(old)), None) => (old, Arc::from("")),
            _ => continue,
        };
        let diff = TextDiff::from_lines(&*old, &*new);
        let unified = diff
            .unified_diff()
            .context_radius(2)
            .header(&format!("a/{path}"), &format!("b/{path}"))
            .to_string();
        for (at, line) in unified.lines().enumerate() {
            if at < FILE_LINES && lines < ALL_LINES {
                shown.push_str(line);
                shown.push('\n');
                lines += 1;
            } else {
                left += 1;
            }
        }
    }
    if left > 0 {
        let _ = writeln!(shown, "({left} more lines of changes are not shown)");
    }
    shown
}

/// What the files that match some patterns hold, by path.
pub fn contents(folder: &Path, patterns: &[String]) -> BTreeMap<PathBuf, u64> {
    patterns
        .iter()
        .flat_map(|pattern| files(folder, pattern))
        .map(|file| {
            let mut hasher = DefaultHasher::new();
            fs::read(&file).unwrap_or_default().hash(&mut hasher);
            (file, hasher.finish())
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use super::{changed, changes, inside, matches, snapshot};

    #[test]
    fn a_star_stands_for_any_text() {
        assert!(matches("*.md", "report.md"));
        assert!(matches("report-*-final.md", "report-2026-final.md"));
        assert!(matches("*", ""));
        assert!(matches("a*a", "aa"));
        assert!(!matches("a*a", "a"));
        assert!(!matches("*.md", "report.txt"));
        assert!(!matches("report.md", "report.mdx"));
    }

    #[test]
    fn paths_stay_inside() {
        assert!(inside("reports/march.md"));
        assert!(inside("a..b/c"));
        for path in ["", " ", "/a", "\\a", "C:/a", "c:a", "a/../b", "..\\a"] {
            assert!(!inside(path), "{path}");
        }
    }

    #[test]
    fn the_files_changed_are_told_apart_from_the_rest() {
        let folder = tempfile::tempdir().expect("a folder");
        let path = folder.path();
        std::fs::write(path.join("kept.txt"), "kept").expect("a file");
        std::fs::write(path.join("gone.txt"), "gone").expect("a file");
        std::fs::create_dir_all(path.join(".vpf")).expect("a folder");
        let before = snapshot(path);
        std::fs::write(path.join("new.txt"), "new").expect("a file");
        std::fs::remove_file(path.join("gone.txt")).expect("removed");
        std::fs::write(path.join(".vpf/run.json"), "{}").expect("a file");
        assert_eq!(changed(&before, &snapshot(path)), ["gone.txt", "new.txt"]);
    }

    #[test]
    fn the_lines_changed_are_shown_up_to_a_limit() {
        let folder = tempfile::tempdir().expect("a folder");
        let path = folder.path();
        let lines = |word: &str| {
            let mut text = String::new();
            for n in 0..200 {
                let _ = writeln!(text, "{word} {n}");
            }
            text
        };
        std::fs::write(path.join("long.txt"), lines("old")).expect("a file");
        std::fs::write(path.join("data.bin"), [0_u8, 1]).expect("a file");
        let before = snapshot(path);
        std::fs::write(path.join("long.txt"), lines("new")).expect("a file");
        std::fs::write(path.join("data.bin"), [0_u8, 2]).expect("a file");
        let now = snapshot(path);
        let shown = changes(&before, &now, &changed(&before, &now));
        assert!(
            shown.contains("-old 0\n+new 0\n") || shown.contains("-old 0\n"),
            "{shown}"
        );
        assert!(!shown.contains("data.bin"), "{shown}");
        assert!(shown.lines().count() <= 81, "{shown}");
        assert!(
            shown.ends_with("more lines of changes are not shown)\n"),
            "{shown}"
        );
    }
}