Skip to content

Commit

Permalink
add keep support to TempDir
Browse files Browse the repository at this point in the history
This patch adds keep() support to TempDir. Rather than
using mem::forget() tricks like NamedTempFile does, it just
uses a flag, which I think is a little easier to follow, though
does require an extra byte of memory footprint.

Closes #194
  • Loading branch information
ethanpailes committed Oct 20, 2022
1 parent 8d50620 commit eb4372b
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ pub fn tempdir_in<P: AsRef<Path>>(dir: P) -> io::Result<TempDir> {
/// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
pub struct TempDir {
path: Box<Path>,
disowned: bool,
}

impl TempDir {
Expand Down Expand Up @@ -386,6 +387,37 @@ impl TempDir {

result
}

/// Marks this directory so that it will not get cleaned up when the rust
/// object is dropped.
///
/// # Examples
/// ```
/// use std::fs;
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let mut tmp_dir = TempDir::new()?;
///
/// let file_path = tmp_dir.path().join("disowned-file.txt");
/// let mut tmp_file = File::create(&file_path)?;
/// writeln!(tmp_file, "some text")?;
///
/// tmp_dir.keep(); // consumes tmp_dir struct
///
/// assert_eq!(fs::read_to_string(&file_path)?, "some text");
///
/// # let _ = fs::remove_dir_all(file_path.parent().unwrap());
/// #
/// # Ok(())
/// # }
/// ```
pub fn keep(mut self) {
self.disowned = true;
}
}

impl AsRef<Path> for TempDir {
Expand All @@ -404,7 +436,9 @@ impl fmt::Debug for TempDir {

impl Drop for TempDir {
fn drop(&mut self) {
let _ = remove_dir_all(self.path());
if !self.disowned {
let _ = remove_dir_all(self.path());
}
}
}

Expand All @@ -413,5 +447,6 @@ pub(crate) fn create(path: PathBuf) -> io::Result<TempDir> {
.with_err_path(|| &path)
.map(|_| TempDir {
path: path.into_boxed_path(),
disowned: false,
})
}

0 comments on commit eb4372b

Please sign in to comment.