Skip to main content

rustysan_sword/
config.rs

1use std::{ffi::OsString, path::PathBuf};
2
3/// Environment variable holding template roots, separated like `PATH`.
4pub const VIEWS_ENV: &str = "SWORD_VIEWS";
5/// Environment variable holding the template cache capacity.
6pub const CACHE_CAPACITY_ENV: &str = "SWORD_CACHE_CAPACITY";
7/// Environment variable holding the application environment name, such as `local`.
8pub const ENVIRONMENT_ENV: &str = "SWORD_ENVIRONMENT";
9/// The environment name used when none is configured. It is the conservative one, as in
10/// Laravel: `@production` content shows and `@env('local')` content does not.
11pub const DEFAULT_ENVIRONMENT: &str = "production";
12/// Longest accepted environment name.
13pub const MAX_ENVIRONMENT_LEN: usize = 64;
14/// Environment variable that enables `@dump`; only read with the `dump` feature.
15#[cfg(feature = "dump")]
16pub const DUMP_ENV: &str = "SWORD_DUMP";
17/// Default number of cached templates.
18pub const DEFAULT_CACHE_CAPACITY: usize = 128;
19/// Largest accepted cache capacity. The limit counts templates, not bytes.
20pub const MAX_CACHE_CAPACITY: usize = 100_000;
21
22/// Validated renderer configuration.
23///
24/// Build one with [`Config::builder`], [`Config::from_env`], or [`Config::default`]. Every
25/// constructor validates its limits, so a `Config` is always usable.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Config {
28    roots: Vec<PathBuf>,
29    cache_capacity: usize,
30    environment: String,
31    dump: bool,
32}
33
34impl Default for Config {
35    fn default() -> Self {
36        Self {
37            roots: vec![PathBuf::from("resources/views")],
38            cache_capacity: DEFAULT_CACHE_CAPACITY,
39            environment: DEFAULT_ENVIRONMENT.to_owned(),
40            dump: false,
41        }
42    }
43}
44
45impl Config {
46    /// Start a builder with conservative defaults.
47    pub fn builder() -> ConfigBuilder {
48        ConfigBuilder::default()
49    }
50
51    /// Read `SWORD_VIEWS`, `SWORD_CACHE_CAPACITY` and `SWORD_ENVIRONMENT` once, at application startup.
52    ///
53    /// Unset variables keep the defaults. Do not call this on a request path; use
54    /// [`ConfigBuilder::from_env`] to override the result programmatically.
55    pub fn from_env() -> Result<Self, ConfigError> {
56        ConfigBuilder::from_env()?.build()
57    }
58
59    /// Template roots, searched in order.
60    pub fn roots(&self) -> &[PathBuf] {
61        &self.roots
62    }
63
64    /// Maximum number of cached templates; zero disables the cache.
65    pub fn cache_capacity(&self) -> usize {
66        self.cache_capacity
67    }
68
69    /// The application environment `@env` and `@production` compare against. Under the
70    /// Laravel adapter the framework's own environment is used instead.
71    pub fn environment(&self) -> &str {
72        &self.environment
73    }
74
75    /// Whether `@dump` was enabled. It still runs only in a `local` or `testing` environment.
76    #[cfg(feature = "dump")]
77    pub fn dump(&self) -> bool {
78        self.dump
79    }
80}
81
82/// Builds a [`Config`]. Values set on the builder override environment-derived ones.
83#[derive(Debug, Clone, Default)]
84pub struct ConfigBuilder {
85    env_roots: Option<Vec<PathBuf>>,
86    roots: Option<Vec<PathBuf>>,
87    cache_capacity: Option<usize>,
88    environment: Option<String>,
89    dump: Option<bool>,
90}
91
92impl ConfigBuilder {
93    /// Seed the builder from the process environment. See [`Config::from_env`].
94    pub fn from_env() -> Result<Self, ConfigError> {
95        Self::from_vars(|name| std::env::var_os(name))
96    }
97
98    /// Seed the builder from a variable source, which keeps tests off the process
99    /// environment.
100    pub fn from_vars(get: impl Fn(&str) -> Option<OsString>) -> Result<Self, ConfigError> {
101        let mut builder = Self::default();
102        if let Some(value) = get(VIEWS_ENV) {
103            builder.env_roots = Some(std::env::split_paths(&value).collect());
104        }
105        if let Some(value) = get(CACHE_CAPACITY_ENV) {
106            let value = value
107                .into_string()
108                .map_err(|_| ConfigError::NotUnicode(CACHE_CAPACITY_ENV))?;
109            builder.cache_capacity = Some(
110                value
111                    .trim()
112                    .parse()
113                    .map_err(|_| ConfigError::NotANumber(CACHE_CAPACITY_ENV))?,
114            );
115        }
116        if let Some(value) = get(ENVIRONMENT_ENV) {
117            builder.environment = Some(
118                value
119                    .into_string()
120                    .map_err(|_| ConfigError::NotUnicode(ENVIRONMENT_ENV))?,
121            );
122        }
123        #[cfg(feature = "dump")]
124        if let Some(value) = get(DUMP_ENV) {
125            let value = value
126                .into_string()
127                .map_err(|_| ConfigError::NotUnicode(DUMP_ENV))?;
128            builder.dump = Some(matches!(value.trim(), "1" | "true"));
129        }
130        Ok(builder)
131    }
132
133    /// Append a template root. The first explicit root replaces any environment roots.
134    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
135        self.roots.get_or_insert_with(Vec::new).push(root.into());
136        self
137    }
138
139    /// Replace all roots, including environment-derived ones.
140    pub fn roots(mut self, roots: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
141        self.roots = Some(roots.into_iter().map(Into::into).collect());
142        self
143    }
144
145    /// Set the cache capacity; zero disables caching.
146    pub fn cache_capacity(mut self, capacity: usize) -> Self {
147        self.cache_capacity = Some(capacity);
148        self
149    }
150
151    /// Set the environment name, such as `local`, `staging` or `production`. It must be 1 to
152    /// 64 letters, digits, `_`, `-` or `.`.
153    pub fn environment(mut self, name: impl Into<String>) -> Self {
154        self.environment = Some(name.into());
155        self
156    }
157
158    /// Enable `@dump`, a development tool. It is off by default and renders nothing outside a
159    /// `local` or `testing` environment, whatever is set here.
160    #[cfg(feature = "dump")]
161    pub fn dump(mut self, enabled: bool) -> Self {
162        self.dump = Some(enabled);
163        self
164    }
165
166    /// Validate the limits and build the configuration.
167    pub fn build(self) -> Result<Config, ConfigError> {
168        let defaults = Config::default();
169        let roots = self.roots.or(self.env_roots).unwrap_or(defaults.roots);
170        if roots.is_empty() {
171            return Err(ConfigError::NoRoots);
172        }
173        if roots.iter().any(|root| root.as_os_str().is_empty()) {
174            return Err(ConfigError::EmptyRoot);
175        }
176        let cache_capacity = self.cache_capacity.unwrap_or(defaults.cache_capacity);
177        if cache_capacity > MAX_CACHE_CAPACITY {
178            return Err(ConfigError::CacheCapacityTooLarge {
179                value: cache_capacity,
180                max: MAX_CACHE_CAPACITY,
181            });
182        }
183        let environment = self.environment.unwrap_or(defaults.environment);
184        let valid = !environment.is_empty()
185            && environment.len() <= MAX_ENVIRONMENT_LEN
186            && environment
187                .chars()
188                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
189        if !valid {
190            return Err(ConfigError::InvalidEnvironment);
191        }
192        Ok(Config {
193            roots,
194            cache_capacity,
195            environment,
196            dump: self.dump.unwrap_or(false),
197        })
198    }
199}
200
201/// An invalid Sword configuration. Messages never include variable values.
202#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
203#[non_exhaustive]
204pub enum ConfigError {
205    /// No template root was configured.
206    #[error("at least one template root is required")]
207    NoRoots,
208    /// A template root is an empty path.
209    #[error("template roots must not be empty paths")]
210    EmptyRoot,
211    /// The cache capacity is above [`MAX_CACHE_CAPACITY`].
212    #[error("cache capacity {value} exceeds the maximum of {max}")]
213    CacheCapacityTooLarge {
214        /// The requested capacity.
215        value: usize,
216        /// The largest allowed capacity.
217        max: usize,
218    },
219    /// The environment name is not 1 to 64 letters, digits, `_`, `-` or `.`.
220    #[error("the environment name must be 1 to 64 letters, digits, `_`, `-` or `.`")]
221    InvalidEnvironment,
222    /// An environment variable (named here) is not valid unicode.
223    #[error("{0} must be valid unicode")]
224    NotUnicode(&'static str),
225    /// An environment variable (named here) is not a non-negative whole number.
226    #[error("{0} must be a non-negative whole number")]
227    NotANumber(&'static str),
228}