Skip to main content

ls_key/
fixtures.rs

1use std::fs::{create_dir_all, remove_dir_all, File};
2use std::path::Path;
3
4#[derive(Debug, Clone, PartialEq, Default)]
5pub struct Fixture {
6    pub paths: Vec<String>,
7    //dirs: Vec<Path>
8    files: Vec<String>,
9}
10
11/// Create directories, files, and tear them down at will.
12/// Used throughout immutag crates for testing purposes.
13/// See tests directories of said crates for examples.
14impl Fixture {
15    pub fn new() -> Fixture {
16        let fixture: Fixture = Default::default();
17
18        fixture
19    }
20
21    pub fn add_dirpath(&mut self, path: String) -> Fixture {
22        self.paths.push(path);
23
24        self.clone()
25    }
26
27    pub fn add_file(&mut self, file: String) -> Fixture {
28        self.files.push(file);
29
30        self.clone()
31    }
32
33    /// Builds all the directory files and paths and then writes them to disk.
34    pub fn build(&mut self) -> Fixture {
35        let mkdirs = |path: String| {
36            create_dir_all(Path::new(&path.clone())).expect("Failed to create directories.");
37            path
38        };
39
40        // Create all dir paths.
41        self.paths
42            .iter()
43            .filter(|path| path != &"")
44            .for_each(|path| {
45                mkdirs(path.to_string());
46            });
47
48        //let data = "version = '0.1.0'\n\n[file]\n\n[dir]\n\n[ignore]";
49        //let data = "[dir.tests]\nmeta = 'Tests'";
50
51        let touch = |path: String| {
52            File::create(path.clone()).expect("Failed to create file.");
53            path
54        };
55
56        self.files
57            .iter()
58            .filter(|path| path != &"")
59            .for_each(|path| {
60                let _path = Path::new(path);
61                touch(path.to_string());
62            });
63
64        self.clone()
65    }
66
67    /// Teardown everything.
68    /// At the moment, it's really only suited for tearing down all the files, except the .immutag dir itself.
69    /// However, more fine grained control can be added within this method.
70    /// For example, teardown could take a Vec of paths to delete.
71    pub fn teardown(
72        &mut self,
73        del_all: bool, /*dir_index: Option<usize>, file_index: Option<usize> */
74    ) -> Fixture {
75        let rmr = |path: String| {
76            remove_dir_all(path.clone()).expect("Failed to delete all files.");
77            path
78        };
79
80        // Create all dir paths.
81        self.paths
82            .iter()
83            // The first one is the initialization.
84            .filter(|path| path != &"")
85            // Kinda weird, but useful code here because we may
86            // want to delete specific paths in the future.
87            // Current usage is to delete the entire root dir
88            // structure that was previously built.
89            .for_each(|path| {
90                if del_all {
91                    // Throws an error if the path doesn't exist, so we only remove
92                    // if the path exists.
93                    if Path::new(path).exists() {
94                        rmr(path.to_string());
95                    }
96                }
97            });
98
99        self.clone()
100    }
101}
102
103
104/// Switch back and forth between paths when executing test commands.
105pub mod command_assistors {
106    use std::env;
107    use std::path::Path;
108
109    pub struct PathCache<'s> {
110        from_path: Box<Path>,
111        to_path: &'s Path,
112    }
113
114    impl<'s> PathCache<'s> {
115        pub fn new(to_path: &Path) -> PathCache {
116            let current_dir = env::current_dir().expect("failed to get current dir");
117            let from_path = current_dir.into_boxed_path();
118
119            PathCache { from_path, to_path }
120        }
121
122        pub fn switch(&mut self) {
123            if env::set_current_dir(&self.to_path).is_err() {
124                panic!("failed to switch back to original dir")
125            }
126        }
127
128        pub fn switch_back(&mut self) {
129            if env::set_current_dir(&self.from_path).is_err() {
130                panic!("failed to switch back to original dir")
131            }
132        }
133    }
134}