Repository: Stebalien/tempfile
Pull request #253 (2023-08-18 21:46:41)

chore: more test cleanups


Patch:
diff --git a/src/dir.rs b/src/dir.rs
index 483b6d8..1b79be4 100644
--- a/src/dir.rs
+++ b/src/dir.rs
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use std::ffi::OsStr;
 use std::fs::remove_dir_all;
 use std::mem;
 use std::path::{self, Path, PathBuf};
@@ -264,6 +265,65 @@ impl TempDir {
         Builder::new().tempdir_in(dir)
     }
 
+    /// Attempts to make a temporary directory with the specified prefix inside of
+    /// `env::temp_dir()`. The directory and everything inside it will be automatically
+    /// deleted once the returned `TempDir` is destroyed.
+    ///
+    /// # Errors
+    ///
+    /// If the directory can not be created, `Err` is returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::fs::{self, File};
+    /// use std::io::Write;
+    /// use tempfile::TempDir;
+    ///
+    /// # use std::io;
+    /// # fn run() -> Result<(), io::Error> {
+    /// // Create a directory inside of the current directory
+    /// let tmp_dir = TempDir::with_prefix("foo-")?;
+    /// let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap();
+    /// assert!(tmp_name.starts_with("foo-"));
+    /// # Ok(())
+    /// # }
+    /// ```
+    pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<TempDir> {
+        Builder::new().prefix(&prefix).tempdir()
+    }
+
+    /// Attempts to make a temporary directory with the specified prefix inside
+    /// the specified directory. The directory and everything inside it will be
+    /// automatically deleted once the returned `TempDir` is destroyed.
+    ///
+    /// # Errors
+    ///
+    /// If the directory can not be created, `Err` is returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::fs::{self, File};
+    /// use std::io::Write;
+    /// use tempfile::TempDir;
+    ///
+    /// # use std::io;
+    /// # fn run() -> Result<(), io::Error> {
+    /// // Create a directory inside of the current directory
+    /// let tmp_dir = TempDir::with_prefix_in("foo-", ".")?;
+    /// let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap();
+    /// assert!(tmp_name.starts_with("foo-"));
+    /// # Ok(())
+    /// # }
+    /// ```
+    pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
+        prefix: S,
+        dir: P,
+    ) -> io::Result<TempDir> {
+        Builder::new().prefix(&prefix).tempdir_in(dir)
+    }
+
     /// Accesses the [`Path`] to the temporary directory.
     ///
     /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
diff --git a/src/file/mod.rs b/src/file/mod.rs
index d0aa150..aca44ce 100644
--- a/src/file/mod.rs
+++ b/src/file/mod.rs
@@ -608,12 +608,45 @@ impl NamedTempFile<File> {
 
     /// Create a new named temporary file in the specified directory.
     ///
+    /// This is equivalent to:
+    ///
+    /// ```ignore
+    /// Builder::new().prefix(&prefix).tempfile()
+    /// ```
+    ///
     /// See [`NamedTempFile::new()`] for details.
     ///
     /// [`NamedTempFile::new()`]: #method.new
     pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> {
         Builder::new().tempfile_in(dir)
     }
+
+    /// Create a new named temporary file with the specified filename prefix.
+    ///
+    /// See [`NamedTempFile::new()`] for details.
+    ///
+    /// [`NamedTempFile::new()`]: #method.new
+    pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> {
+        Builder::new().prefix(&prefix).tempfile()
+    }
+    /// Create a new named temporary file with the specified filename prefix,
+    /// in the specified directory.
+    ///
+    /// This is equivalent to:
+    ///
+    /// ```ignore
+    /// Builder::new().prefix(&prefix).tempfile_in(directory)
+    /// ```
+    ///
+    /// See [`NamedTempFile::new()`] for details.
+    ///
+    /// [`NamedTempFile::new()`]: #method.new
+    pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
+        prefix: S,
+        dir: P,
+    ) -> io::Result<NamedTempFile> {
+        Builder::new().prefix(&prefix).tempfile_in(dir)
+    }
 }
 
 impl<F> NamedTempFile<F> {


Test patch:
diff --git a/tests/namedtempfile.rs b/tests/namedtempfile.rs
index 54396c3..4b940b6 100644
--- a/tests/namedtempfile.rs
+++ b/tests/namedtempfile.rs
@@ -11,6 +11,13 @@ fn exists<P: AsRef<Path>>(path: P) -> bool {
     std::fs::metadata(path.as_ref()).is_ok()
 }
 
+#[test]
+fn test_prefix() {
+    let tmpfile = NamedTempFile::with_prefix("prefix").unwrap();
+    let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
+    assert!(name.starts_with("prefix"));
+}
+
 #[test]
 fn test_basic() {
     let mut tmpfile = NamedTempFile::new().unwrap();
diff --git a/tests/tempdir.rs b/tests/tempdir.rs
index 898aba3..8ca7984 100644
--- a/tests/tempdir.rs
+++ b/tests/tempdir.rs
@@ -18,32 +18,9 @@ use std::thread;
 
 use tempfile::{Builder, TempDir};
 
-macro_rules! t {
-    ($e:expr) => {
-        match $e {
-            Ok(n) => n,
-            Err(e) => panic!("error: {}", e),
-        }
-    };
-}
-
-trait PathExt {
-    fn exists(&self) -> bool;
-    fn is_dir(&self) -> bool;
-}
-
-impl PathExt for Path {
-    fn exists(&self) -> bool {
-        fs::metadata(self).is_ok()
-    }
-    fn is_dir(&self) -> bool {
-        fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
-    }
-}
-
 fn test_tempdir() {
     let path = {
-        let p = t!(Builder::new().prefix("foobar").tempdir_in(Path::new(".")));
+        let p = Builder::new().prefix("foobar").tempdir_in(".").unwrap();
         let p = p.path();
         assert!(p.to_str().unwrap().contains("foobar"));
         p.to_path_buf()
@@ -51,6 +28,12 @@ fn test_tempdir() {
     assert!(!path.exists());
 }
 
+fn test_prefix() {
+    let tmpfile = TempDir::with_prefix_in("prefix", ".").unwrap();
+    let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
+    assert!(name.starts_with("prefix"));
+}
+
 fn test_customnamed() {
     let tmpfile = Builder::new()
         .prefix("prefix")
@@ -67,7 +50,7 @@ fn test_customnamed() {
 fn test_rm_tempdir() {
     let (tx, rx) = channel();
     let f = move || {
-        let tmp = t!(TempDir::new());
+        let tmp = TempDir::new().unwrap();
         tx.send(tmp.path().to_path_buf()).unwrap();
         panic!("panic to unwind past `tmp`");
     };
@@ -75,7 +58,7 @@ fn test_rm_tempdir() {
     let path = rx.recv().unwrap();
     assert!(!path.exists());
 
-    let tmp = t!(TempDir::new());
+    let tmp = TempDir::new().unwrap();
     let path = tmp.path().to_path_buf();
     let f = move || {
         let _tmp = tmp;
@@ -86,7 +69,7 @@ fn test_rm_tempdir() {
 
     let path;
     {
-        let f = move || t!(TempDir::new());
+        let f = move || TempDir::new().unwrap();
 
         let tmp = thread::spawn(f).join().unwrap();
         path = tmp.path().to_path_buf();
@@ -96,31 +79,31 @@ fn test_rm_tempdir() {
 
     let path;
     {
-        let tmp = t!(TempDir::new());
+        let tmp = TempDir::new().unwrap();
         path = tmp.into_path();
     }
     assert!(path.exists());
-    t!(fs::remove_dir_all(&path));
+    fs::remove_dir_all(&path).unwrap();
     assert!(!path.exists());
 }
 
 fn test_rm_tempdir_close() {
     let (tx, rx) = channel();
     let f = move || {
-        let tmp = t!(TempDir::new());
+        let tmp = TempDir::new().unwrap();
         tx.send(tmp.path().to_path_buf()).unwrap();
-        t!(tmp.close());
+        tmp.close().unwrap();
         panic!("panic when unwinding past `tmp`");
     };
     let _ = thread::spawn(f).join();
     let path = rx.recv().unwrap();
     assert!(!path.exists());
 
-    let tmp = t!(TempDir::new());
+    let tmp = TempDir::new().unwrap();
     let path = tmp.path().to_path_buf();
     let f = move || {
         let tmp = tmp;
-        t!(tmp.close());
+        tmp.close().unwrap();
         panic!("panic when unwinding past `tmp`");
     };
     let _ = thread::spawn(f).join();
@@ -128,22 +111,22 @@ fn test_rm_tempdir_close() {
 
     let path;
     {
-        let f = move || t!(TempDir::new());
+        let f = move || TempDir::new().unwrap();
 
         let tmp = thread::spawn(f).join().unwrap();
         path = tmp.path().to_path_buf();
         assert!(path.exists());
-        t!(tmp.close());
+        tmp.close().unwrap();
     }
     assert!(!path.exists());
 
     let path;
     {
-        let tmp = t!(TempDir::new());
+        let tmp = TempDir::new().unwrap();
         path = tmp.into_path();
     }
     assert!(path.exists());
-    t!(fs::remove_dir_all(&path));
+    fs::remove_dir_all(&path).unwrap();
     assert!(!path.exists());
 }
 
@@ -152,7 +135,7 @@ fn dont_double_panic() {
         let tmpdir = TempDir::new().unwrap();
         // Remove the temporary directory so that TempDir sees
         // an error on drop
-        t!(fs::remove_dir(tmpdir.path()));
+        fs::remove_dir(tmpdir.path()).unwrap();
         // Panic. If TempDir panics *again* due to the rmdir
         // error then the process will abort.
         panic!();
@@ -165,14 +148,14 @@ fn in_tmpdir<F>(f: F)
 where
     F: FnOnce(),
 {
-    let tmpdir = t!(TempDir::new());
+    let tmpdir = TempDir::new().unwrap();
     assert!(env::set_current_dir(tmpdir.path()).is_ok());
 
     f();
 }
 
-pub fn pass_as_asref_path() {
-    let tempdir = t!(TempDir::new());
+fn pass_as_asref_path() {
+    let tempdir = TempDir::new().unwrap();
     takes_asref_path(&tempdir);
 
     fn takes_asref_path<T: AsRef<Path>>(path: T) {
@@ -184,6 +167,7 @@ pub fn pass_as_asref_path() {
 #[test]
 fn main() {
     in_tmpdir(test_tempdir);
+    in_tmpdir(test_prefix);
     in_tmpdir(test_customnamed);
     in_tmpdir(test_rm_tempdir);
     in_tmpdir(test_rm_tempdir_close);