novel_cli/utils/
current_dir.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::{
    env,
    path::{Path, PathBuf},
};

use color_eyre::eyre::{self, Result};

pub struct CurrentDir {
    backup_path: PathBuf,
}

impl CurrentDir {
    pub fn new<T>(path: T) -> Result<Self>
    where
        T: AsRef<Path>,
    {
        let path = path.as_ref();

        eyre::ensure!(
            path.is_dir(),
            "The directory does not exist and cannot be set as the current working directory: `{}`",
            path.display()
        );

        let backup_path = env::current_dir()?;
        env::set_current_dir(path)?;

        Ok(Self { backup_path })
    }

    pub fn restore(self) -> Result<()> {
        env::set_current_dir(self.backup_path)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::{assert_eq, assert_ne};
    use testresult::TestResult;

    use super::*;

    #[test]
    fn current_dir() -> TestResult {
        let temp_dir = tempfile::tempdir()?;
        let backup_dir = env::current_dir()?;

        let current_dir = CurrentDir::new(temp_dir.path())?;
        assert_ne!(env::current_dir()?, backup_dir);

        current_dir.restore()?;
        assert_eq!(env::current_dir()?, backup_dir);

        Ok(())
    }
}