rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
use std::{ffi::OsString, path::PathBuf};

/// Environment variable holding template roots, separated like `PATH`.
pub const VIEWS_ENV: &str = "SWORD_VIEWS";
/// Environment variable holding the template cache capacity.
pub const CACHE_CAPACITY_ENV: &str = "SWORD_CACHE_CAPACITY";
/// Environment variable holding the application environment name, such as `local`.
pub const ENVIRONMENT_ENV: &str = "SWORD_ENVIRONMENT";
/// The environment name used when none is configured. It is the conservative one, as in
/// Laravel: `@production` content shows and `@env('local')` content does not.
pub const DEFAULT_ENVIRONMENT: &str = "production";
/// Longest accepted environment name.
pub const MAX_ENVIRONMENT_LEN: usize = 64;
/// Environment variable that enables `@dump`; only read with the `dump` feature.
#[cfg(feature = "dump")]
pub const DUMP_ENV: &str = "SWORD_DUMP";
/// Default number of cached templates.
pub const DEFAULT_CACHE_CAPACITY: usize = 128;
/// Largest accepted cache capacity. The limit counts templates, not bytes.
pub const MAX_CACHE_CAPACITY: usize = 100_000;

/// Validated renderer configuration.
///
/// Build one with [`Config::builder`], [`Config::from_env`], or [`Config::default`]. Every
/// constructor validates its limits, so a `Config` is always usable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    roots: Vec<PathBuf>,
    cache_capacity: usize,
    environment: String,
    dump: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            roots: vec![PathBuf::from("resources/views")],
            cache_capacity: DEFAULT_CACHE_CAPACITY,
            environment: DEFAULT_ENVIRONMENT.to_owned(),
            dump: false,
        }
    }
}

impl Config {
    /// Start a builder with conservative defaults.
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::default()
    }

    /// Read `SWORD_VIEWS`, `SWORD_CACHE_CAPACITY` and `SWORD_ENVIRONMENT` once, at application startup.
    ///
    /// Unset variables keep the defaults. Do not call this on a request path; use
    /// [`ConfigBuilder::from_env`] to override the result programmatically.
    pub fn from_env() -> Result<Self, ConfigError> {
        ConfigBuilder::from_env()?.build()
    }

    /// Template roots, searched in order.
    pub fn roots(&self) -> &[PathBuf] {
        &self.roots
    }

    /// Maximum number of cached templates; zero disables the cache.
    pub fn cache_capacity(&self) -> usize {
        self.cache_capacity
    }

    /// The application environment `@env` and `@production` compare against. Under the
    /// Laravel adapter the framework's own environment is used instead.
    pub fn environment(&self) -> &str {
        &self.environment
    }

    /// Whether `@dump` was enabled. It still runs only in a `local` or `testing` environment.
    #[cfg(feature = "dump")]
    pub fn dump(&self) -> bool {
        self.dump
    }
}

/// Builds a [`Config`]. Values set on the builder override environment-derived ones.
#[derive(Debug, Clone, Default)]
pub struct ConfigBuilder {
    env_roots: Option<Vec<PathBuf>>,
    roots: Option<Vec<PathBuf>>,
    cache_capacity: Option<usize>,
    environment: Option<String>,
    dump: Option<bool>,
}

impl ConfigBuilder {
    /// Seed the builder from the process environment. See [`Config::from_env`].
    pub fn from_env() -> Result<Self, ConfigError> {
        Self::from_vars(|name| std::env::var_os(name))
    }

    /// Seed the builder from a variable source, which keeps tests off the process
    /// environment.
    pub fn from_vars(get: impl Fn(&str) -> Option<OsString>) -> Result<Self, ConfigError> {
        let mut builder = Self::default();
        if let Some(value) = get(VIEWS_ENV) {
            builder.env_roots = Some(std::env::split_paths(&value).collect());
        }
        if let Some(value) = get(CACHE_CAPACITY_ENV) {
            let value = value
                .into_string()
                .map_err(|_| ConfigError::NotUnicode(CACHE_CAPACITY_ENV))?;
            builder.cache_capacity = Some(
                value
                    .trim()
                    .parse()
                    .map_err(|_| ConfigError::NotANumber(CACHE_CAPACITY_ENV))?,
            );
        }
        if let Some(value) = get(ENVIRONMENT_ENV) {
            builder.environment = Some(
                value
                    .into_string()
                    .map_err(|_| ConfigError::NotUnicode(ENVIRONMENT_ENV))?,
            );
        }
        #[cfg(feature = "dump")]
        if let Some(value) = get(DUMP_ENV) {
            let value = value
                .into_string()
                .map_err(|_| ConfigError::NotUnicode(DUMP_ENV))?;
            builder.dump = Some(matches!(value.trim(), "1" | "true"));
        }
        Ok(builder)
    }

    /// Append a template root. The first explicit root replaces any environment roots.
    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
        self.roots.get_or_insert_with(Vec::new).push(root.into());
        self
    }

    /// Replace all roots, including environment-derived ones.
    pub fn roots(mut self, roots: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
        self.roots = Some(roots.into_iter().map(Into::into).collect());
        self
    }

    /// Set the cache capacity; zero disables caching.
    pub fn cache_capacity(mut self, capacity: usize) -> Self {
        self.cache_capacity = Some(capacity);
        self
    }

    /// Set the environment name, such as `local`, `staging` or `production`. It must be 1 to
    /// 64 letters, digits, `_`, `-` or `.`.
    pub fn environment(mut self, name: impl Into<String>) -> Self {
        self.environment = Some(name.into());
        self
    }

    /// Enable `@dump`, a development tool. It is off by default and renders nothing outside a
    /// `local` or `testing` environment, whatever is set here.
    #[cfg(feature = "dump")]
    pub fn dump(mut self, enabled: bool) -> Self {
        self.dump = Some(enabled);
        self
    }

    /// Validate the limits and build the configuration.
    pub fn build(self) -> Result<Config, ConfigError> {
        let defaults = Config::default();
        let roots = self.roots.or(self.env_roots).unwrap_or(defaults.roots);
        if roots.is_empty() {
            return Err(ConfigError::NoRoots);
        }
        if roots.iter().any(|root| root.as_os_str().is_empty()) {
            return Err(ConfigError::EmptyRoot);
        }
        let cache_capacity = self.cache_capacity.unwrap_or(defaults.cache_capacity);
        if cache_capacity > MAX_CACHE_CAPACITY {
            return Err(ConfigError::CacheCapacityTooLarge {
                value: cache_capacity,
                max: MAX_CACHE_CAPACITY,
            });
        }
        let environment = self.environment.unwrap_or(defaults.environment);
        let valid = !environment.is_empty()
            && environment.len() <= MAX_ENVIRONMENT_LEN
            && environment
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
        if !valid {
            return Err(ConfigError::InvalidEnvironment);
        }
        Ok(Config {
            roots,
            cache_capacity,
            environment,
            dump: self.dump.unwrap_or(false),
        })
    }
}

/// An invalid Sword configuration. Messages never include variable values.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// No template root was configured.
    #[error("at least one template root is required")]
    NoRoots,
    /// A template root is an empty path.
    #[error("template roots must not be empty paths")]
    EmptyRoot,
    /// The cache capacity is above [`MAX_CACHE_CAPACITY`].
    #[error("cache capacity {value} exceeds the maximum of {max}")]
    CacheCapacityTooLarge {
        /// The requested capacity.
        value: usize,
        /// The largest allowed capacity.
        max: usize,
    },
    /// The environment name is not 1 to 64 letters, digits, `_`, `-` or `.`.
    #[error("the environment name must be 1 to 64 letters, digits, `_`, `-` or `.`")]
    InvalidEnvironment,
    /// An environment variable (named here) is not valid unicode.
    #[error("{0} must be valid unicode")]
    NotUnicode(&'static str),
    /// An environment variable (named here) is not a non-negative whole number.
    #[error("{0} must be a non-negative whole number")]
    NotANumber(&'static str),
}