daipendency_testing/
tempdir.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//! Management of temporary directories.

use std::io::Write;
use std::{fs::File, io::Error, path::PathBuf};

use tempfile::TempDir as UpstreamTempDir;

/// A temporary directory.
pub struct TempDir {
    temp_dir: UpstreamTempDir,
    /// The path to the temporary directory.
    pub path: PathBuf,
}

impl Default for TempDir {
    fn default() -> Self {
        Self::new()
    }
}

impl TempDir {
    pub fn new() -> Self {
        let temp_dir = UpstreamTempDir::new().unwrap();
        let path = temp_dir.path().to_path_buf();
        Self { temp_dir, path }
    }

    /// Create a file in the temporary directory.
    pub fn create_file(&self, path: &str, content: &str) -> Result<PathBuf, Error> {
        let file_path = self.temp_dir.path().join(path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        let mut file = File::create(&file_path)?;
        write!(file, "{}", content)?;
        Ok(file_path)
    }
}