1use std::{ffi::OsString, path::PathBuf};
2
3pub const VIEWS_ENV: &str = "SWORD_VIEWS";
5pub const CACHE_CAPACITY_ENV: &str = "SWORD_CACHE_CAPACITY";
7pub const ENVIRONMENT_ENV: &str = "SWORD_ENVIRONMENT";
9pub const DEFAULT_ENVIRONMENT: &str = "production";
12pub const MAX_ENVIRONMENT_LEN: usize = 64;
14#[cfg(feature = "dump")]
16pub const DUMP_ENV: &str = "SWORD_DUMP";
17pub const DEFAULT_CACHE_CAPACITY: usize = 128;
19pub const MAX_CACHE_CAPACITY: usize = 100_000;
21
22#[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 pub fn builder() -> ConfigBuilder {
48 ConfigBuilder::default()
49 }
50
51 pub fn from_env() -> Result<Self, ConfigError> {
56 ConfigBuilder::from_env()?.build()
57 }
58
59 pub fn roots(&self) -> &[PathBuf] {
61 &self.roots
62 }
63
64 pub fn cache_capacity(&self) -> usize {
66 self.cache_capacity
67 }
68
69 pub fn environment(&self) -> &str {
72 &self.environment
73 }
74
75 #[cfg(feature = "dump")]
77 pub fn dump(&self) -> bool {
78 self.dump
79 }
80}
81
82#[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 pub fn from_env() -> Result<Self, ConfigError> {
95 Self::from_vars(|name| std::env::var_os(name))
96 }
97
98 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 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 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 pub fn cache_capacity(mut self, capacity: usize) -> Self {
147 self.cache_capacity = Some(capacity);
148 self
149 }
150
151 pub fn environment(mut self, name: impl Into<String>) -> Self {
154 self.environment = Some(name.into());
155 self
156 }
157
158 #[cfg(feature = "dump")]
161 pub fn dump(mut self, enabled: bool) -> Self {
162 self.dump = Some(enabled);
163 self
164 }
165
166 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
203#[non_exhaustive]
204pub enum ConfigError {
205 #[error("at least one template root is required")]
207 NoRoots,
208 #[error("template roots must not be empty paths")]
210 EmptyRoot,
211 #[error("cache capacity {value} exceeds the maximum of {max}")]
213 CacheCapacityTooLarge {
214 value: usize,
216 max: usize,
218 },
219 #[error("the environment name must be 1 to 64 letters, digits, `_`, `-` or `.`")]
221 InvalidEnvironment,
222 #[error("{0} must be valid unicode")]
224 NotUnicode(&'static str),
225 #[error("{0} must be a non-negative whole number")]
227 NotANumber(&'static str),
228}