tmp.rs
1 use std::{fs, ops::Deref, path::Path}; 2 3 pub struct TmpDir { 4 path: Box<Path>, 5 } 6 7 impl TmpDir { 8 pub fn create(path: Box<Path>) -> Self { 9 fs::create_dir_all(&path).expect("Failed to create temporary directory: {}"); 10 Self { path } 11 } 12 13 pub fn keep(self) -> Box<Path> { 14 let path = self.path.clone(); 15 16 // Skip the destructor 17 std::mem::forget(self); 18 19 log::debug!("Keeping sandbox temporary directory at {}", path.display()); 20 path 21 } 22 23 pub fn as_path(&self) -> &Path { 24 self.path.as_ref() 25 } 26 } 27 28 impl Deref for TmpDir { 29 type Target = Path; 30 31 fn deref(&self) -> &Self::Target { 32 &self.path 33 } 34 } 35 36 impl Drop for TmpDir { 37 fn drop(&mut self) { 38 if let Err(err) = fs::remove_dir_all(&self.path) { 39 log::error!( 40 "Failed to delete temporary directory {}: {err}", 41 self.path.display() 42 ); 43 } 44 } 45 }