monorepo/l10n-db/src/bundle.rs
2025-02-22 19:11:29 -05:00

53 lines
1.4 KiB
Rust

use std::{collections::HashMap, fs::File, io::Write, path::PathBuf};
use crate::{Message, WriteError};
pub struct Bundle {
path: PathBuf,
messages: HashMap<String, Message>,
}
impl Bundle {
pub fn load_from_disk(path: PathBuf) -> Self {
let mut messages = HashMap::new();
if path.is_dir() {
for entry in std::fs::read_dir(&path).unwrap() {
let entry = entry.unwrap();
let path = entry.path().clone();
let key = path.file_stem().unwrap();
let message = Message::from_file(&entry.path());
messages.insert(key.to_str().unwrap().to_owned(), message);
}
}
Self { path, messages }
}
pub fn message_iter(&self) -> impl Iterator<Item = (&String, &Message)> {
self.messages.iter()
}
pub fn message(&mut self, name: String) -> &mut Message {
self.messages
.entry(name.to_owned())
.or_insert(Message::new(name.to_owned()))
}
pub fn save(&self) {
self.messages.iter().for_each(|(key, value)| {
let mut path = self.path.clone();
path.push(key);
path.set_extension("toml");
save_file(&path, toml::to_string(value).unwrap().as_bytes());
});
}
}
fn save_file(path: &PathBuf, s: &[u8]) {
let mut f = File::create(path).unwrap();
f.write(s).unwrap();
}
#[cfg(test)]
mod test {}