1 unstable release

0.0.1 Nov 6, 2023

#8 in #temporarily

Download history 89/week @ 2024-03-14 47/week @ 2024-03-21 68/week @ 2024-03-28 20/week @ 2024-04-04 1/week @ 2024-04-11 63/week @ 2024-04-18 20/week @ 2024-04-25 127/week @ 2024-05-02 13/week @ 2024-05-09 76/week @ 2024-05-16 11/week @ 2024-05-23 10/week @ 2024-05-30 14/week @ 2024-06-06 36/week @ 2024-06-13 6/week @ 2024-06-20 3/week @ 2024-06-27

60 downloads per month
Used in 3 crates

MIT/Apache

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.4–0.9MB
~20K SLoC