|
1 | 1 | /// Collection of files
|
2 |
| -pub trait DirFixture { |
| 2 | +pub trait DirFixture: std::fmt::Debug { |
3 | 3 | /// Initialize a test fixture directory `root`
|
4 | 4 | fn write_to_path(&self, root: &std::path::Path) -> Result<(), crate::assert::Error>;
|
5 | 5 | }
|
@@ -59,3 +59,56 @@ impl DirFixture for String {
|
59 | 59 | std::path::Path::new(self).write_to_path(root)
|
60 | 60 | }
|
61 | 61 | }
|
| 62 | + |
| 63 | +impl<P, S> DirFixture for &[(P, S)] |
| 64 | +where |
| 65 | + P: AsRef<std::path::Path>, |
| 66 | + P: std::fmt::Debug, |
| 67 | + S: AsRef<[u8]>, |
| 68 | + S: std::fmt::Debug, |
| 69 | +{ |
| 70 | + fn write_to_path(&self, root: &std::path::Path) -> Result<(), crate::assert::Error> { |
| 71 | + let root = super::ops::canonicalize(root) |
| 72 | + .map_err(|e| format!("Failed to canonicalize {}: {}", root.display(), e))?; |
| 73 | + |
| 74 | + for (path, content) in self.iter() { |
| 75 | + let rel_path = path.as_ref(); |
| 76 | + let path = root.join(rel_path); |
| 77 | + let path = super::ops::normalize_path(&path); |
| 78 | + if !path.starts_with(&root) { |
| 79 | + return Err(crate::assert::Error::new(format!( |
| 80 | + "Fixture {} is for outside of the target root", |
| 81 | + rel_path.display(), |
| 82 | + ))); |
| 83 | + } |
| 84 | + |
| 85 | + let content = content.as_ref(); |
| 86 | + |
| 87 | + if let Some(dir) = path.parent() { |
| 88 | + std::fs::create_dir_all(dir).map_err(|e| { |
| 89 | + format!( |
| 90 | + "Failed to create fixture directory {}: {}", |
| 91 | + dir.display(), |
| 92 | + e |
| 93 | + ) |
| 94 | + })?; |
| 95 | + } |
| 96 | + std::fs::write(&path, content) |
| 97 | + .map_err(|e| format!("Failed to write fixture {}: {}", path.display(), e))?; |
| 98 | + } |
| 99 | + Ok(()) |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +impl<const N: usize, P, S> DirFixture for [(P, S); N] |
| 104 | +where |
| 105 | + P: AsRef<std::path::Path>, |
| 106 | + P: std::fmt::Debug, |
| 107 | + S: AsRef<[u8]>, |
| 108 | + S: std::fmt::Debug, |
| 109 | +{ |
| 110 | + fn write_to_path(&self, root: &std::path::Path) -> Result<(), crate::assert::Error> { |
| 111 | + let s: &[(P, S)] = self; |
| 112 | + s.write_to_path(root) |
| 113 | + } |
| 114 | +} |
0 commit comments