pub struct WithDir<'a> { /* private fields */ }Expand description
Scoped modifier of the current working directory. This uses RAII to set the
current working directory back to what it was when the instance is dropped.
This struct uses a static parking_lot::ReentrantMutex to prevent WithDir on other
threads from updating the current working directory while any WithDir instances
exist. However there is nothing stopping other threads from calling std::env::set_current_dir
directly which would override the working directory.
WithDir should be created with new which returns a result. Result couldbe Err if the
directory doesn’t exist, or if the user does not have permission to access.
use with_dir::WithDir;
// create a directory
let path = std::env::current_dir().unwrap().join("a");
if !path.exists() {
std::fs::create_dir(&path);
}
// enter that directory
WithDir::new(&path).map( |_| {
assert_eq!(std::env::current_dir().unwrap(), path);
}).unwrap();
// cwd is reset
// enter it again
let cwd = WithDir::new("a").unwrap();
// exit it
cwd.leave().unwrap();Implementations§
Source§impl<'a> WithDir<'a>
impl<'a> WithDir<'a>
Sourcepub fn new(path: impl AsRef<Path>) -> Result<WithDir<'a>, Error>
pub fn new(path: impl AsRef<Path>) -> Result<WithDir<'a>, Error>
On creation, the current working directory is set to path
and a ReentrantMutexGuard is claimed.
Sourcepub fn temp() -> Result<WithDir<'a>, Error>
pub fn temp() -> Result<WithDir<'a>, Error>
Uses TempDir to create a temporary
directory that with the same lifetime as the returned
WithDir. The current working dir is change to the temp_dir