use crate::utils::fs::dirs::{ensure_dir, remove_dir_all};
use anyhow::Result;
use std::path::{Path, PathBuf};
pub struct TempDir {
path: PathBuf,
}
impl TempDir {
pub fn new(prefix: &str) -> Result<Self> {
let temp_dir = std::env::temp_dir();
let unique_name = format!("agpm_{}_{}", prefix, uuid::Uuid::new_v4());
let path = temp_dir.join(unique_name);
ensure_dir(&path)?;
Ok(Self {
path,
})
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = remove_dir_all(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_temp_dir() {
let temp_dir = TempDir::new("test").unwrap();
let path = temp_dir.path().to_path_buf();
assert!(path.exists());
assert!(path.is_dir());
std::fs::write(path.join("test.txt"), "test").unwrap();
assert!(path.join("test.txt").exists());
drop(temp_dir);
assert!(!path.exists());
}
#[test]
fn test_temp_dir_custom_prefix() {
let temp1 = TempDir::new("prefix1").unwrap();
let temp2 = TempDir::new("prefix2").unwrap();
assert!(temp1.path().to_string_lossy().contains("prefix1"));
assert!(temp2.path().to_string_lossy().contains("prefix2"));
let path1 = temp1.path().to_path_buf();
let path2 = temp2.path().to_path_buf();
assert_ne!(path1, path2);
assert!(path1.exists());
assert!(path2.exists());
}
}