|
| 1 | +use std::{ |
| 2 | + collections::HashMap, |
| 3 | + env::temp_dir, |
| 4 | + fs::{create_dir_all, remove_dir_all, File}, |
| 5 | + io::{Error, Write}, |
| 6 | + ops::{Deref, DerefMut}, |
| 7 | + path::{Path, PathBuf}, |
| 8 | +}; |
| 9 | + |
| 10 | +pub struct MockRoot(PathBuf); |
| 11 | + |
| 12 | +impl MockRoot { |
| 13 | + pub(crate) fn new<D, H>(docroot: D, files: H) -> Result<Self, Error> |
| 14 | + where |
| 15 | + D: AsRef<Path>, |
| 16 | + H: Into<HashMap<PathBuf, String>>, |
| 17 | + { |
| 18 | + let docroot = docroot.as_ref(); |
| 19 | + create_dir_all(docroot)?; |
| 20 | + |
| 21 | + let map: HashMap<PathBuf, String> = files.into(); |
| 22 | + for (path, contents) in map.iter() { |
| 23 | + let stripped = path.strip_prefix("/").unwrap_or(path); |
| 24 | + |
| 25 | + let file_path = docroot.join(stripped); |
| 26 | + if let Some(parent) = file_path.parent() { |
| 27 | + create_dir_all(parent)?; |
| 28 | + } |
| 29 | + |
| 30 | + let mut file = File::create(file_path)?; |
| 31 | + file.write_all(contents.as_bytes())?; |
| 32 | + } |
| 33 | + |
| 34 | + // This unwrap should be safe due to creating the docroot base dir above. |
| 35 | + Ok(Self(docroot.canonicalize().unwrap())) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn builder() -> MockRootBuilder { |
| 39 | + MockRootBuilder::default() |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl Drop for MockRoot { |
| 44 | + fn drop(&mut self) { |
| 45 | + remove_dir_all(&self.0).ok(); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Deref for MockRoot { |
| 50 | + type Target = PathBuf; |
| 51 | + |
| 52 | + fn deref(&self) -> &Self::Target { |
| 53 | + &self.0 |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl DerefMut for MockRoot { |
| 58 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 59 | + &mut self.0 |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +#[derive(Debug)] |
| 64 | +pub struct MockRootBuilder(PathBuf, HashMap<PathBuf, String>); |
| 65 | + |
| 66 | +impl MockRootBuilder { |
| 67 | + pub(crate) fn new<D>(docroot: D) -> Self |
| 68 | + where |
| 69 | + D: AsRef<Path>, |
| 70 | + { |
| 71 | + Self(docroot.as_ref().to_owned(), HashMap::new()) |
| 72 | + } |
| 73 | + |
| 74 | + pub fn file<P, C>(mut self, path: P, contents: C) -> MockRootBuilder |
| 75 | + where |
| 76 | + P: AsRef<Path>, |
| 77 | + C: Into<String>, |
| 78 | + { |
| 79 | + let path = path.as_ref().to_owned(); |
| 80 | + let contents = contents.into(); |
| 81 | + |
| 82 | + self.1.insert(path, contents); |
| 83 | + self |
| 84 | + } |
| 85 | + |
| 86 | + pub fn build(self) -> Result<MockRoot, Error> { |
| 87 | + MockRoot::new(self.0, self.1) |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +impl Default for MockRootBuilder { |
| 92 | + fn default() -> Self { |
| 93 | + Self::new(temp_dir().join("php-temp-dir-base")) |
| 94 | + } |
| 95 | +} |
0 commit comments