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