daipendency_testing/
tempdir.rs

1//! Management of temporary directories.
2
3use std::io::Write;
4use std::{fs::File, io::Error, path::PathBuf};
5
6use tempfile::TempDir as UpstreamTempDir;
7
8/// A temporary directory.
9pub struct TempDir {
10    temp_dir: UpstreamTempDir,
11    /// The path to the temporary directory.
12    pub path: PathBuf,
13}
14
15impl Default for TempDir {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl TempDir {
22    pub fn new() -> Self {
23        let temp_dir = UpstreamTempDir::new().unwrap();
24        let path = temp_dir.path().to_path_buf();
25        Self { temp_dir, path }
26    }
27
28    /// Create a file in the temporary directory.
29    pub fn create_file(&self, path: &str, content: &str) -> Result<PathBuf, Error> {
30        let file_path = self.temp_dir.path().join(path);
31        if let Some(parent) = file_path.parent() {
32            std::fs::create_dir_all(parent).unwrap();
33        }
34        let mut file = File::create(&file_path)?;
35        write!(file, "{}", content)?;
36        Ok(file_path)
37    }
38}