use std::path::{Path, PathBuf};
pub struct TempFileGuard {
path: Option<PathBuf>,
}
impl TempFileGuard {
pub fn new(path: impl AsRef<Path>) -> Self {
Self { path: Some(path.as_ref().to_path_buf()) }
}
pub fn defuse(mut self) {
self.path = None;
}
#[allow(dead_code)]
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
}
impl Drop for TempFileGuard {
fn drop(&mut self) {
if let Some(path) = &self.path {
if path.exists() {
let _ = std::fs::remove_file(path);
tracing::debug!("Cleaned up temporary file: {}", path.display());
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_temp_file_guard_cleans_up() {
let temp_dir = TempDir::new().unwrap();
let temp_path = temp_dir.path().join("test.tmp");
fs::write(&temp_path, b"test data").unwrap();
assert!(temp_path.exists());
{
let _guard = TempFileGuard::new(&temp_path);
}
assert!(!temp_path.exists());
}
#[test]
fn test_temp_file_guard_defuse() {
let temp_dir = TempDir::new().unwrap();
let temp_path = temp_dir.path().join("test.tmp");
fs::write(&temp_path, b"test data").unwrap();
assert!(temp_path.exists());
{
let guard = TempFileGuard::new(&temp_path);
guard.defuse();
}
assert!(temp_path.exists());
}
#[test]
fn test_temp_file_guard_nonexistent_file() {
let temp_dir = TempDir::new().unwrap();
let temp_path = temp_dir.path().join("nonexistent.tmp");
{
let _guard = TempFileGuard::new(&temp_path);
}
assert!(!temp_path.exists());
}
#[test]
fn test_temp_file_guard_path() {
let temp_dir = TempDir::new().unwrap();
let temp_path = temp_dir.path().join("test.tmp");
let guard = TempFileGuard::new(&temp_path);
assert_eq!(guard.path(), Some(temp_path.as_path()));
guard.defuse();
}
}