use super::{dict::Dictionary, err};
use rust_embed::EmbeddedFile;
use std::path::PathBuf;
pub struct EmbeddedMeta {
pub file: EmbeddedFile,
pub name: String,
}
impl Clone for EmbeddedMeta {
fn clone(&self) -> Self {
Self {
file: EmbeddedFile {
data: self.file.data.clone(),
metadata: rust_embed::Metadata::__rust_embed_new(
self.file.metadata.sha256_hash(),
self.file.metadata.last_modified(),
),
},
name: self.name.clone(),
}
}
}
#[derive(Clone)]
pub struct Config {
embed_assets: Vec<EmbeddedMeta>,
default_locale: String,
}
impl Default for Config {
fn default() -> Self {
Self::global()
}
}
impl Config {
pub(crate) fn global() -> Self {
Self {
default_locale: String::from("en"),
embed_assets: Vec::new(),
}
}
pub fn with_embed<T: rust_embed::RustEmbed>(mut self) -> Self {
T::iter().for_each(|filename| {
self.embed_assets.push(EmbeddedMeta {
file: T::get(filename.as_ref()).unwrap(),
name: filename.to_string(),
});
});
self
}
pub fn finish(self) -> err::Result<Dictionary> {
let mut out = Dictionary::default();
for asset in self.embed_assets {
let path = PathBuf::from(asset.name);
let locale = match path.file_stem().and_then(|x| x.to_str()) {
Some(locale) => locale.to_string(),
None => continue,
};
let value = match path.extension().and_then(|x| x.to_str()) {
Some("json") => {
serde_json::from_reader::<_, serde_json::Value>(asset.file.data.as_ref())?
}
#[cfg(feature = "yaml")]
Some("yml") => {
serde_yaml::from_reader::<_, serde_json::Value>(asset.file.data.as_ref())?
}
#[cfg(feature = "toml")]
Some("toml") => toml::from_slice::<serde_json::Value>(asset.file.data.as_ref())?,
_ => {
continue;
}
};
out.inner.insert(locale, value);
}
out.default_locale = self.default_locale.clone();
Ok(out)
}
}