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