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
39
use cargo::util::CargoResult;
use std::fs::{self, File};
use std::path::PathBuf;

/// Temporary file implementation that allows creating a file with a specified path which
/// will be deleted when dropped.
pub struct TempFile {
    pub path: PathBuf,
}

impl TempFile {
    /// Create a new `TempFile` using the contents provided by a closure.
    /// If the file already exists, it will be overwritten and then deleted when the instance
    /// is dropped.
    pub fn new<F>(path: PathBuf, write_contents: F) -> CargoResult<TempFile>
    where
        F: FnOnce(&mut File) -> CargoResult<()>,
    {
        let tmp_file = TempFile { path };

        // Write the contents to the the temp file
        let mut file = File::create(&tmp_file.path)?;
        write_contents(&mut file)?;

        Ok(tmp_file)
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        fs::remove_file(&self.path).unwrap_or_else(|e| {
            eprintln!(
                "Unable to remove temporary file: {}. {}",
                &self.path.to_string_lossy(),
                &e
            );
        })
    }
}