#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::fs;
use std::path::Path;
use tempfile::TempDir;
#[must_use]
pub fn tree(entries: &[&str]) -> TempDir {
let root = TempDir::new().expect("a temporary directory");
build(root.path(), entries);
root
}
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");
}
}
}
#[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();
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);
}
}
}
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;
const FILE_WRITE_ATTRIBUTES: u32 = 0x0100;
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::*;
#[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:?}");
}
}