#![expect(clippy::let_underscore_must_use, reason = "removing what is already meant to be gone")]
#![warn(missing_docs)]
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
pub fn unique_dir(label: &str) -> PathBuf {
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let p = std::env::temp_dir().join(format!("kevy-{label}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p)
.expect("a caller with nowhere to put its files has nothing to do next");
p
}
#[derive(Debug)]
pub struct TmpDir(PathBuf);
impl TmpDir {
pub fn new(label: &str) -> Self {
Self(unique_dir(label))
}
pub fn path(&self) -> &Path {
&self.0
}
pub fn close(mut self) -> std::io::Result<()> {
let path = std::mem::take(&mut self.0);
std::fs::remove_dir_all(path)
}
}
impl AsRef<Path> for TmpDir {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl Drop for TmpDir {
fn drop(&mut self) {
if !self.0.as_os_str().is_empty() {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
const _: () = {
const fn send_sync<T: Send + Sync>() {}
send_sync::<TmpDir>();
};
#[cfg(test)]
mod tests {
use super::TmpDir;
use std::collections::HashSet;
#[test]
fn two_dirs_in_one_process_are_different() {
let a = TmpDir::new("x");
let b = TmpDir::new("x");
assert_ne!(a.path(), b.path());
}
#[test]
fn threads_racing_for_a_name_all_get_their_own() {
let dirs: Vec<_> = std::thread::scope(|s| {
let handles: Vec<_> =
(0..32).map(|_| s.spawn(|| TmpDir::new("race").path().to_path_buf())).collect();
handles.into_iter().map(|h| h.join().expect("thread")).collect()
});
let uniq: HashSet<_> = dirs.iter().collect();
assert_eq!(uniq.len(), 32, "two threads got the same directory");
}
#[test]
fn the_directory_exists_and_then_does_not() {
let p = {
let d = TmpDir::new("drop");
assert!(d.path().is_dir());
d.path().to_path_buf()
};
assert!(!p.exists(), "TmpDir did not clean up after itself");
}
#[test]
fn close_removes_the_tree_and_reports_a_failure() {
let d = TmpDir::new("close");
let p = d.path().to_path_buf();
std::fs::create_dir(p.join("sub")).unwrap();
std::fs::write(p.join("sub/f"), b"x").unwrap();
d.close().unwrap();
assert!(!p.exists(), "close left the directory behind");
let gone = TmpDir::new("close-gone");
std::fs::remove_dir_all(gone.path()).unwrap();
let err = gone.close().unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
}
}