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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::atoms::Outcome;

use super::super::Atom;
use std::path::PathBuf;

pub struct Create {
    pub path: PathBuf,
}

impl std::fmt::Display for Create {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "The directory {} needs to be created",
            self.path.display(),
        )
    }
}

impl Atom for Create {
    fn plan(&self) -> anyhow::Result<Outcome> {
        Ok(Outcome {
            side_effects: vec![],
            should_run: !self.path.exists(),
        })
    }

    fn execute(&mut self) -> anyhow::Result<()> {
        std::fs::create_dir_all(&self.path)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::env::temp_dir;

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn it_can_plan() {
        let atom = Create {
            path: std::path::PathBuf::from("/some-random-path"),
        };
        assert_eq!(true, atom.plan().unwrap().should_run);

        let temp = temp_dir();
        let atom = Create { path: temp };
        assert_eq!(false, atom.plan().unwrap().should_run);
    }

    #[test]
    fn it_can_execute() {
        let temp_dir = match tempfile::tempdir() {
            std::result::Result::Ok(dir) => dir,
            std::result::Result::Err(_) => {
                assert_eq!(false, true);
                return;
            }
        };

        let mut atom = Create {
            path: temp_dir.path().join("create-me"),
        };

        assert_eq!(false, temp_dir.path().join("create-me").exists());

        assert_eq!(true, atom.execute().is_ok());
        assert_eq!(false, atom.plan().unwrap().should_run);

        assert_eq!(true, temp_dir.path().join("create-me").is_dir());
    }
}