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;
13
14pub const MANIFEST: &str = "manifest.json";
16
17#[derive(Clone, Debug, PartialEq)]
19pub struct Bundle {
20 manifest: Manifest,
21 files: Files,
22}
23
24impl Bundle {
25 pub fn embedded(files: &'static [(&'static str, &'static [u8])]) -> Result<Self, BundleError> {
31 Self::with(Files::Embedded(files))
32 }
33
34 pub fn read(folder: &Path) -> Result<Self, BundleError> {
40 Self::with(Files::Folder(folder.to_path_buf()))
41 }
42
43 pub fn from_files<P: Into<String>>(
49 files: impl IntoIterator<Item = (P, Vec<u8>)>,
50 ) -> Result<Self, BundleError> {
51 let files: BTreeMap<String, Vec<u8>> = files
52 .into_iter()
53 .map(|(path, bytes)| (path.into(), bytes))
54 .collect();
55 Self::with(Files::Owned(files))
56 }
57
58 fn with(files: Files) -> Result<Self, BundleError> {
59 let text = files.read(MANIFEST).ok_or(BundleError::NoManifest)?;
60 let manifest = Manifest::parse(&String::from_utf8_lossy(&text))?;
61 Ok(Self { manifest, files })
62 }
63
64 #[must_use]
66 pub const fn manifest(&self) -> &Manifest {
67 &self.manifest
68 }
69
70 #[must_use]
72 pub fn frame_file(&self, path: &FilePath) -> Option<Vec<u8>> {
73 self.files
74 .read(&format!("frames/{}/{path}", self.manifest.frames.hash))
75 }
76
77 #[must_use]
79 pub fn pack_file(&self, place: &Place) -> Option<Vec<u8>> {
80 self.manifest.pack(&place.release)?;
81 self.files.read(&format!("packs/{place}"))
82 }
83
84 #[must_use]
86 pub fn frames_base(&self, origin: &str) -> String {
87 format!(
88 "{}/frames/{}/",
89 origin.trim_end_matches('/'),
90 self.manifest.frames.hash
91 )
92 }
93}
94
95#[cfg(test)]
96pub(crate) mod tests;