1 unstable release
0.0.1 | Nov 6, 2023 |
---|
#8 in #temporarily
21 downloads per month
Used in 3 crates
16KB
294 lines
pushd
A simple library for temporarily changing the current working directory.
Usage
Add this to your Cargo.toml
:
[dependencies]
pushd = "0.0.1"
Example
use anyhow::Result
use std::path::PathBuf;
use pushd::Pushd;
fn main() -> Result<()> {
write_in_etc()?;
// Current working directory is whatever it was before the call to
// `write_in_etc`.
}
fn write_in_etc() -> Result<()> {
let path = PathBuf::new("/etc");
let _pd = Pushd::new(path)?;
// Current working directory is now /etc
//
// Do something in /etc.
}
lib.rs
:
This crate provides a Pushd
type that temporarily changes the current
directory.
When a Pushd
struct is created it will call env::set_current_dir
to change to the given directory. When the Pushd
is dropped, it will
change back to the original directory.
If the original directory doesn't exist, this error is ignored, since this
may be because the original directory was a temporary directory. All other
errors during drop cause a panic by default, but panics can be disabled
entirely by using the Pushd::new_no_panic
constructor.
Examples
use pushd::Pushd;
use std::path::PathBuf;
fn in_directory(path: PathBuf) {
// When the current function exits and this variable is dropped, the
// current directory will revert back to whatever it was before this
// `Pushd` was created.
let _pd = Pushd::new(path);
// ...
}
Panics
The Pushd
may panic if it cannot change back to the original directory
when it's dropped. Use the new_no_panic
constructor to prevent this.
Dependencies
~0.3–0.8MB
~19K SLoC