Struct TempDir

Source
pub struct TempDir { /* private fields */ }
Expand description

A temporary directory that automatically cleans up its contents when dropped.

Files created through the TempDir are tracked and removed upon drop.

Implementations§

Source§

impl TempDir

Source

pub fn new<P: AsRef<Path>>(path: P) -> TempResult<Self>

Creates a new temporary directory at the specified path.

The directory (and any missing parent directories) will be created.

§Arguments
  • path - The path at which to create the directory. If a relative path is provided, it is resolved relative to the system temporary directory.
§Errors

Returns an error if the directory cannot be created.

Source

pub fn new_here<P: AsRef<Path>>(path: P) -> TempResult<Self>

Creates a new temporary directory at the specified path.

The directory (and any missing parent directories) will be created.

§Arguments
  • path - The path at which to create the directory. If a relative path is provided, it is resolved relative to the current directory.
§Errors

Returns an error if the directory cannot be created.

Source

pub fn new_random<P: AsRef<Path>>(dir: Option<P>) -> TempResult<Self>

Creates a new temporary directory with a random name in the given parent directory.

The directory name will consist of alphanumeric characters only, ensuring compatibility across different filesystems.

§Arguments
  • dir - An optional parent directory in which to create the temporary directory. If a relative directory is provided, it is resolved relative to the system temporary directory.
§Errors

Returns an error if a unique directory name cannot be generated or if directory creation fails.

Examples found in repository?
ex/e2.rs (line 6)
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}
Source

pub fn new_random_here<P: AsRef<Path>>(dir: Option<P>) -> TempResult<Self>

Creates a new temporary directory with a random name in the given parent directory.

The directory name will consist of alphanumeric characters only, ensuring compatibility across different filesystems.

§Arguments
  • dir - An optional parent directory in which to create the temporary directory. If a relative directory is provided, it is resolved relative to the current working directory.
§Errors

Returns an error if a unique directory name cannot be generated or if directory creation fails.

Source

pub fn create_file<S: AsRef<str>>( &mut self, filename: S, ) -> TempResult<&mut TempFile>

Creates a new temporary file with the given filename in the directory.

The created file is tracked and will be automatically deleted on drop.

§Arguments
  • filename - The name of the file to create.
§Errors

This function will return an error if the inner path is None.

Examples found in repository?
ex/e2.rs (line 10)
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}
Source

pub fn create_random_file(&mut self) -> TempResult<&mut TempFile>

Creates a new temporary file with a random name in the directory.

The file is tracked and will be automatically deleted on drop.

§Errors

Returns an error if a unique filename cannot be generated or if file creation fails.

Examples found in repository?
ex/e2.rs (line 16)
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}
Source

pub fn remove_file<S: AsRef<str>>(&mut self, filename: S)

Removes a file from the directory’s management.

This does not delete the file immediately—it will be removed when the directory is dropped.

§Arguments
  • filename - The name of the file to remove from management.
Source

pub fn get_file<S: AsRef<str>>(&self, filename: S) -> Option<&TempFile>

Retrieves a reference to a temporary file by filename.

§Arguments
  • filename - The name of the file to retrieve.
Source

pub fn get_file_mut<S: AsRef<str>>( &mut self, filename: S, ) -> Option<&mut TempFile>

Retrieves a mutable reference to a temporary file by filename.

§Arguments
  • filename - The name of the file to retrieve.
Source

pub fn path(&self) -> Option<&Path>

Returns the path of the temporary directory.

Source

pub fn into_path(self) -> Option<PathBuf>

Consumes the TempDir, returning its path and preventing cleanup.

Source

pub fn list_files(&self) -> Vec<&Path>

Lists the paths of all files managed by the directory.

Examples found in repository?
ex/e2.rs (line 21)
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}
Source

pub fn new_in<P: AsRef<Path>>(path: P) -> TempResult<Self>

Creates a new temporary directory with a random name within the given parent directory.

§Arguments
  • path - The parent directory in which to create the temporary directory. If a relative path is provided, it is resolved relative to the system temporary directory.
§Errors

Returns an error if a unique directory name cannot be generated or if directory creation fails.

Source§

impl TempDir

Source

pub fn find_files_by_pattern<S: AsRef<str>>( &self, pattern: S, ) -> Result<Vec<&TempFile>, RErr>

Finds files with names matching a regex pattern.

§Arguments
  • pattern - A regex pattern to match file names.
§Errors

Returns an error if the regex pattern is invalid.

Examples found in repository?
ex/e2.rs (line 28)
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}
Source

pub fn find_files_by_pattern_mut<S: AsRef<str>>( &mut self, pattern: S, ) -> Result<Vec<&mut TempFile>, RErr>

Finds mutable references to files with names matching a regex pattern.

§Arguments
  • pattern - A regex pattern to match file names.
§Errors

Returns an error if the regex pattern is invalid.

Trait Implementations§

Source§

impl AsRef<Path> for TempDir

Source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Drop for TempDir

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V