larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

use crate::blog::Shared;
use crate::{Blog, Error, LarablogConfig};

/// The manager behind [`collection`](crate::collection): one [`Blog`] per collection of the
/// configuration, each remembering what it has read.
#[derive(Clone)]
pub struct Larablog {
    inner: Arc<Inner>,
}

struct Inner {
    shared: Arc<Shared>,
    blogs: Mutex<HashMap<String, Blog>>,
}

/// The manager of one application, kept in its configuration so the synchronous helpers of this
/// crate (`larablog::collection`, `Post::url`) can reach it: Laravel Rust 0.1 resolves services
/// only asynchronously.
pub(crate) struct Runtime(pub(crate) Larablog);

impl Default for Larablog {
    fn default() -> Self {
        Self::new()
    }
}

impl Larablog {
    /// A manager with nothing read yet.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Inner {
                shared: Arc::new(Shared::new()),
                blogs: Mutex::new(HashMap::new()),
            }),
        }
    }

    /// A collection by its name.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::UnknownCollection`] when the configuration has no such collection.
    pub fn get(&self, name: &str) -> Result<Blog, Error> {
        if !laravel::config()
            .section::<LarablogConfig>()
            .collections
            .contains_key(name)
        {
            return Err(Error::UnknownCollection(name.to_owned()));
        }

        let mut blogs = self.inner.blogs.lock().unwrap_or_else(PoisonError::into_inner);

        Ok(blogs
            .entry(name.to_owned())
            .or_insert_with(|| Blog::new(name, Arc::clone(&self.inner.shared)))
            .clone())
    }

    /// Every collection of the configuration, by name.
    pub fn collections(&self) -> Vec<(String, Blog)> {
        laravel::config()
            .section::<LarablogConfig>()
            .collections
            .keys()
            .filter_map(|name| self.get(name).ok().map(|blog| (name.clone(), blog)))
            .collect()
    }
}