laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use std::io;
use std::path::PathBuf;

use laravel::str::Str;

use crate::support::lang_path;

/// Locked translation keys, stored per language in `lang/.locked/{locale}.json`.
///
/// A locked key is never written by the scanner: it is not retranslated when the source text
/// changes, it is not touched by `--resync` and it is not removed by `--prune`. Nothing is locked
/// unless somebody locks it, so a project with no lock files behaves as if this did not exist.
pub struct TranslationLocks;

impl TranslationLocks {
    /// Path of the lock file of a language.
    pub fn path(lang: &str) -> PathBuf {
        lang_path().join(".locked").join(format!("{lang}.json"))
    }

    /// Locked keys of a language.
    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
    }

    /// Whether a key is locked in a language. Locked patterns support wildcards, so `errors.*`
    /// covers every key under errors.
    pub fn is_locked(lang: &str, key: &str) -> bool {
        Self::all(lang)
            .iter()
            .any(|locked| locked == key || key.resembles(locked))
    }

    /// Filter a list of keys down to the locked ones.
    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()
    }

    /// Lock keys in a language. Returns the keys that were not locked already.
    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)
    }

    /// Unlock keys in a language. Returns the keys that were actually removed.
    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)
    }

    /// Persist the lock file, removing it when nothing is left so that the absence of the file
    /// keeps meaning "nothing is locked".
    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)))
    }
}