use std::collections::BTreeMap;
use std::path::Path;
use compmd_pack::{FilePath, Place};
use crate::bundle_error::BundleError;
use crate::files::Files;
use crate::manifest::Manifest;
pub const MANIFEST: &str = "manifest.json";
#[derive(Clone, Debug, PartialEq)]
pub struct Bundle {
manifest: Manifest,
files: Files,
}
impl Bundle {
pub fn embedded(files: &'static [(&'static str, &'static [u8])]) -> Result<Self, BundleError> {
Self::with(Files::Embedded(files))
}
pub fn read(folder: &Path) -> Result<Self, BundleError> {
Self::with(Files::Folder(folder.to_path_buf()))
}
pub fn from_files<P: Into<String>>(
files: impl IntoIterator<Item = (P, Vec<u8>)>,
) -> Result<Self, BundleError> {
let files: BTreeMap<String, Vec<u8>> = files
.into_iter()
.map(|(path, bytes)| (path.into(), bytes))
.collect();
Self::with(Files::Owned(files))
}
fn with(files: Files) -> Result<Self, BundleError> {
let text = files.read(MANIFEST).ok_or(BundleError::NoManifest)?;
let manifest = Manifest::parse(&String::from_utf8_lossy(&text))?;
Ok(Self { manifest, files })
}
#[must_use]
pub const fn manifest(&self) -> &Manifest {
&self.manifest
}
#[must_use]
pub fn frame_file(&self, path: &FilePath) -> Option<Vec<u8>> {
self.files
.read(&format!("frames/{}/{path}", self.manifest.frames.hash))
}
#[must_use]
pub fn pack_file(&self, place: &Place) -> Option<Vec<u8>> {
self.manifest.pack(&place.release)?;
self.files.read(&format!("packs/{place}"))
}
#[must_use]
pub fn frames_base(&self, origin: &str) -> String {
format!(
"{}/frames/{}/",
origin.trim_end_matches('/'),
self.manifest.frames.hash
)
}
}
#[cfg(test)]
pub(crate) mod tests;