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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use crate::{
error::{BundleError, MrBundleResult},
location::Location,
manifest::Manifest,
resource::ResourceBytes,
};
use holochain_util::ffs;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
path::{Path, PathBuf},
};
pub type ResourceMap = HashMap<PathBuf, ResourceBytes>;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Bundle<M>
where
M: Manifest,
{
#[serde(bound(deserialize = "M: DeserializeOwned"))]
manifest: M,
resources: ResourceMap,
#[serde(skip)]
root_dir: Option<PathBuf>,
}
impl<M> Bundle<M>
where
M: Manifest,
{
pub fn new<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
manifest: M,
resources: R,
root_dir: PathBuf,
) -> MrBundleResult<Self> {
Self::from_parts(manifest, resources, Some(root_dir))
}
pub fn new_unchecked<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
manifest: M,
resources: R,
) -> MrBundleResult<Self> {
Self::from_parts(manifest, resources, None)
}
fn from_parts<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
manifest: M,
resources: R,
root_dir: Option<PathBuf>,
) -> MrBundleResult<Self> {
let resources: ResourceMap = resources.into_iter().collect();
let manifest_paths: HashSet<_> = manifest
.locations()
.into_iter()
.filter_map(|loc| match loc {
Location::Bundled(path) => Some(path),
_ => None,
})
.collect();
for (resource_path, _) in resources.iter() {
if !manifest_paths.contains(resource_path) {
return Err(BundleError::BundledPathNotInManifest(resource_path.clone()).into());
}
}
let resources = resources.into_iter().collect();
Ok(Self {
manifest,
resources,
root_dir,
})
}
pub fn manifest(&self) -> &M {
&self.manifest
}
pub fn update_manifest(self, manifest: M) -> MrBundleResult<Self> {
Self::from_parts(manifest, self.resources, self.root_dir)
}
pub async fn read_from_file(path: &Path) -> MrBundleResult<Self> {
Ok(Self::decode(&ffs::read(path).await?)?)
}
pub async fn write_to_file(&self, path: &Path) -> MrBundleResult<()> {
Ok(ffs::write(path, &self.encode()?).await?)
}
pub async fn resolve(&self, location: &Location) -> MrBundleResult<Cow<'_, ResourceBytes>> {
let bytes = match &location.normalize(self.root_dir.as_ref())? {
Location::Bundled(path) => Cow::Borrowed(
self.resources
.get(path)
.ok_or_else(|| BundleError::BundledResourceMissing(path.clone()))?,
),
Location::Path(path) => Cow::Owned(crate::location::resolve_local(path).await?),
Location::Url(url) => Cow::Owned(crate::location::resolve_remote(url).await?),
};
Ok(bytes)
}
pub async fn resolve_all(&self) -> MrBundleResult<HashMap<Location, Cow<'_, ResourceBytes>>> {
futures::future::join_all(
self.manifest.locations().into_iter().map(|loc| async move {
MrBundleResult::Ok((loc.clone(), self.resolve(&loc).await?))
}),
)
.await
.into_iter()
.collect::<MrBundleResult<HashMap<Location, Cow<'_, ResourceBytes>>>>()
}
pub async fn resolve_all_cloned(&self) -> MrBundleResult<HashMap<Location, ResourceBytes>> {
Ok(self
.resolve_all()
.await?
.into_iter()
.map(|(k, v)| (k, v.into_owned()))
.collect())
}
pub fn bundled_resources(&self) -> &ResourceMap {
&self.resources
}
pub fn encode(&self) -> MrBundleResult<Vec<u8>> {
crate::encode(self)
}
pub fn decode(bytes: &[u8]) -> MrBundleResult<Self> {
crate::decode(bytes)
}
#[cfg(feature = "packing")]
pub fn find_root_dir(&self, path: &Path) -> MrBundleResult<PathBuf> {
crate::util::prune_path(path.into(), M::path()).map_err(Into::into)
}
}
#[cfg(test)]
mod tests {
use crate::error::MrBundleError;
use super::*;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct TestManifest(Vec<Location>);
impl Manifest for TestManifest {
fn locations(&self) -> Vec<Location> {
self.0.clone()
}
#[cfg(feature = "packing")]
fn path() -> PathBuf {
unimplemented!()
}
#[cfg(feature = "packing")]
fn bundle_extension() -> &'static str {
unimplemented!()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Thing(u32);
#[tokio::test]
async fn bundle_validation() {
let manifest = TestManifest(vec![
Location::Bundled("1.thing".into()),
Location::Bundled("2.thing".into()),
]);
assert!(Bundle::new_unchecked(manifest.clone(), vec![("1.thing".into(), vec![1])]).is_ok());
matches::assert_matches!(
Bundle::new_unchecked(manifest, vec![("3.thing".into(), vec![3])]),
Err(MrBundleError::BundleError(BundleError::BundledPathNotInManifest(path))) if path == PathBuf::from("3.thing")
);
}
}