Skip to main content

mads_core/
config.rs

1//! Deterministic configuration sources and merged configuration values.
2//!
3//! Configuration loading is explicit. Dotenv files supply interpolation values;
4//! ordinary sources merge from first to last, so the final source wins on a key:
5//!
6//! ```no_run
7//! use mads_core::{ConfigBuilder, DotenvSource, EnvSource, Mads, TomlSource};
8//!
9//! # async fn example() -> mads_core::Result<()> {
10//! let config = ConfigBuilder::new()
11//!     .dotenv(DotenvSource::optional(".env"))
12//!     .source(TomlSource::file("mads.toml"))
13//!     .source(EnvSource::new("MADS_"))
14//!     .build()?;
15//! let application = Mads::builder_with_config(config).build().await?;
16//! # let _ = application;
17//! # Ok(())
18//! # }
19//! ```
20//!
21//! TOML and programmatic sources may contain string arrays. A later scalar or
22//! string array replaces the earlier value and its shape completely. Process
23//! environment variables override dotenv variables during `${NAME}`
24//! interpolation; [`EnvSource`] itself remains scalar-only.
25
26use std::collections::{BTreeMap, BTreeSet};
27use std::ffi::OsString;
28use std::fmt;
29use std::path::{Path, PathBuf};
30
31use crate::{Diagnostic, Error, MADS020, Result};
32
33/// A redacted configuration document containing supported value shapes.
34#[derive(Clone, Default, Eq, PartialEq)]
35pub struct ConfigDocument {
36    scalars: BTreeMap<String, String>,
37    string_arrays: BTreeMap<String, Vec<String>>,
38    tables: BTreeSet<String>,
39}
40
41impl fmt::Debug for ConfigDocument {
42    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
43        formatter
44            .debug_struct("ConfigDocument")
45            .field("entries", &self.len())
46            .field("values", &"[REDACTED]")
47            .finish()
48    }
49}
50
51impl ConfigDocument {
52    /// Creates an empty configuration document.
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    /// Creates a configuration document from scalar values.
58    pub fn from_scalars(values: BTreeMap<String, String>) -> Self {
59        Self {
60            scalars: values,
61            string_arrays: BTreeMap::new(),
62            tables: BTreeSet::new(),
63        }
64    }
65
66    /// Inserts a scalar, replacing any value at the same key.
67    pub fn insert_scalar(&mut self, key: impl Into<String>, value: impl Into<String>) {
68        let key = key.into();
69        self.string_arrays.remove(&key);
70        self.scalars.insert(key, value.into());
71    }
72
73    /// Inserts a string array, replacing any value at the same key.
74    pub fn insert_string_array<I, V>(&mut self, key: impl Into<String>, values: I)
75    where
76        I: IntoIterator<Item = V>,
77        V: Into<String>,
78    {
79        let key = key.into();
80        self.scalars.remove(&key);
81        self.string_arrays
82            .insert(key, values.into_iter().map(Into::into).collect());
83    }
84
85    /// Records a table path without adding a configuration value.
86    pub fn insert_table(&mut self, key: impl Into<String>) {
87        self.tables.insert(key.into());
88    }
89
90    /// Returns the number of configuration entries across all value shapes.
91    pub fn len(&self) -> usize {
92        self.scalars.len() + self.string_arrays.len()
93    }
94
95    /// Returns whether the document has no configuration entries.
96    pub fn is_empty(&self) -> bool {
97        self.scalars.is_empty() && self.string_arrays.is_empty()
98    }
99}
100
101/// A source of string configuration values.
102pub trait ConfigSource: Send + Sync {
103    /// Returns the source name used for attribution.
104    fn name(&self) -> &str;
105
106    /// Returns the base directory for relative path values from this source.
107    fn relative_path_base(&self) -> Option<&Path> {
108        None
109    }
110
111    /// Loads the source's configuration values.
112    #[allow(clippy::result_large_err)]
113    fn load(&self) -> Result<BTreeMap<String, String>>;
114
115    /// Loads all supported configuration value shapes.
116    #[allow(clippy::result_large_err)]
117    fn load_document(&self) -> Result<ConfigDocument> {
118        self.load().map(ConfigDocument::from_scalars)
119    }
120}
121
122/// A fixed, named set of configuration values.
123#[derive(Clone, Eq, PartialEq)]
124pub struct MapSource {
125    name: String,
126    scalars: BTreeMap<String, String>,
127    string_arrays: BTreeMap<String, Vec<String>>,
128}
129
130impl fmt::Debug for MapSource {
131    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132        formatter
133            .debug_struct("MapSource")
134            .field("name", &self.name)
135            .field("entries", &(self.scalars.len() + self.string_arrays.len()))
136            .field("values", &"[REDACTED]")
137            .finish()
138    }
139}
140
141impl MapSource {
142    /// Creates a named source from an iterable of key-value pairs.
143    pub fn new<I, K, V>(name: impl Into<String>, values: I) -> Self
144    where
145        I: IntoIterator<Item = (K, V)>,
146        K: Into<String>,
147        V: Into<String>,
148    {
149        Self {
150            name: name.into(),
151            scalars: values
152                .into_iter()
153                .map(|(key, value)| (key.into(), value.into()))
154                .collect(),
155            string_arrays: BTreeMap::new(),
156        }
157    }
158
159    /// Adds a string array, replacing any scalar at the same key.
160    pub fn with_string_array<I, V>(mut self, key: impl Into<String>, values: I) -> Self
161    where
162        I: IntoIterator<Item = V>,
163        V: Into<String>,
164    {
165        let key = key.into();
166        self.scalars.remove(&key);
167        self.string_arrays
168            .insert(key, values.into_iter().map(Into::into).collect());
169        self
170    }
171}
172
173impl ConfigSource for MapSource {
174    fn name(&self) -> &str {
175        &self.name
176    }
177
178    fn load(&self) -> Result<BTreeMap<String, String>> {
179        Ok(self.scalars.clone())
180    }
181
182    fn load_document(&self) -> Result<ConfigDocument> {
183        Ok(ConfigDocument {
184            scalars: self.scalars.clone(),
185            string_arrays: self.string_arrays.clone(),
186            tables: BTreeSet::new(),
187        })
188    }
189}
190
191/// An environment-variable configuration source.
192#[derive(Clone, Eq, PartialEq)]
193pub struct EnvSource {
194    prefix: String,
195    variables: Vec<(OsString, OsString)>,
196}
197
198impl fmt::Debug for EnvSource {
199    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200        formatter
201            .debug_struct("EnvSource")
202            .field("prefix", &self.prefix)
203            .field("entries", &self.variables.len())
204            .field("values", &"[REDACTED]")
205            .finish()
206    }
207}
208
209impl EnvSource {
210    /// Creates a source that reads the current process environment.
211    pub fn new(prefix: impl Into<String>) -> Self {
212        Self::from_iter(prefix, std::env::vars_os())
213    }
214
215    /// Creates a source from environment variables supplied by the caller.
216    pub fn from_iter<I, K, V>(prefix: impl Into<String>, variables: I) -> Self
217    where
218        I: IntoIterator<Item = (K, V)>,
219        K: Into<OsString>,
220        V: Into<OsString>,
221    {
222        Self {
223            prefix: prefix.into(),
224            variables: variables
225                .into_iter()
226                .map(|(key, value)| (key.into(), value.into()))
227                .collect(),
228        }
229    }
230}
231
232impl ConfigSource for EnvSource {
233    fn name(&self) -> &str {
234        "environment"
235    }
236
237    fn load(&self) -> Result<BTreeMap<String, String>> {
238        let values = self
239            .variables
240            .iter()
241            .filter_map(|(key, value)| {
242                let key = key.to_str()?.strip_prefix(&self.prefix)?;
243                let value = value.to_str()?;
244                Some((normalize_environment_key(key), value.to_owned()))
245            })
246            .collect();
247        Ok(values)
248    }
249}
250
251/// A TOML configuration file source.
252#[derive(Clone, Debug, Eq, PartialEq)]
253pub struct TomlSource {
254    path: PathBuf,
255    name: String,
256    required: bool,
257}
258
259impl TomlSource {
260    /// Creates a TOML source backed by `path`.
261    pub fn file(path: impl Into<PathBuf>) -> Self {
262        let path = path.into();
263        let name = path.to_string_lossy().into_owned();
264        Self {
265            path,
266            name,
267            required: true,
268        }
269    }
270
271    /// Creates a TOML source that is ignored when the file does not exist.
272    pub fn optional(path: impl Into<PathBuf>) -> Self {
273        let path = path.into();
274        let name = path.to_string_lossy().into_owned();
275        Self {
276            path,
277            name,
278            required: false,
279        }
280    }
281}
282
283impl ConfigSource for TomlSource {
284    fn name(&self) -> &str {
285        &self.name
286    }
287
288    fn relative_path_base(&self) -> Option<&Path> {
289        self.path.parent()
290    }
291
292    fn load(&self) -> Result<BTreeMap<String, String>> {
293        Ok(self.parse(TomlArrayMode::Reject)?.scalars)
294    }
295
296    fn load_document(&self) -> Result<ConfigDocument> {
297        self.parse(TomlArrayMode::StringOnly)
298    }
299}
300
301impl TomlSource {
302    fn parse(&self, array_mode: TomlArrayMode) -> Result<ConfigDocument> {
303        let input = match std::fs::read_to_string(&self.path) {
304            Ok(input) => input,
305            Err(source) if !self.required && source.kind() == std::io::ErrorKind::NotFound => {
306                return Ok(ConfigDocument::new());
307            }
308            Err(source) => {
309                return Err(Error::with_source(
310                    Diagnostic::new(
311                        MADS020,
312                        "configuration file could not be read",
313                        format!("could not read configuration file `{}`", self.name),
314                    )
315                    .with_subject(&self.name),
316                    source,
317                ));
318            }
319        };
320        parse_toml_document(&input, &self.name, array_mode)
321    }
322}
323
324#[derive(Clone, Copy)]
325enum TomlArrayMode {
326    Reject,
327    StringOnly,
328}
329
330fn parse_toml_document(
331    input: &str,
332    source_name: &str,
333    array_mode: TomlArrayMode,
334) -> Result<ConfigDocument> {
335    let parsed = input.parse::<toml::Value>().map_err(|_| {
336        Error::new(
337            Diagnostic::new(
338                MADS020,
339                "configuration file could not be parsed",
340                format!("configuration file `{source_name}` is not valid TOML"),
341            )
342            .with_subject(source_name),
343        )
344    })?;
345    let syntax = input.parse::<toml_edit::DocumentMut>().map_err(|_| {
346        Error::new(
347            Diagnostic::new(
348                MADS020,
349                "configuration file could not be parsed",
350                format!("configuration file `{source_name}` is not valid TOML"),
351            )
352            .with_subject(source_name),
353        )
354    })?;
355    if let Some(key) = inline_table_key("", syntax.as_table()) {
356        return Err(unsupported_value(&key, "inline table"));
357    }
358
359    let mut output = ConfigDocument::new();
360    flatten_toml("", parsed, &mut output, array_mode)?;
361    Ok(output)
362}
363
364fn inline_table_key(prefix: &str, table: &toml_edit::Table) -> Option<String> {
365    for (segment, item) in table {
366        let key = if prefix.is_empty() {
367            segment.to_owned()
368        } else {
369            format!("{prefix}.{segment}")
370        };
371        match item {
372            toml_edit::Item::Value(toml_edit::Value::InlineTable(_)) => return Some(key),
373            toml_edit::Item::Table(nested) => {
374                if let Some(key) = inline_table_key(&key, nested) {
375                    return Some(key);
376                }
377            }
378            toml_edit::Item::None
379            | toml_edit::Item::Value(_)
380            | toml_edit::Item::ArrayOfTables(_) => {}
381        }
382    }
383    None
384}
385
386fn flatten_toml(
387    prefix: &str,
388    value: toml::Value,
389    output: &mut ConfigDocument,
390    array_mode: TomlArrayMode,
391) -> Result<()> {
392    match value {
393        toml::Value::Table(table) => {
394            if !prefix.is_empty() {
395                output.insert_table(prefix);
396            }
397            if prefix.is_empty() && table.is_empty() {
398                return Ok(());
399            }
400            for (segment, value) in table {
401                let key = if prefix.is_empty() {
402                    segment
403                } else {
404                    format!("{prefix}.{segment}")
405                };
406                flatten_toml(&key, value, output, array_mode)?;
407            }
408            Ok(())
409        }
410        toml::Value::String(value) => insert_scalar(prefix, value, output),
411        toml::Value::Integer(value) => insert_scalar(prefix, value.to_string(), output),
412        toml::Value::Float(value) => insert_scalar(prefix, value.to_string(), output),
413        toml::Value::Boolean(value) => insert_scalar(prefix, value.to_string(), output),
414        toml::Value::Array(values) => match array_mode {
415            TomlArrayMode::Reject => Err(unsupported_value(prefix, "array")),
416            TomlArrayMode::StringOnly => {
417                let values = values
418                    .into_iter()
419                    .map(|value| match value {
420                        toml::Value::String(value) => Ok(value),
421                        _ => Err(unsupported_value(prefix, "non-string array")),
422                    })
423                    .collect::<Result<Vec<_>>>()?;
424                output.insert_string_array(prefix, values);
425                Ok(())
426            }
427        },
428        toml::Value::Datetime(_) => Err(unsupported_value(prefix, "datetime")),
429    }
430}
431
432fn insert_scalar(key: &str, value: String, output: &mut ConfigDocument) -> Result<()> {
433    if key.is_empty() {
434        return Err(unsupported_value(key, "root scalar"));
435    }
436    output.insert_scalar(key, value);
437    Ok(())
438}
439
440fn unsupported_value(key: &str, kind: &str) -> Error {
441    Error::new(
442        Diagnostic::new(
443            MADS020,
444            "unsupported configuration value",
445            format!("configuration value has unsupported type `{kind}`"),
446        )
447        .with_subject(key),
448    )
449}
450
451/// A dotenv file whose variables are available for configuration interpolation.
452#[derive(Clone, Debug, Eq, PartialEq)]
453pub struct DotenvSource {
454    path: PathBuf,
455    required: bool,
456    name: String,
457}
458
459impl DotenvSource {
460    /// Creates a dotenv source that is ignored when the file does not exist.
461    pub fn optional(path: impl Into<PathBuf>) -> Self {
462        Self::new(path.into(), false)
463    }
464
465    /// Creates a dotenv source that fails when the file does not exist.
466    pub fn required(path: impl Into<PathBuf>) -> Self {
467        Self::new(path.into(), true)
468    }
469
470    fn new(path: PathBuf, required: bool) -> Self {
471        let name = path.to_string_lossy().into_owned();
472        Self {
473            path,
474            required,
475            name,
476        }
477    }
478}
479
480/// A configuration value and the source that supplied it.
481#[derive(Clone, Eq, PartialEq)]
482pub struct ConfigValue {
483    value: String,
484    origin: ConfigOrigin,
485}
486
487#[derive(Clone, Eq, PartialEq)]
488struct ConfigStringArrayValue {
489    value: Vec<String>,
490    origin: ConfigOrigin,
491}
492
493#[derive(Clone, Debug, Eq, PartialEq)]
494struct ConfigOrigin {
495    label: String,
496    relative_path_base: Option<PathBuf>,
497}
498
499impl fmt::Debug for ConfigStringArrayValue {
500    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
501        formatter
502            .debug_struct("ConfigStringArrayValue")
503            .field("elements", &self.value.len())
504            .field("source", &self.origin.label)
505            .finish()
506    }
507}
508
509impl fmt::Debug for ConfigValue {
510    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
511        formatter
512            .debug_struct("ConfigValue")
513            .field("value", &"[REDACTED]")
514            .field("source", &self.origin.label)
515            .finish()
516    }
517}
518
519impl ConfigValue {
520    /// Returns the string value.
521    pub fn value(&self) -> &str {
522        &self.value
523    }
524
525    /// Returns the name of the source that supplied the value.
526    pub fn source(&self) -> &str {
527        &self.origin.label
528    }
529}
530
531/// Configuration values merged in source insertion order.
532#[derive(Clone, Default, Eq, PartialEq)]
533pub struct Config {
534    values: BTreeMap<String, ConfigValue>,
535    string_arrays: BTreeMap<String, ConfigStringArrayValue>,
536    tables: BTreeMap<String, ConfigOrigin>,
537}
538
539impl fmt::Debug for Config {
540    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
541        formatter
542            .debug_struct("Config")
543            .field("entries", &self.len())
544            .field("values", &"[REDACTED]")
545            .finish()
546    }
547}
548
549impl Config {
550    /// Parses a typed view without loading any additional configuration sources.
551    pub fn parse<T: crate::Configuration>(&self) -> crate::ConfigurationResult<T> {
552        T::from_config(self)
553    }
554
555    pub(crate) fn project(&self, prefix: &str) -> Self {
556        if prefix.is_empty() {
557            return self.clone();
558        }
559        let prefix = format!("{prefix}.");
560        Self {
561            values: self
562                .values
563                .iter()
564                .filter_map(|(key, value)| {
565                    key.strip_prefix(&prefix)
566                        .map(|key| (key.to_owned(), value.clone()))
567                })
568                .collect(),
569            string_arrays: self
570                .string_arrays
571                .iter()
572                .filter_map(|(key, value)| {
573                    key.strip_prefix(&prefix)
574                        .map(|key| (key.to_owned(), value.clone()))
575                })
576                .collect(),
577            tables: self
578                .tables
579                .iter()
580                .filter_map(|(key, value)| {
581                    key.strip_prefix(&prefix)
582                        .map(|key| (key.to_owned(), value.clone()))
583                })
584                .collect(),
585        }
586    }
587
588    pub(crate) fn has_descendants(&self, key: &str) -> bool {
589        let prefix = format!("{key}.");
590        self.values
591            .keys()
592            .chain(self.string_arrays.keys())
593            .chain(self.tables.keys())
594            .any(|candidate| candidate.starts_with(&prefix))
595    }
596
597    /// Creates an empty configuration.
598    pub fn empty() -> Self {
599        Self::default()
600    }
601
602    /// Returns a configuration value by key.
603    pub fn get(&self, key: &str) -> Option<&str> {
604        self.values.get(key).map(ConfigValue::value)
605    }
606
607    /// Returns the source name for a configuration key.
608    pub fn source_of(&self, key: &str) -> Option<&str> {
609        self.values.get(key).map(ConfigValue::source)
610    }
611
612    /// Returns whether a source declared a TOML table at `key`.
613    pub fn contains_table(&self, key: &str) -> bool {
614        self.tables.contains_key(key)
615    }
616
617    /// Returns the source name for a declared TOML table.
618    pub fn table_source(&self, key: &str) -> Option<&str> {
619        self.tables.get(key).map(|origin| origin.label.as_str())
620    }
621
622    /// Iterates over keys and their attributed values in lexical key order.
623    pub fn iter(&self) -> impl Iterator<Item = (&str, &ConfigValue)> {
624        self.values.iter().map(|(key, value)| (key.as_str(), value))
625    }
626
627    /// Returns a string-array configuration value by key.
628    pub fn get_string_array(&self, key: &str) -> Option<&[String]> {
629        self.string_arrays
630            .get(key)
631            .map(|value| value.value.as_slice())
632    }
633
634    /// Returns the source name for a string-array configuration key.
635    pub fn source_of_string_array(&self, key: &str) -> Option<&str> {
636        self.string_arrays
637            .get(key)
638            .map(|value| value.origin.label.as_str())
639    }
640
641    /// Resolves a scalar path value relative to the source that supplied it.
642    pub fn resolve_path(&self, key: &str) -> Option<PathBuf> {
643        let value = self.values.get(key)?;
644        let configured = Path::new(&value.value);
645        if configured.is_absolute() {
646            return Some(configured.to_path_buf());
647        }
648
649        let base = match &value.origin.relative_path_base {
650            Some(base) => base.clone(),
651            None => std::env::current_dir().ok()?,
652        };
653        Some(base.join(configured))
654    }
655
656    /// Iterates over string-array keys and values in lexical key order.
657    pub fn iter_string_arrays(&self) -> impl Iterator<Item = (&str, &[String])> {
658        self.string_arrays
659            .iter()
660            .map(|(key, value)| (key.as_str(), value.value.as_slice()))
661    }
662
663    /// Returns the number of configuration values.
664    pub fn len(&self) -> usize {
665        self.values.len() + self.string_arrays.len()
666    }
667
668    /// Returns whether the configuration has no values.
669    pub fn is_empty(&self) -> bool {
670        self.values.is_empty() && self.string_arrays.is_empty()
671    }
672}
673
674/// Builds a configuration by merging ordered sources.
675#[derive(Default)]
676pub struct ConfigBuilder {
677    dotenv_sources: Vec<DotenvSource>,
678    sources: Vec<Box<dyn ConfigSource>>,
679}
680
681impl ConfigBuilder {
682    /// Creates an empty configuration builder.
683    pub fn new() -> Self {
684        Self::default()
685    }
686
687    /// Adds a source whose values override earlier source values.
688    pub fn source<S>(mut self, source: S) -> Self
689    where
690        S: ConfigSource + 'static,
691    {
692        self.sources.push(Box::new(source));
693        self
694    }
695
696    /// Adds a dotenv source used only for exact configuration interpolation.
697    pub fn dotenv(mut self, source: DotenvSource) -> Self {
698        self.dotenv_sources.push(source);
699        self
700    }
701
702    /// Loads and merges all sources in insertion order.
703    #[allow(clippy::result_large_err)]
704    pub fn build(self) -> Result<Config> {
705        self.build_with_environment(std::env::vars_os())
706    }
707
708    fn build_with_environment<I, K, V>(self, environment: I) -> Result<Config>
709    where
710        I: IntoIterator<Item = (K, V)>,
711        K: Into<OsString>,
712        V: Into<OsString>,
713    {
714        let mut variables = BTreeMap::new();
715        for source in self.dotenv_sources {
716            let iterator = match dotenvy::from_path_iter(&source.path) {
717                Ok(iterator) => iterator,
718                Err(error) if !source.required && error.not_found() => continue,
719                Err(error) => return Err(dotenv_open_error(&source, error)),
720            };
721            for entry in iterator {
722                let (key, value) = entry.map_err(|_| dotenv_parse_error(&source))?;
723                variables.insert(key, value);
724            }
725        }
726        for (key, value) in environment {
727            let key = key.into();
728            let value = value.into();
729            if let (Some(key), Some(value)) = (key.to_str(), value.to_str()) {
730                variables.insert(key.to_owned(), value.to_owned());
731            }
732        }
733
734        let mut values = BTreeMap::new();
735        let mut string_arrays = BTreeMap::new();
736        let mut tables = BTreeMap::new();
737        for source in self.sources {
738            let origin = ConfigOrigin {
739                label: source.name().to_owned(),
740                relative_path_base: source.relative_path_base().map(Path::to_path_buf),
741            };
742            let document = source.load_document()?;
743            for (key, value) in document.scalars {
744                string_arrays.remove(&key);
745                values.insert(
746                    key,
747                    ConfigValue {
748                        value,
749                        origin: origin.clone(),
750                    },
751                );
752            }
753            for (key, value) in document.string_arrays {
754                values.remove(&key);
755                string_arrays.insert(
756                    key,
757                    ConfigStringArrayValue {
758                        value,
759                        origin: origin.clone(),
760                    },
761                );
762            }
763            for key in document.tables {
764                tables.insert(key, origin.clone());
765            }
766        }
767        for (key, value) in &mut values {
768            if let Some(variable) = exact_variable_name(&value.value) {
769                let resolved = resolve_variable(key, variable, &variables)?;
770                value.value.clone_from(resolved);
771            }
772        }
773        for (key, value) in &mut string_arrays {
774            for element in &mut value.value {
775                if let Some(variable) = exact_variable_name(element) {
776                    let resolved = resolve_variable(key, variable, &variables)?;
777                    element.clone_from(resolved);
778                }
779            }
780        }
781        Ok(Config {
782            values,
783            string_arrays,
784            tables,
785        })
786    }
787}
788
789fn resolve_variable<'a>(
790    key: &str,
791    variable: &str,
792    variables: &'a BTreeMap<String, String>,
793) -> Result<&'a String> {
794    variables.get(variable).ok_or_else(|| {
795        Error::new(
796            Diagnostic::new(
797                MADS020,
798                "configuration variable is missing",
799                format!("configuration variable `{variable}` is not defined"),
800            )
801            .with_subject(key),
802        )
803    })
804}
805
806fn dotenv_open_error(source: &DotenvSource, error: dotenvy::Error) -> Error {
807    match error {
808        dotenvy::Error::Io(error) => Error::with_source(
809            Diagnostic::new(
810                MADS020,
811                "configuration variable file could not be read",
812                format!(
813                    "could not read configuration variable file `{}`",
814                    source.name
815                ),
816            )
817            .with_subject(&source.name),
818            error,
819        ),
820        _ => dotenv_parse_error(source),
821    }
822}
823
824fn dotenv_parse_error(source: &DotenvSource) -> Error {
825    Error::new(
826        Diagnostic::new(
827            MADS020,
828            "configuration variable file could not be parsed",
829            format!(
830                "configuration variable file `{}` is not valid dotenv syntax",
831                source.name
832            ),
833        )
834        .with_subject(&source.name),
835    )
836}
837
838fn exact_variable_name(value: &str) -> Option<&str> {
839    let variable = value.strip_prefix("${")?.strip_suffix('}')?;
840    (!variable.is_empty()
841        && !variable.contains("${")
842        && !variable.contains('}')
843        && !variable.contains(":-"))
844    .then_some(variable)
845}
846
847fn normalize_environment_key(key: &str) -> String {
848    key.to_ascii_lowercase().replace("__", ".")
849}
850
851#[cfg(test)]
852mod tests {
853    use std::ffi::OsString;
854    use std::fs;
855
856    #[cfg(unix)]
857    use std::os::unix::ffi::OsStringExt;
858
859    use super::{ConfigBuilder, DotenvSource, TomlSource};
860
861    #[test]
862    fn optional_dotenv_resolves_exact_placeholders_without_becoming_config() {
863        let directory = tempfile::tempdir().unwrap();
864        let dotenv = directory.path().join(".env");
865        let toml = directory.path().join("mads.toml");
866        fs::write(&dotenv, "DATABASE_URL=postgres://dotenv-value\n").unwrap();
867        fs::write(&toml, "[database]\nurl = \"${DATABASE_URL}\"\n").unwrap();
868
869        let config = ConfigBuilder::new()
870            .dotenv(DotenvSource::optional(&dotenv))
871            .source(TomlSource::file(&toml))
872            .build_with_environment(std::iter::empty::<(OsString, OsString)>())
873            .unwrap();
874
875        assert_eq!(config.get("database.url"), Some("postgres://dotenv-value"));
876        assert_eq!(config.get("DATABASE_URL"), None);
877        assert_eq!(config.source_of("database.url"), toml.to_str());
878    }
879
880    #[test]
881    fn unicode_process_environment_overrides_dotenv_variables() {
882        let directory = tempfile::tempdir().unwrap();
883        let dotenv = directory.path().join(".env");
884        fs::write(&dotenv, "DATABASE_URL=postgres://dotenv-value\n").unwrap();
885
886        let config = ConfigBuilder::new()
887            .dotenv(DotenvSource::required(dotenv))
888            .source(super::MapSource::new(
889                "test",
890                [("database.url", "${DATABASE_URL}")],
891            ))
892            .build_with_environment([("DATABASE_URL", "postgres://process-value")])
893            .unwrap();
894
895        assert_eq!(config.get("database.url"), Some("postgres://process-value"));
896    }
897
898    #[cfg(unix)]
899    #[test]
900    fn non_unicode_process_environment_is_ignored_for_interpolation() {
901        let directory = tempfile::tempdir().unwrap();
902        let dotenv = directory.path().join(".env");
903        fs::write(&dotenv, "DATABASE_URL=postgres://dotenv-value\n").unwrap();
904        let invalid = OsString::from_vec(vec![0xFF]);
905
906        let config = ConfigBuilder::new()
907            .dotenv(DotenvSource::required(dotenv))
908            .source(super::MapSource::new(
909                "test",
910                [("database.url", "${DATABASE_URL}")],
911            ))
912            .build_with_environment([
913                (invalid.clone(), OsString::from("ignored")),
914                (OsString::from("DATABASE_URL"), invalid),
915            ])
916            .unwrap();
917
918        assert_eq!(config.get("database.url"), Some("postgres://dotenv-value"));
919    }
920}