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::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, RwLock};
use std::time::SystemTime;

use indexmap::IndexMap;
use serde_json::Value;

use crate::json;
use crate::support::lang_file;

/// The lines of a language file, in the order the file has them. The values are strings, but the
/// file may hold anything and is written back as it was found.
pub type Lines = IndexMap<String, Value>;

type Stamp = (Option<SystemTime>, u64);

type Cache = HashMap<PathBuf, (Stamp, Arc<Lines>)>;

static CACHE: LazyLock<RwLock<Cache>> = LazyLock::new(RwLock::default);

/// The `lang/{locale}.json` files, which is where Laravel keeps JSON translations.
///
/// Lookups read through a cache that notices when a file changes, so a scan that rewrites a file
/// is seen by a running application without a restart.
pub struct Catalog;

impl Catalog {
    /// The lines of a locale's language file: none when the file does not exist or is not valid
    /// JSON, which is how Laravel treats it.
    pub fn lines(locale: &str) -> Arc<Lines> {
        let path = lang_file(locale);
        let stamp = stamp(&path);

        if let Some((cached, lines)) = CACHE.read().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&path)
            && *cached == stamp
        {
            return Arc::clone(lines);
        }

        let lines = Arc::new(Self::read(&path).ok().flatten().unwrap_or_default());

        CACHE
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .insert(path, (stamp, Arc::clone(&lines)));

        lines
    }

    /// Read a language file. `None` when it does not exist, an error when it is not valid JSON.
    pub fn read(path: &Path) -> io::Result<Option<Lines>> {
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };

        match serde_json::from_str::<Value>(&content) {
            Ok(Value::Object(_)) => serde_json::from_str::<Lines>(&content)
                .map(Some)
                .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)),
            // PHP writes an empty array as `[]`.
            Ok(Value::Array(items)) if items.is_empty() => Ok(Some(Lines::new())),
            Ok(_) => Err(io::Error::new(io::ErrorKind::InvalidData, "not a JSON object")),
            Err(error) => Err(io::Error::new(io::ErrorKind::InvalidData, error)),
        }
    }

    /// Write a language file the way the PHP package does: four spaces of indentation, unescaped
    /// unicode and slashes, and no newline at the end. The folder is created when it is missing.
    pub fn write(path: &Path, lines: &Lines) -> io::Result<()> {
        if let Some(directory) = path.parent() {
            std::fs::create_dir_all(directory)?;
        }

        let content = if lines.is_empty() {
            "[]".to_owned()
        } else {
            json::pretty(lines, true)
        };

        std::fs::write(path, content)?;

        Self::forget(path);

        Ok(())
    }

    /// Drop what is cached for a file, so the next lookup reads it again.
    pub fn forget(path: &Path) {
        CACHE
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(path);
    }

    /// Drop everything that is cached.
    pub fn flush() {
        CACHE.write().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
    }
}

fn stamp(path: &Path) -> Stamp {
    match std::fs::metadata(path) {
        Ok(metadata) => (metadata.modified().ok(), metadata.len()),
        Err(_) => (None, 0),
    }
}