use std::{ffi::OsString, path::PathBuf};
pub const VIEWS_ENV: &str = "SWORD_VIEWS";
pub const CACHE_CAPACITY_ENV: &str = "SWORD_CACHE_CAPACITY";
pub const ENVIRONMENT_ENV: &str = "SWORD_ENVIRONMENT";
pub const DEFAULT_ENVIRONMENT: &str = "production";
pub const MAX_ENVIRONMENT_LEN: usize = 64;
#[cfg(feature = "dump")]
pub const DUMP_ENV: &str = "SWORD_DUMP";
pub const DEFAULT_CACHE_CAPACITY: usize = 128;
pub const MAX_CACHE_CAPACITY: usize = 100_000;
#[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 {
pub fn builder() -> ConfigBuilder {
ConfigBuilder::default()
}
pub fn from_env() -> Result<Self, ConfigError> {
ConfigBuilder::from_env()?.build()
}
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
pub fn cache_capacity(&self) -> usize {
self.cache_capacity
}
pub fn environment(&self) -> &str {
&self.environment
}
#[cfg(feature = "dump")]
pub fn dump(&self) -> bool {
self.dump
}
}
#[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 {
pub fn from_env() -> Result<Self, ConfigError> {
Self::from_vars(|name| std::env::var_os(name))
}
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)
}
pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
self.roots.get_or_insert_with(Vec::new).push(root.into());
self
}
pub fn roots(mut self, roots: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
self.roots = Some(roots.into_iter().map(Into::into).collect());
self
}
pub fn cache_capacity(mut self, capacity: usize) -> Self {
self.cache_capacity = Some(capacity);
self
}
pub fn environment(mut self, name: impl Into<String>) -> Self {
self.environment = Some(name.into());
self
}
#[cfg(feature = "dump")]
pub fn dump(mut self, enabled: bool) -> Self {
self.dump = Some(enabled);
self
}
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),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("at least one template root is required")]
NoRoots,
#[error("template roots must not be empty paths")]
EmptyRoot,
#[error("cache capacity {value} exceeds the maximum of {max}")]
CacheCapacityTooLarge {
value: usize,
max: usize,
},
#[error("the environment name must be 1 to 64 letters, digits, `_`, `-` or `.`")]
InvalidEnvironment,
#[error("{0} must be valid unicode")]
NotUnicode(&'static str),
#[error("{0} must be a non-negative whole number")]
NotANumber(&'static str),
}