laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

/// Remembers the fingerprint of every card that was generated.
///
/// Without this, "has this card changed?" can only be answered by "does the file exist?", which is why
/// a card with the publish date printed on it has to be deleted by hand whenever the date moves.
pub struct Manifest {
    path: PathBuf,
    state: Mutex<State>,
}

#[derive(Default)]
struct State {
    entries: BTreeMap<String, String>,
    loaded: bool,
}

impl Manifest {
    /// A manifest stored at `path`. Nothing is read until it is asked something.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            state: Mutex::new(State::default()),
        }
    }

    /// Whether the card has to be generated: its file is gone, or its fingerprint is not the recorded one.
    pub fn is_stale(&self, key: &str, fingerprint: &str, output: &Path) -> bool {
        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);

        self.load(&mut state);

        if !output.is_file() {
            return true;
        }

        state.entries.get(key).map(String::as_str) != Some(fingerprint)
    }

    /// Record the fingerprint of a card that was just generated.
    pub fn put(&self, key: &str, fingerprint: &str) {
        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);

        self.load(&mut state);
        state.entries.insert(key.to_owned(), fingerprint.to_owned());
    }

    /// Write the manifest to disk. Does nothing when it was never read or changed.
    ///
    /// # Errors
    ///
    /// Fails when the directory or the file cannot be written.
    pub fn save(&self) -> laravel::Result<()> {
        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);

        if !state.loaded {
            return Ok(());
        }

        if let Some(directory) = self.path.parent() {
            std::fs::create_dir_all(directory)?;
        }

        std::fs::write(&self.path, serde_json::to_string_pretty(&state.entries)?)?;

        Ok(())
    }

    fn load(&self, state: &mut State) {
        if state.loaded {
            return;
        }

        state.loaded = true;

        if let Ok(contents) = std::fs::read_to_string(&self.path) {
            state.entries = serde_json::from_str(&contents).unwrap_or_default();
        }
    }
}