use std::io;
use std::path::{Path, PathBuf};
use backbeat_core::asset_id::AssetId;
#[derive(Clone)]
pub(crate) struct AssetStore {
root: PathBuf,
}
impl AssetStore {
pub(crate) fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub(crate) fn asset_path(&self, asset: AssetId) -> PathBuf {
self.root.join(asset.fanned_path())
}
pub(crate) fn store(&self, asset: AssetId, data: &[u8]) -> io::Result<()> {
let path = self.asset_path(asset);
if path.is_file() {
return Ok(());
}
if let Some(parent) = path.parent() {
crate::fs::create_dir_all(parent)?;
}
crate::fs::write(&path, data)?;
Ok(())
}
pub(crate) fn copy_into(&self, asset: AssetId, path: impl AsRef<Path>) -> io::Result<()> {
let dest = self.asset_path(asset);
if dest.is_file() {
return Ok(());
}
if let Some(parent) = dest.parent() {
crate::fs::create_dir_all(parent)?;
}
fs_err::copy(path, dest)?;
Ok(())
}
}