### parent Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates retrieving the parent of a Path. ```rust use std::path::Path; let path = Path::new("/foo/bar"); let parent = path.parent().unwrap(); assert_eq!(parent, Path::new("/foo")); let grand_parent = parent.parent().unwrap(); assert_eq!(grand_parent, Path::new("/")); assert_eq!(grand_parent.parent(), None); let relative_path = Path::new("foo/bar"); let parent = relative_path.parent(); assert_eq!(parent, Some(Path::new("foo"))); let grand_parent = parent.and_then(Path::parent); assert_eq!(grand_parent, Some(Path::new(""))); let great_grand_parent = grand_parent.and_then(Path::parent); assert_eq!(great_grand_parent, None); ``` -------------------------------- ### to_path_buf Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates converting a Path to an owned PathBuf. ```rust use std::path::{Path, PathBuf}; let path_buf = Path::new("foo.txt").to_path_buf(); assert_eq!(path_buf, PathBuf::from("foo.txt")); ``` -------------------------------- ### Unix socket creation with Builder::make Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html An example of using Builder::make to create a Unix socket listener. ```rust # #[cfg(unix)] # { use std::os::unix::net::UnixListener; use tempfile::Builder; let tempsock = Builder::new().make(|path| UnixListener::bind(path))?; # } # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### as_os_str Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates how to yield the underlying OsStr slice from a Path. ```rust use std::path::Path; let os_str = Path::new("foo.txt").as_os_str(); assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); ``` -------------------------------- ### Example: create and use a temporary directory Source: https://docs.rs/tempfile/latest/tempfile/fn.tempdir.html Shows how to create a temporary directory, write a file inside it, and then close it. The directory is automatically deleted when the `TempDir` goes out of scope or when `close()` is called. ```rust use tempfile::tempdir; use std::fs::File; use std::io::Write; // Create a directory inside of `env::temp_dir()` let tmp_dir = tempdir()?; let file_path = tmp_dir.path().join("my-temporary-note.txt"); let mut tmp_file = File::create(file_path)?; writeln!(tmp_file, "Brian was here. Briefly.")?; // `tmp_dir` goes out of scope, the directory as well as // `tmp_file` will be deleted here. drop(tmp_file); tmp_dir.close()?; ``` -------------------------------- ### TempDir::with_prefix usage example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory with a specified prefix. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // 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-")); ``` -------------------------------- ### Unix socket creation with Builder::make_in Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html An example of using Builder::make_in to create a Unix socket listener in a specific directory. ```rust # #[cfg(unix)] # { use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make_in("./", |path| UnixListener::bind(path))?; # } # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### is_absolute Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates checking if a Path is absolute. ```rust use std::path::Path; assert!(!Path::new("foo.txt").is_absolute()); ``` -------------------------------- ### Builder::new Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Creates a new Builder instance with default settings. This is the starting point for configuring and creating temporary files or directories. ```APIDOC ## Builder::new ### Description Creates a new `Builder` instance with default settings. This is the starting point for configuring and creating temporary files or directories. ### Method `pub fn new() -> Self` ### Parameters None. ### Returns - `Self` - A new `Builder` instance. ### Examples ```rust use tempfile::Builder; let builder = Builder::new(); ``` ``` -------------------------------- ### is_relative Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates checking if a Path is relative. ```rust use std::path::Path; assert!(Path::new("foo.txt").is_relative()); ``` -------------------------------- ### TempDir::with_prefix_in usage example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory with a specified prefix inside a given path. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // 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-")); ``` -------------------------------- ### Insecure file creation with Builder::make Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html This example shows an insecure usage of Builder::make where File::create is used directly, which may overwrite existing files. ```rust use tempfile::Builder; use std::fs::File; // This could overwrite an existing file! let tempfile = Builder::new().make(|path| File::create(path))?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### has_root Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates checking if a Path has a root. ```rust use std::path::Path; assert!(Path::new("/etc/passwd").has_root()); ``` -------------------------------- ### Create a temporary directory with a custom prefix Source: https://docs.rs/tempfile/latest/src/tempfile/dir/mod.rs.html Creates a temporary directory with a specified prefix and verifies the name starts with that prefix. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // 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::<(), std::io::Error>(()) ``` -------------------------------- ### TempDir::with_suffix usage example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory with a specified suffix. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // Create a directory inside of the current directory let tmp_dir = TempDir::with_suffix("-foo")?; let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap(); assert!(tmp_name.ends_with("-foo")); ``` -------------------------------- ### to_string_lossy Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates converting a Path to a Cow, replacing invalid UTF-8 sequences with the replacement character. ```rust use std::path::Path; let path = Path::new("foo.txt"); assert_eq!(path.to_string_lossy(), "foo.txt"); ``` -------------------------------- ### TempDir::new_in usage example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory inside a specified path. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // Create a directory inside of the current directory let tmp_dir = TempDir::new_in(".")?; let file_path = tmp_dir.path().join("my-temporary-note.txt"); let mut tmp_file = File::create(file_path)?; writeln!(tmp_file, "Brian was here. Briefly.")?; ``` -------------------------------- ### Query metadata with metadata() Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Queries the file system to get information about a file or directory, traversing symbolic links. ```rust use std::path::Path; let path = Path::new("/Minas/tirith"); let metadata = path.metadata().expect("metadata call failed"); println!("{:?}", metadata.file_type()); ``` -------------------------------- ### Create named temporary file and reopen with NamedTempFile Source: https://docs.rs/tempfile/latest/index.html Creates a named temporary file, reopens it to get an independent handle, writes data through the first handle, and reads it back through the second handle. The file is automatically cleaned up when the NamedTempFile is dropped. ```rust use tempfile::NamedTempFile; use std::io::{Write, Read}; let text = "Brian was here. Briefly."; // Create a file inside of `env::temp_dir()`. let mut file1 = NamedTempFile::new()?; // Re-open it. let mut file2 = file1.reopen()?; // Write some test data to the first handle. file1.write_all(text.as_bytes())?; // Read the test data using the second handle. let mut buf = String::new(); file2.read_to_string(&mut buf)?; assert_eq!(buf, text); ``` -------------------------------- ### Create a temporary directory and file Source: https://docs.rs/tempfile/latest/src/tempfile/dir/mod.rs.html Demonstrates creating a temporary directory and a file within it, which are both deleted when the TempDir goes out of scope. ```rust use std::fs::File; use std::io::Write; use tempfile::TempDir; // Create a directory inside of `env::temp_dir()` let tmp_dir = TempDir::new()?; let file_path = tmp_dir.path().join("my-temporary-note.txt"); let mut tmp_file = File::create(file_path)?; writeln!(tmp_file, "Brian was here. Briefly.")?; // `tmp_dir` goes out of scope, the directory as well as // `tmp_file` will be deleted here. # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a temporary directory with Builder Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html Shows how to create a temporary directory, add a file to it, and explicitly close the directory to verify deletion. ```rust use std::io::Write; use std::fs::File; use std::ffi::OsStr; use tempfile::Builder; let dir = Builder::new() .prefix("my-temporary-dir") .rand_bytes(5) .tempdir()?; let file_path = dir.path().join("my-temporary-note.txt"); let mut file = File::create(file_path)?; writeln!(file, "Brian was here. Briefly.")?; // By closing the `TempDir` explicitly, we can check that it has // been deleted successfully. If we don't close it explicitly, // the directory will still be deleted when `dir` goes out // of scope, but we won't know whether deleting the directory // succeeded. drop(file); dir.close()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a temporary directory and file Source: https://docs.rs/tempfile Create a temporary directory and add a file to it, using close to explicitly handle cleanup. ```rust use tempfile::tempdir; use std::fs::File; use std::io::Write; // Create a directory inside of `env::temp_dir()`. let dir = tempdir()?; let file_path = dir.path().join("my-temporary-note.txt"); let mut file = File::create(file_path)?; writeln!(file, "Brian was here. Briefly.")?; // By closing the `TempDir` explicitly, we can check that it has // been deleted successfully. If we don't close it explicitly, // the directory will still be deleted when `dir` goes out // of scope, but we won't know whether deleting the directory // succeeded. drop(file); dir.close()?; ``` -------------------------------- ### Create a temporary file with tempfile Source: https://docs.rs/tempfile/latest/tempfile/fn.tempfile.html Demonstrates creating a temporary file in the system's temporary directory and writing to it. ```rust use tempfile::tempfile; use std::io::Write; // Create a file inside of `env::temp_dir()`. let mut file = tempfile()?; writeln!(file, "Brian was here. Briefly.")?; ``` -------------------------------- ### to_str Example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Demonstrates how to yield a &str slice if the Path is valid UTF-8. ```rust use std::path::Path; let path = Path::new("foo.txt"); assert_eq!(path.to_str(), Some("foo.txt")); ``` -------------------------------- ### Create and use a SpooledTempFile Source: https://docs.rs/tempfile/latest/src/tempfile/spooled.rs.html Demonstrates creating a SpooledTempFile with a 15-byte limit and observing the transition from memory to disk storage when the limit is exceeded. ```rust use tempfile::spooled_tempfile; use std::io::Write; let mut file = spooled_tempfile(15); writeln!(file, "short line")?; assert!(!file.is_rolled()); // as a result of this write call, the size of the data will exceed // `max_size` (15), so it will be written to a temporary file on disk, // and the in-memory buffer will be dropped writeln!(file, "marvin gardens")?; assert!(file.is_rolled()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### TempDir::with_suffix_in usage example Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory with a specified suffix inside a given path. ```rust use std::fs::{self, File}; use std::io::Write; use tempfile::TempDir; // Create a directory inside of the current directory let tmp_dir = TempDir::with_suffix_in("-foo", ".")?; let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap(); assert!(tmp_name.ends_with("-foo")); ``` -------------------------------- ### Get the temporary file's path Source: https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html Creates a NamedTempFile and prints its path using the path() method. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::new()?; println!("{:?}", file.path()); ``` -------------------------------- ### Create a temporary file with Builder::tempfile Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html Creates a temporary file in the default system temporary directory. ```rust use tempfile::Builder; let tempfile = Builder::new().tempfile()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a UNIX domain socket in a specific directory with Builder::make_in Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Similar to Builder::make, but allows specifying a custom base directory for the temporary file path. ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make_in("./", |path| UnixListener::bind(path))?; ``` -------------------------------- ### make_in Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Same as Builder::make, but uses the specified directory as the base directory for the temporary file path. ```APIDOC ## make_in ### Description This is the same as `Builder::make`, except `dir` is used as the base directory for the temporary file path. See `Builder::make` for more details and security implications. ### Method pub fn make_in(&self, dir: P, f: F) -> Result> where F: FnMut(&Path) -> Result, P: AsRef, ### Parameters #### Path Parameters - `dir` (P) - Required - The base directory for the temporary file path. #### Function Parameter - `f` (F) - Required - A closure that receives a temporary file path and returns an `std::io::Result`. ### Examples ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make_in("./", |path| UnixListener::bind(path))?; ``` ``` -------------------------------- ### Insecure usage of Builder::make Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html An example of an insecure implementation of Builder::make that is vulnerable to time-of-check to time-of-use (TOCTOU) bugs. ```rust use std::fs::File; use tempfile::Builder; // This is NOT secure! let tempfile = Builder::new().make(|path| { if path.is_file() { return Err(std::io::ErrorKind::AlreadyExists.into()); } // Between the check above and the usage below, an attacker could // have replaced `path` with another file, which would get truncated // by `File::create`. File::create(path) })?; ``` -------------------------------- ### Create a world-readable named temporary file Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Demonstrates setting custom permissions on a temporary file using Builder. Note that the final permissions are subject to the user's umask. ```rust use tempfile::Builder; use std::os::unix::fs::PermissionsExt; let all_read_write = std::fs::Permissions::from_mode(0o666); let tempfile = Builder::new().permissions(all_read_write).tempfile()?; // Check that this worked and that the file is world-readable. // // NOTE: the file likely won't actually be created with 0o666 permissions because it's // restricted by the user's umask. // // NOTE: This test will fail if the user's umask is, e.g., 0o066. let actual_permissions = tempfile.path().metadata()?.permissions(); assert_eq!(actual_permissions.mode() & 0o044, 0o044); ``` -------------------------------- ### Create a named temporary file Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Demonstrates creating a temporary file with a custom prefix, suffix, and random byte count. ```rust use std::ffi::OsStr; use tempfile::Builder; let named_tempfile = Builder::new() .prefix("my-temporary-note") .suffix(".txt") .rand_bytes(5) .tempfile()?; let name = named_tempfile .path() .file_name().and_then(OsStr::to_str); if let Some(name) = name { assert!(name.starts_with("my-temporary-note")); assert!(name.ends_with(".txt")); assert_eq!(name.len(), "my-temporary-note.txt".len() + 5); } ``` -------------------------------- ### Create an owner-restricted temporary directory Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Demonstrates setting custom permissions on a temporary directory to restrict access to the owner. ```rust use tempfile::Builder; use std::os::unix::fs::PermissionsExt; let owner_rwx = std::fs::Permissions::from_mode(0o700); let tempdir = Builder::new().permissions(owner_rwx).tempdir()?; let actual_permissions = tempdir.path().metadata()?.permissions(); assert_eq!( actual_permissions.mode() & !0o170000, 0o700, "we get the narrow permissions we asked for" ); ``` -------------------------------- ### Create a temporary directory and add a file with tempdir Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html Creates a temporary directory, adds a file to it, and explicitly closes the `TempDir` to verify successful deletion. Without the explicit `close()`, the directory is still deleted when `dir` goes out of scope, but the success of deletion is not known. ```rust use tempfile::tempdir; use std::fs::File; use std::io::Write; // Create a directory inside of `env::temp_dir()`. let dir = tempdir()?; let file_path = dir.path().join("my-temporary-note.txt"); let mut file = File::create(file_path)?; writeln!(file, "Brian was here. Briefly.")?; // By closing the `TempDir` explicitly, we can check that it has // been deleted successfully. If we don't close it explicitly, // the directory will still be deleted when `dir` goes out // of scope, but we won't know whether deleting the directory // succeeded. drop(file); dir.close()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a temporary directory Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Basic usage of Builder to create a temporary directory. ```rust use tempfile::Builder; let tmp_dir = Builder::new().tempdir()?; ``` -------------------------------- ### spooled_tempfile(max_size: usize) -> SpooledTempFile Source: https://docs.rs/tempfile/latest/tempfile/fn.spooled_tempfile.html Creates a new SpooledTempFile. The file starts in memory and rolls over to a temporary file on disk when the data size exceeds max_size. This variant is secure in the presence of a pathological temporary file cleaner and automatically removes the temporary file when the last handle is closed. ```APIDOC ## spooled_tempfile(max_size: usize) -> SpooledTempFile ### Description Creates a new SpooledTempFile. The file starts in memory and rolls over to a temporary file on disk when the data size exceeds max_size. This variant is secure in the presence of a pathological temporary file cleaner and automatically removes the temporary file when the last handle is closed. ### Function Signature pub fn spooled_tempfile(max_size: usize) -> SpooledTempFile ### Parameters - **max_size** (usize) - Required - The maximum size in bytes that the in-memory buffer can hold before the file rolls over to disk. ### Return Value - **SpooledTempFile** - A new spooled temporary file. ### Security This variant is secure/reliable in the presence of a pathological temporary file cleaner. ### Backing Storage By default, the underlying temporary file will be created in your operating system's temporary file directory, which is often an in-memory filesystem. Consider using spooled_tempfile_in with a storage-backed filesystem (e.g., /var/tmp on Linux) if needed. ### Resource Leaking The temporary file will be automatically removed by the OS when the last handle to it is closed. This does not rely on Rust destructors being run, so it will almost never fail to clean up the temporary file. ### Example ```rust use tempfile::spooled_tempfile; use std::io::Write; let mut file = spooled_tempfile(15); writeln!(file, "short line")?; assert!(!file.is_rolled()); // as a result of this write call, the size of the data will exceed // `max_size` (15), so it will be written to a temporary file on disk, // and the in-memory buffer will be dropped writeln!(file, "marvin gardens")?; assert!(file.is_rolled()); ``` ``` -------------------------------- ### Create a UNIX domain socket with Builder::make Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Uses Builder::make to create a temporary UNIX domain socket, which is a valid use case for this method. ```rust use std::os::unix::net::UnixListener; use tempfile::Builder; let tempsock = Builder::new().make(|path| UnixListener::bind(path))?; ``` -------------------------------- ### Create a temporary directory with a prefix Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Uses the Builder pattern to create a temporary directory with a specific prefix in its name. ```rust use std::fs::File; use std::io::Write; use tempfile::Builder; // Create a directory inside of `env::temp_dir()`, // whose name will begin with 'example'. let tmp_dir = Builder::new().prefix("example").tempdir()?; ``` -------------------------------- ### Create a temporary directory in a specific directory with tempdir_in Source: https://docs.rs/tempfile/latest/tempfile/fn.tempdir_in.html Use `tempdir_in` to create a temporary directory inside a specified directory (here, the current directory). The returned `TempDir` automatically deletes the directory when it goes out of scope, but you can also call `close()` explicitly. The example creates a file inside the temporary directory and writes to it. ```rust use tempfile::tempdir_in; use std::fs::File; use std::io::Write; // Create a directory inside of the current directory. let tmp_dir = tempdir_in(".")?; let file_path = tmp_dir.path().join("my-temporary-note.txt"); let mut tmp_file = File::create(file_path)?; writeln!(tmp_file, "Brian was here. Briefly.")?; // `tmp_dir` goes out of scope, the directory as well as // `tmp_file` will be deleted here. drop(tmp_file); tmp_dir.close()?; ``` -------------------------------- ### Create a temporary file with tempfile_in Source: https://docs.rs/tempfile/latest/src/tempfile/file/mod.rs.html Creates a new temporary file in a specified directory. ```rust use tempfile::tempfile_in; use std::io::Write; // Create a file inside of the current working directory let mut file = tempfile_in("./")?; writeln!(file, "Brian was here. Briefly.")?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### by_ref Source: https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html Creates a 'by reference' adapter for this instance of Write. ```APIDOC ## by_ref ### Description Creates a 'by reference' adapter for this instance of Write. ### Signature fn by_ref(&mut self) -> &mut Self where Self: Sized ### Returns - **&mut Self** - A mutable reference to the writer. ``` -------------------------------- ### Create a named temporary file in a specific directory Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Demonstrates creating a named temporary file within a specified directory path. ```rust use tempfile::Builder; let tempfile = Builder::new().tempfile_in("./")?; ``` -------------------------------- ### Create a temporary directory with Builder::tempdir Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html Creates a temporary directory in the default system temporary directory that is automatically deleted when the returned TempDir is dropped. ```rust use tempfile::Builder; let tmp_dir = Builder::new().tempdir()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### NamedTempFile::with_prefix_in Source: https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html Creates a new NamedTempFile with a specified prefix in a specified directory. ```APIDOC ## NamedTempFile::with_prefix_in ### Description Creates a new named temporary file with a given prefix in a specified directory. ### Method Function ### Signature `pub fn with_prefix_in, P: AsRef>(prefix: S, dir: P) -> Result` ### Parameters - `prefix` (S) - Required - The prefix for the temporary file name. - `dir` (P) - Required - The directory in which to create the temporary file. ### Returns - `Result` - The created temporary file or an error. ### Example ```rust use tempfile::NamedTempFile; let file = NamedTempFile::with_prefix_in("myapp", ".")?; ``` ``` -------------------------------- ### Unix create function for TempDir Source: https://docs.rs/tempfile/latest/src/tempfile/dir/imp/unix.rs.html Creates a temporary directory using `DirBuilder`, applies Unix permissions if provided, and returns a `TempDir` with cleanup control. Uses `IoResultExt` to add error context. ```rust use crate::error::IoResultExt; use crate::TempDir; use std::io; use std::path::PathBuf; pub fn create( path: PathBuf, permissions: Option<&std::fs::Permissions>, disable_cleanup: bool, ) -> io::Result { let mut dir_options = std::fs::DirBuilder::new(); #[cfg(not(target_os = "wasi"))] { use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; if let Some(p) = permissions { dir_options.mode(p.mode()); } } dir_options .create(&path) .with_err_path(|| &path) .map(|_| TempDir { path: path.into_boxed_path(), disable_cleanup, }) } ``` -------------------------------- ### Create a temporary directory with a generated name Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Creates a temporary directory inside the system's default temporary directory. ```rust use std::fs::File; use std::io::Write; use tempfile::TempDir; // Create a directory inside of `env::temp_dir()` let tmp_dir = TempDir::new()?; ``` -------------------------------- ### as_file Source: https://docs.rs/tempfile/latest/src/tempfile/file/mod.rs.html Returns a reference to the underlying file. ```APIDOC ## as_file ### Description Returns a reference to the underlying file. ### Signature pub fn as_file(&self) -> &F ### Return Value - **&F** - A reference to the underlying file. ``` -------------------------------- ### Path::starts_with Source: https://docs.rs/tempfile/latest/tempfile/struct.TempPath.html Determines whether `base` is a prefix of `self`. Only considers whole path components to match. ```APIDOC ## Path::starts_with ### Description Determines whether `base` is a prefix of `self`. Only considers whole path components to match. ### Method starts_with ### Signature pub fn starts_with

(&self, base: P) -> bool where P: AsRef ### Parameters - **base** (P) - Required - The prefix to check. ### Return Value A `bool` indicating whether `base` is a prefix of `self`. ### Examples ```rust use std::path::Path; let path = Path::new("/etc/passwd"); assert!(path.starts_with("/etc")); assert!(path.starts_with("/etc/")); assert!(path.starts_with("/etc/passwd")); assert!(path.starts_with("/etc/passwd/")); // extra slash is okay assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay assert!(!path.starts_with("/e")); assert!(!path.starts_with("/etc/passwd.txt")); assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo")); ``` ``` -------------------------------- ### Create a temporary directory in a specific location Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Creates a temporary directory with a custom prefix inside a specified folder. ```rust use tempfile::Builder; let dir = Builder::new() .prefix("my-temporary-dir") .tempdir_in("folder-with-tempdirs")?; ``` -------------------------------- ### make Source: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html Attempts to create a temporary file (or file-like object) using the provided closure. The closure is passed a temporary file path and returns an std::io::Result. The path is inside the system temporary directory unless overridden with make_in. ```APIDOC ## make ### Description Attempts to create a temporary file (or file-like object) using the provided closure. The closure is passed a temporary file path and returns an `std::io::Result`. The path provided to the closure will be inside of `env::temp_dir()`. Use `Builder::make_in` to provide a custom temporary directory. If the closure returns one of the following errors, then another randomized file path is tried: `std::io::ErrorKind::AlreadyExists`, `std::io::ErrorKind::AddrInUse`. ### Method pub fn make(&self, f: F) -> Result> where F: FnMut(&Path) -> Result, ### Parameters #### Function Parameter - `f` (F) - Required - A closure that receives a temporary file path and returns an `std::io::Result`. ### Errors If the closure returns any error besides `std::io::ErrorKind::AlreadyExists` or `std::io::ErrorKind::AddrInUse`, then `Err` is returned. ### Security This has the same security implications as `NamedTempFile`, but with additional caveats. Specifically, it is up to the closure to ensure that the file does not exist and that such a check is _atomic_. Otherwise, a time-of-check to time-of-use bug could be introduced. ### Examples ```rust use std::os::unix::net::UnixListener; use tempfile::Builder; let tempsock = Builder::new().make(|path| UnixListener::bind(path))?; ``` ``` -------------------------------- ### Builder::new() Source: https://docs.rs/tempfile/latest/src/tempfile/lib.rs.html Creates a new Builder instance with default settings. The default prefix is '.tmp', suffix is empty, random bytes is 6, append is false, and cleanup is enabled. ```APIDOC ## Builder::new() ### Description Creates a new `Builder` instance with default settings. The default prefix is `.tmp`, suffix is empty, random bytes is `6`, append is `false`, and cleanup is enabled. ### Method `pub fn new() -> Self` ### Parameters None. ### Returns - `Self` - A new `Builder` instance. ### Examples ```rust use tempfile::Builder; let named_tempfile = Builder::new() .prefix("my-temporary-note") .suffix(".txt") .rand_bytes(5) .tempfile()?; ``` ``` -------------------------------- ### Accessing the TempDir path Source: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html Demonstrates how to retrieve the path of a temporary directory and verify its existence before it is automatically deleted at the end of its scope. ```rust use tempfile::TempDir; let tmp_path; { let tmp_dir = TempDir::new()?; tmp_path = tmp_dir.path().to_owned(); // Check that the temp directory actually exists. assert!(tmp_path.exists()); // End of `tmp_dir` scope, directory will be deleted } // Temp directory should be deleted by now assert_eq!(tmp_path.exists(), false); ```