Skip to main content

acorn/io/
temporary.rs

1//! Automatically cleaned temporary directories.
2use crate::io::ApiResult;
3use crate::prelude::{create_dir_all, remove_dir_all, temp_dir, Path, PathBuf};
4use color_eyre::eyre::eyre;
5use nanoid::nanoid;
6
7/// A uniquely named temporary directory removed when dropped
8#[derive(Debug)]
9pub struct TemporaryDirectory(PathBuf);
10impl TemporaryDirectory {
11    /// Creates a temporary directory using `namespace` in its name
12    pub fn create(namespace: &str) -> ApiResult<Self> {
13        let path = temp_dir().join(format!("{namespace}-{}", nanoid!()));
14        create_dir_all(&path)
15            .map(|()| Self(path))
16            .map_err(|why| eyre!("Failed to create temporary directory — {why}"))
17    }
18    /// Returns the temporary directory path
19    pub fn path(&self) -> &Path {
20        &self.0
21    }
22}
23impl AsRef<Path> for TemporaryDirectory {
24    fn as_ref(&self) -> &Path {
25        self.path()
26    }
27}
28impl Drop for TemporaryDirectory {
29    fn drop(&mut self) {
30        let _ = remove_dir_all(&self.0);
31    }
32}