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
76
77
78
79
80
81
82
83
use crate::atoms::Outcome;

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

pub struct Create {
    pub path: PathBuf,
}

impl FileAtom for Create {
    fn get_path(&self) -> &PathBuf {
        &self.path
    }
}

impl std::fmt::Display for Create {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "The file {} 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::File::create(&self.path)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn it_can_plan() {
        let file_create = Create {
            path: std::path::PathBuf::from("some-random-path"),
        };

        assert_eq!(true, file_create.plan().unwrap().should_run);

        let temp_file = match tempfile::NamedTempFile::new() {
            std::result::Result::Ok(file) => file,
            std::result::Result::Err(_) => {
                assert_eq!(false, true);
                return;
            }
        };

        let file_create = Create {
            path: temp_file.path().to_path_buf(),
        };

        assert_eq!(false, file_create.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 file_create = Create {
            path: temp_dir.path().join("create-me"),
        };

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