voom 0.14.1

Fast, safe, parallel build-artifact pruning across every major language ecosystem
Documentation
//! Fixture helpers shared by the unit tests and, through the `test-support` feature, the
//! integration suites.
//!
//! The unit under test in this crate is "what does voom do to a filesystem", so nothing
//! smaller than a real directory tree is convincing. Every fixture lives under a [`TempDir`] —
//! a test that reached `$HOME`, or `/tmp` directly, would be a bug regardless of whether it
//! passed.

// A panic in fixture construction *is* the failure report. Under `test-support` this module is
// compiled into the non-test lib, where clippy.toml's `allow-expect-in-tests` does not reach it.
#![allow(clippy::expect_used, clippy::unwrap_used)]

use std::fs;
use std::path::Path;

use tempfile::TempDir;

/// Builds a fixture tree in a fresh temporary directory.
///
/// An entry ending in `/` becomes a directory; anything else becomes a file with placeholder
/// contents, and its parent directories are created for it.
///
/// # Panics
///
/// If the tree cannot be built, which means the test environment is broken.
#[must_use]
pub fn tree(entries: &[&str]) -> TempDir {
    let root = TempDir::new().expect("a temporary directory");
    build(root.path(), entries);
    root
}

/// Adds entries to an existing tree.
///
/// # Panics
///
/// If an entry cannot be created.
pub fn build(root: &Path, entries: &[&str]) {
    for entry in entries {
        let path = root.join(entry.trim_end_matches('/'));
        if entry.ends_with('/') {
            fs::create_dir_all(&path).expect("a fixture directory");
        } else {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).expect("a fixture parent directory");
            }
            fs::write(&path, b"fixture").expect("a fixture file");
        }
    }
}

/// Every path under `root`, relative and sorted, for asserting on what a run left behind.
///
/// Directories carry a trailing `/` so a file and a directory of the same name are
/// distinguishable. Symlinks are recorded but never descended into.
///
/// # Panics
///
/// If a path cannot be rendered.
#[must_use]
pub fn snapshot(root: &Path) -> Vec<String> {
    let mut paths = Vec::new();
    collect(root, root, &mut paths);
    paths.sort();
    paths
}

fn collect(root: &Path, dir: &Path, paths: &mut Vec<String>) {
    let Ok(entries) = fs::read_dir(dir) else { return };
    for entry in entries.flatten() {
        let path = entry.path();
        // Callers assert against `/`-separated literals, and `display()` renders the platform's
        // separator — on Windows every one of those assertions would fail for a reason that has
        // nothing to do with the behaviour under test.
        let relative = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .display()
            .to_string()
            .replace(std::path::MAIN_SEPARATOR, "/");
        let file_type = entry.file_type();
        let is_symlink = file_type.as_ref().is_ok_and(std::fs::FileType::is_symlink);
        let is_dir = file_type.as_ref().is_ok_and(std::fs::FileType::is_dir);
        paths.push(if is_dir { format!("{relative}/") } else { relative });
        if is_dir && !is_symlink {
            collect(root, &path, paths);
        }
    }
}

/// Sets a path's modification time, whether it is a file or a directory.
///
/// A directory has to be ageable: Bazel staleness is the *newest* of the output base and its
/// markers, so a fixture must be able to push the directory itself into the past. Unix
/// `futimens` needs only an open handle, and a read handle opens a directory. Windows
/// `SetFileTime` needs `FILE_WRITE_ATTRIBUTES`, and a directory handle additionally needs
/// `FILE_FLAG_BACKUP_SEMANTICS` — neither of which `File::open` or `OpenOptions::write`
/// supplies for a directory.
///
/// # Panics
///
/// If the time cannot be set, which means the test environment is broken.
pub fn set_modified(path: &Path, when: std::time::SystemTime) {
    open_for_time(path)
        .set_modified(when)
        .expect("a modification time can be set");
}

#[cfg(not(windows))]
fn open_for_time(path: &Path) -> fs::File {
    fs::File::open(path).expect("the path opens for its modification time")
}

#[cfg(windows)]
fn open_for_time(path: &Path) -> fs::File {
    use std::os::windows::fs::OpenOptionsExt;
    // `FILE_WRITE_ATTRIBUTES`, the access `SetFileTime` requires.
    const FILE_WRITE_ATTRIBUTES: u32 = 0x0100;
    // `FILE_FLAG_BACKUP_SEMANTICS`, required to obtain a handle to a directory.
    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
    fs::OpenOptions::new()
        .access_mode(FILE_WRITE_ATTRIBUTES)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(path)
        .expect("the path opens for its modification time")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The whole suite asserts against `/`-separated literals, so the snapshot has to produce
    /// them on every platform rather than whatever the local separator happens to be.
    #[test]
    fn should_render_snapshot_paths_with_slash_separators() {
        let fixture = tree(&["Cargo.toml", "src/main.rs", "target/debug/"]);
        let paths = snapshot(fixture.path());
        assert_eq!(
            paths,
            vec!["Cargo.toml", "src/", "src/main.rs", "target/", "target/debug/"]
        );
        assert!(paths.iter().all(|path| !path.contains('\\')), "{paths:?}");
    }
}