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 files: Vec<String>,
9}
10
11impl 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 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 self.paths
42 .iter()
43 .filter(|path| path != &"")
44 .for_each(|path| {
45 mkdirs(path.to_string());
46 });
47
48 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 pub fn teardown(
72 &mut self,
73 del_all: bool, ) -> Fixture {
75 let rmr = |path: String| {
76 remove_dir_all(path.clone()).expect("Failed to delete all files.");
77 path
78 };
79
80 self.paths
82 .iter()
83 .filter(|path| path != &"")
85 .for_each(|path| {
90 if del_all {
91 if Path::new(path).exists() {
94 rmr(path.to_string());
95 }
96 }
97 });
98
99 self.clone()
100 }
101}
102
103
104pub 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}