Skip to main content

chwd/
lib.rs

1//! Helper library to store your current working directory when changing to a different directory,
2//! then changing back to the original directory once the helper object goes out of scope.
3
4use std::env;
5use std::path;
6
7#[derive(Debug)]
8pub struct ChangeWorkingDirectory {
9    previous_directory: path::PathBuf,
10}
11
12impl ChangeWorkingDirectory {
13    /// Store the current working directory, then change it to the supplied path. When the struct
14    /// goes out of scope, the current working directory will be changed back to what it originally
15    /// was.
16    ///
17    /// ```rust
18    /// use std::env;
19    /// use chwd::ChangeWorkingDirectory;
20    /// use std::io;
21    ///
22    /// fn main() -> Result<(), std::io::Error>
23    /// {
24    ///     {
25    ///         let _dir_change = ChangeWorkingDirectory::change(&env::temp_dir())?;
26    ///         // Do something in the temp dir
27    ///     }
28    ///
29    ///     // _dir_change has gone out of scope, you will be back where you started.
30    ///     Ok(())
31    /// }
32    /// ```
33    pub fn change(new_directory: &impl AsRef<path::Path>) -> Result<Self, std::io::Error> {
34        let current_working_directory = env::current_dir()?;
35
36        env::set_current_dir(new_directory)?;
37
38        Ok(ChangeWorkingDirectory {
39            previous_directory: current_working_directory,
40        })
41    }
42}
43
44impl Drop for ChangeWorkingDirectory {
45    fn drop(&mut self) {
46        // Panics in drops are bad, especially if the drop is called when code has panicked
47        // elsewhere already. We'll stick with printing something to stderr for now...
48        if let Err(e) = env::set_current_dir(&self.previous_directory) {
49            eprintln!(
50                "Unable to change directory back to {:?} due to error {}",
51                &self.previous_directory, &e
52            );
53        }
54    }
55}