Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add stored parent_dir builder parameter #308

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,29 +171,31 @@ pub use crate::spooled::{spooled_tempfile, SpooledData, SpooledTempFile};

/// Create a new temporary file or directory with custom parameters.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Builder<'a, 'b> {
pub struct Builder<'a, 'b, 'c> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a breaking change. IMO, I messed up and should have had just one lifetime here (relying on sub-typing) but fixing that would also be a breaking change.

We can do one of:

  1. Re-use one of the other lifetimes.
  2. Store the directory by-value (although I'd still take the parameter as AsRef).

I'd go with the former approach (probably using the prefix's lifetime, 'a. It's a bit awkward but it provides the best upgrade path for an eventual v4.

random_len: usize,
prefix: &'a OsStr,
suffix: &'b OsStr,
dir: Option<&'c Path>,
append: bool,
permissions: Option<std::fs::Permissions>,
keep: bool,
}

impl<'a, 'b> Default for Builder<'a, 'b> {
impl<'a, 'b, 'c> Default for Builder<'a, 'b, 'c> {
fn default() -> Self {
Builder {
random_len: crate::NUM_RAND_CHARS,
prefix: OsStr::new(".tmp"),
suffix: OsStr::new(""),
dir: None, // Use env::temp_dir().
append: false,
permissions: None,
keep: false,
}
}
}

impl<'a, 'b> Builder<'a, 'b> {
impl<'a, 'b, 'c> Builder<'a, 'b, 'c> {
/// Create a new `Builder`.
///
/// # Examples
Expand Down Expand Up @@ -304,6 +306,28 @@ impl<'a, 'b> Builder<'a, 'b> {
self
}

/// Set a directory to create files in.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Set a directory to create files in.
/// Set the default directory in which temporary files/directories will be created.

///
/// This is an alternative API that achieves essentially the same thing as
/// `tempfile_in` and `tempdir_in`.
///
/// Default: `env::temp_dir()`
///
/// # Examples
/// ```
/// use tempfile::Builder;
/// use tempfile::tempdir;
///
/// let parent = tempdir()?;
/// let tempfile_in_parent = Builder::new()
/// .parent_dir(parent.path())
/// .tempfile()?;
/// # Ok::<(), std::io::Error>(())
pub fn parent_dir<P: AsRef<Path> + ?Sized>(&mut self, dir: &'c P) -> &mut Self {
self.dir = Some(dir.as_ref());
self
}

/// Set the number of random bytes.
///
/// Default: `6`.
Expand Down Expand Up @@ -461,7 +485,7 @@ impl<'a, 'b> Builder<'a, 'b> {
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
self.tempfile_in(env::temp_dir())
self.tempfile_in(self.dir.unwrap_or(&env::temp_dir()))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a documentation update here and below.

}

/// Create the named temporary file in the specified directory.
Expand Down Expand Up @@ -530,7 +554,7 @@ impl<'a, 'b> Builder<'a, 'b> {
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir(&self) -> io::Result<TempDir> {
self.tempdir_in(env::temp_dir())
self.tempdir_in(self.dir.unwrap_or(&env::temp_dir()))
}

/// Attempts to make a temporary directory inside of `dir`.
Expand Down
14 changes: 14 additions & 0 deletions tests/tempdir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ fn test_suffix() {
assert!(name.ends_with("suffix"));
}

fn test_stored_parent_dir() {
let parent = TempDir::new().unwrap();
let child = Builder::new().parent_dir(parent.path()).tempdir().unwrap();
let path_str = child.path().to_str().unwrap();
assert!(
path_str.starts_with(child.path().to_str().unwrap()),
"{:?} not in {:?}",
child,
parent
);
}

fn test_customnamed() {
let tmpfile = Builder::new()
.prefix("prefix")
Expand Down Expand Up @@ -182,6 +194,8 @@ fn main() {
in_tmpdir(test_tempdir);
in_tmpdir(test_prefix);
in_tmpdir(test_suffix);
in_tmpdir(test_suffix);
in_tmpdir(test_stored_parent_dir);
in_tmpdir(test_customnamed);
in_tmpdir(test_rm_tempdir);
in_tmpdir(test_rm_tempdir_close);
Expand Down
16 changes: 16 additions & 0 deletions tests/tempfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use std::{
thread,
};

use tempfile::{Builder, TempDir};

#[test]
fn test_basic() {
let mut tmpfile = tempfile::tempfile().unwrap();
Expand All @@ -18,6 +20,20 @@ fn test_basic() {
assert_eq!("abcde", buf);
}

#[test]
fn test_stored_parent_dir() {
let parent = TempDir::new().unwrap();
let child = Builder::new().parent_dir(parent.path()).tempfile().unwrap();
let path_str = child.path().to_str().unwrap();
assert!(
path_str.starts_with(child.path().to_str().unwrap()),
"{:?} not in {:?}",
child,
parent
);
}


#[test]
fn test_cleanup() {
let tmpdir = tempfile::tempdir().unwrap();
Expand Down