comtrya_lib/atoms/file/
create.rs1use crate::atoms::Outcome;
2
3use super::super::Atom;
4use super::FileAtom;
5use std::path::PathBuf;
6
7pub struct Create {
8 pub path: PathBuf,
9}
10
11impl FileAtom for Create {
12 fn get_path(&self) -> &PathBuf {
13 &self.path
14 }
15}
16
17impl std::fmt::Display for Create {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 write!(f, "The file {} needs to be created", self.path.display(),)
20 }
21}
22
23impl Atom for Create {
24 fn plan(&self) -> anyhow::Result<Outcome> {
25 Ok(Outcome {
26 side_effects: vec![],
27 should_run: !self.path.exists(),
28 })
29 }
30
31 fn execute(&mut self) -> anyhow::Result<()> {
32 std::fs::File::create(&self.path)?;
33
34 Ok(())
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use pretty_assertions::assert_eq;
42
43 #[test]
44 fn it_can_plan() {
45 let file_create = Create {
46 path: std::path::PathBuf::from("some-random-path"),
47 };
48
49 assert_eq!(true, file_create.plan().unwrap().should_run);
50
51 let temp_file = match tempfile::NamedTempFile::new() {
52 std::result::Result::Ok(file) => file,
53 std::result::Result::Err(_) => {
54 assert_eq!(false, true);
55 return;
56 }
57 };
58
59 let file_create = Create {
60 path: temp_file.path().to_path_buf(),
61 };
62
63 assert_eq!(false, file_create.plan().unwrap().should_run);
64 }
65
66 #[test]
67 fn it_can_execute() {
68 let temp_dir = match tempfile::tempdir() {
69 std::result::Result::Ok(dir) => dir,
70 std::result::Result::Err(_) => {
71 assert_eq!(false, true);
72 return;
73 }
74 };
75
76 let mut file_create = Create {
77 path: temp_dir.path().join("create-me"),
78 };
79
80 assert_eq!(true, file_create.execute().is_ok());
81 assert_eq!(false, file_create.plan().unwrap().should_run);
82 }
83}