use std::fs::{create_dir_all, remove_dir_all, File};
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Fixture {
pub paths: Vec<String>,
files: Vec<String>,
}
impl Fixture {
pub fn new() -> Fixture {
let fixture: Fixture = Default::default();
fixture
}
pub fn add_dirpath(&mut self, path: String) -> Fixture {
self.paths.push(path);
self.clone()
}
pub fn add_file(&mut self, file: String) -> Fixture {
self.files.push(file);
self.clone()
}
pub fn build(&mut self) -> Fixture {
let mkdirs = |path: String| {
create_dir_all(Path::new(&path.clone())).expect("Failed to create directories.");
path
};
self.paths
.iter()
.filter(|path| path != &"")
.for_each(|path| {
mkdirs(path.to_string());
});
let touch = |path: String| {
File::create(path.clone()).expect("Failed to create file.");
path
};
self.files
.iter()
.filter(|path| path != &"")
.for_each(|path| {
let _path = Path::new(path);
touch(path.to_string());
});
self.clone()
}
pub fn teardown(
&mut self,
del_all: bool,
) -> Fixture {
let rmr = |path: String| {
remove_dir_all(path.clone()).expect("Failed to delete all files.");
path
};
self.paths
.iter()
.filter(|path| path != &"")
.for_each(|path| {
if del_all {
if Path::new(path).exists() {
rmr(path.to_string());
}
}
});
self.clone()
}
}
pub mod command_assistors {
use std::env;
use std::path::Path;
pub struct PathCache<'s> {
from_path: Box<Path>,
to_path: &'s Path,
}
impl<'s> PathCache<'s> {
pub fn new(to_path: &Path) -> PathCache {
let current_dir = env::current_dir().expect("failed to get current dir");
let from_path = current_dir.into_boxed_path();
PathCache { from_path, to_path }
}
pub fn switch(&mut self) {
if env::set_current_dir(&self.to_path).is_err() {
panic!("failed to switch back to original dir")
}
}
pub fn switch_back(&mut self) {
if env::set_current_dir(&self.from_path).is_err() {
panic!("failed to switch back to original dir")
}
}
}
}