use std::io;
use std::path::PathBuf;
use laravel::str::Str;
use crate::support::lang_path;
pub struct TranslationLocks;
impl TranslationLocks {
pub fn path(lang: &str) -> PathBuf {
lang_path().join(".locked").join(format!("{lang}.json"))
}
pub fn all(lang: &str) -> Vec<String> {
let Ok(content) = std::fs::read_to_string(Self::path(lang)) else {
return Vec::new();
};
let Ok(keys) = serde_json::from_str::<Vec<String>>(&content) else {
return Vec::new();
};
let mut unique: Vec<String> = Vec::with_capacity(keys.len());
for key in keys {
if !unique.contains(&key) {
unique.push(key);
}
}
unique
}
pub fn is_locked(lang: &str, key: &str) -> bool {
Self::all(lang)
.iter()
.any(|locked| locked == key || key.resembles(locked))
}
pub fn locked_among(lang: &str, keys: &[String]) -> Vec<String> {
let locked = Self::all(lang);
keys.iter()
.filter(|key| locked.iter().any(|pattern| pattern == *key || key.resembles(pattern)))
.cloned()
.collect()
}
pub fn lock(lang: &str, keys: &[String]) -> io::Result<Vec<String>> {
let current = Self::all(lang);
let mut added: Vec<String> = Vec::new();
for key in keys {
if !current.contains(key) && !added.contains(key) {
added.push(key.clone());
}
}
if !added.is_empty() {
let mut all = current;
all.extend(added.iter().cloned());
Self::write(lang, all)?;
}
Ok(added)
}
pub fn unlock(lang: &str, keys: &[String]) -> io::Result<Vec<String>> {
let current = Self::all(lang);
let removed: Vec<String> = current.iter().filter(|key| keys.contains(key)).cloned().collect();
if !removed.is_empty() {
let remaining = current.into_iter().filter(|key| !removed.contains(key)).collect();
Self::write(lang, remaining)?;
}
Ok(removed)
}
fn write(lang: &str, mut keys: Vec<String>) -> io::Result<()> {
let path = Self::path(lang);
keys.sort();
keys.dedup();
if keys.is_empty() {
return match std::fs::remove_file(&path) {
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
_ => Ok(()),
};
}
if let Some(directory) = path.parent() {
std::fs::create_dir_all(directory)?;
}
std::fs::write(&path, format!("{}\n", crate::json::pretty(&keys, true)))
}
}