novel_cli/utils/
current_dir.rs

1use std::{
2    env,
3    path::{Path, PathBuf},
4};
5
6use color_eyre::eyre::{self, Result};
7
8pub struct CurrentDir {
9    backup_path: PathBuf,
10}
11
12impl CurrentDir {
13    pub fn new<T>(path: T) -> Result<Self>
14    where
15        T: AsRef<Path>,
16    {
17        let path = path.as_ref();
18
19        eyre::ensure!(
20            path.is_dir(),
21            "The directory does not exist and cannot be set as the current working directory: `{}`",
22            path.display()
23        );
24
25        let backup_path = env::current_dir()?;
26        env::set_current_dir(path)?;
27
28        Ok(Self { backup_path })
29    }
30
31    pub fn restore(self) -> Result<()> {
32        env::set_current_dir(self.backup_path)?;
33        Ok(())
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use pretty_assertions::{assert_eq, assert_ne};
40    use testresult::TestResult;
41
42    use super::*;
43
44    #[test]
45    fn current_dir() -> TestResult {
46        let temp_dir = tempfile::tempdir()?;
47        let backup_dir = env::current_dir()?;
48
49        let current_dir = CurrentDir::new(temp_dir.path())?;
50        assert_ne!(env::current_dir()?, backup_dir);
51
52        current_dir.restore()?;
53        assert_eq!(env::current_dir()?, backup_dir);
54
55        Ok(())
56    }
57}