1use std::collections::BTreeMap;
6use std::path::Path;
7
8use compmd_pack::{FilePath, Place};
9
10use crate::bundle_error::BundleError;
11use crate::files::Files;
12use crate::manifest::Manifest;
13use crate::store::Store;
14
15pub const MANIFEST: &str = "manifest.json";
17
18#[derive(Clone, Debug, PartialEq)]
20pub struct Bundle {
21 manifest: Manifest,
22 files: Files,
23}
24
25impl Bundle {
26 pub fn embedded(files: &'static [(&'static str, &'static [u8])]) -> Result<Self, BundleError> {
32 Self::with(Files::Embedded(files))
33 }
34
35 pub fn read(folder: &Path) -> Result<Self, BundleError> {
41 Self::with(Files::Folder(folder.to_path_buf()))
42 }
43
44 pub fn from_files<P: Into<String>>(
50 files: impl IntoIterator<Item = (P, Vec<u8>)>,
51 ) -> Result<Self, BundleError> {
52 let files: BTreeMap<String, Vec<u8>> = files
53 .into_iter()
54 .map(|(path, bytes)| (path.into(), bytes))
55 .collect();
56 Self::with(Files::Owned(files))
57 }
58
59 fn with(files: Files) -> Result<Self, BundleError> {
60 let text = files.read(MANIFEST).ok_or(BundleError::NoManifest)?;
61 let manifest = Manifest::parse(&String::from_utf8_lossy(&text))?;
62 Ok(Self { manifest, files })
63 }
64
65 #[must_use]
67 pub const fn manifest(&self) -> &Manifest {
68 &self.manifest
69 }
70
71 #[must_use]
73 pub fn frame_file(&self, path: &FilePath) -> Option<Vec<u8>> {
74 self.files
75 .read(&format!("frames/{}/{path}", self.manifest.frames.hash))
76 }
77
78 #[must_use]
80 pub fn pack_file(&self, place: &Place) -> Option<Vec<u8>> {
81 self.manifest.pack(&place.release)?;
82 self.files.read(&format!("packs/{place}"))
83 }
84
85 #[must_use]
88 pub fn pack_file_or(&self, store: &dyn Store, place: &Place) -> Option<Vec<u8>> {
89 self.pack_file(place).or_else(|| store.file(place))
90 }
91
92 #[must_use]
94 pub fn frames_base(&self, origin: &str) -> String {
95 format!(
96 "{}/frames/{}/",
97 origin.trim_end_matches('/'),
98 self.manifest.frames.hash
99 )
100 }
101}
102
103#[cfg(test)]
104pub(crate) mod tests;