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
extern crate walkdir; use std::fs::DirBuilder; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; use walkdir::WalkDir; #[derive(Debug)] pub struct SimpleFile { content: String, abs_path: PathBuf, rel_path: PathBuf, } type MiddlewareFunction = Box<FnMut(&mut Vec<SimpleFile>)>; pub fn seven(middleware: Vec<MiddlewareFunction>, destination: &str) -> Vec<SimpleFile> { let mut files = Vec::<SimpleFile>::new(); read_dir(&mut files); for mut function in middleware { function(&mut files); } write_dir(&mut files); files } fn read_dir(files: &mut Vec<SimpleFile>) { for entry in WalkDir::new("example") { let entry = entry.unwrap(); let path = entry.path().to_owned(); if !&path.is_dir() { let mut file = File::open(&path).unwrap(); let mut content = String::new(); file.read_to_string(&mut content).unwrap(); let file_struct = SimpleFile { content: content, abs_path: path.clone().canonicalize().unwrap(), rel_path: path, }; &files.push(file_struct); } } } fn write_dir(files: &mut Vec<SimpleFile>) { for file in files { let temp_path = file.rel_path.strip_prefix("example").unwrap(); let destination_path = PathBuf::from("destination").join(temp_path); let mut dir_path = destination_path.clone(); dir_path.pop(); DirBuilder::new().recursive(true).create(&dir_path).unwrap(); let mut fileref = File::create(&destination_path).unwrap(); fileref.write_all(file.content.as_bytes()).unwrap(); } } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let result = seven(vec![ Box::new(|files: &mut Vec<SimpleFile>| { let file: &mut SimpleFile = &mut files[0]; file.content = "test hello".to_string(); }), Box::new(|files: &mut Vec<SimpleFile>| { let file: &mut SimpleFile = &mut files[0]; file.content = "override".to_string(); }), ]); assert_eq!(result[0].content, "override"); } }