adotenv-config 0.12.1

config crate source adapter for adotenv documents.
Documentation
//! `config` crate source adapter for literal adotenv documents and loaded
//! environments.
//!
//! The source exposes only effective literal `String` values. Duplicate policy
//! and lookup participation follow the document or environment being wrapped.
//! With the `load` feature it also accepts a `LoadedEnvironment`.
//!
//! Key names are handed to `config` unchanged. `config` 0.15 keeps key case,
//! treats `.` as a nested path separator and treats `[`/`]` as array-path
//! syntax; for example, `A[0]` and `A[1]` can become an array under `A`. A dotted key and a scalar key
//! with the same parent name collide: with `A=1` and `A.B=2`, `config` exposes
//! either the scalar or the nested table, not both. The winner is an
//! implementation detail of `config`'s source map, so normalize or rename
//! keys before building a source when both shapes are needed.

use std::collections::BTreeMap;

#[cfg(feature = "load")]
use adotenv::load::LoadedEnvironment;
use adotenv::{CompactEntries, CompactValues, Document};
use config::{Map, Source, Value};

/// A `config` source containing the adapter's effective string values.
#[derive(Debug, Clone, Default)]
pub struct AdotenvSource {
    values: BTreeMap<String, String>,
}

impl AdotenvSource {
    /// Build a source from an explicit key/value map.
    ///
    /// Keys are passed through unchanged. A key containing `.` becomes a
    /// nested path and a key containing `[`/`]` can become an array path under
    /// `config`; if another key names the same parent, the shapes collide and
    /// `config` exposes only one of them. Normalize or rename such keys before
    /// constructing the source.
    #[must_use]
    pub fn from_values(values: BTreeMap<String, String>) -> Self {
        Self { values }
    }

    /// Build a source from final values in a loaded environment.
    ///
    /// Available only with the `load` feature.
    #[cfg(feature = "load")]
    #[must_use]
    pub fn from_environment(environment: &LoadedEnvironment) -> Self {
        Self {
            values: environment
                .values()
                .map(|(key, value)| (key.to_string(), value.to_string()))
                .collect(),
        }
    }

    /// Build a source from a document's effective literal declarations.
    ///
    /// Duplicate keys follow the document's dialect. Nonparticipating and empty
    /// keys are omitted; bare declarations contribute `""` only under
    /// `BareKeys::Empty`.
    #[must_use]
    pub fn from_document(document: &Document<'_>) -> Self {
        let values = document
            .effective_entries()
            .map(|entry| (entry.key().to_string(), entry.value().to_string()))
            .collect();
        Self { values }
    }

    /// Build a source from compact effective literal values.
    ///
    /// Accepts the output of `parse_values_compact*`, `load_values_compact*`,
    /// or `load_cascade_values_compact*`.
    #[must_use]
    pub fn from_compact_values(values: &CompactValues) -> Self {
        Self {
            values: values
                .iter()
                .map(|(key, value)| (key.to_string(), value.to_string()))
                .collect(),
        }
    }

    /// Build a source from compact winning entries.
    ///
    /// Bare declarations retained as `None` under `BareKeys::Preserve` are
    /// omitted; bare declarations converted to `""` under `BareKeys::Empty`
    /// are included.
    #[must_use]
    pub fn from_compact_entries(entries: &CompactEntries) -> Self {
        Self {
            values: entries
                .iter()
                .filter_map(|(key, value)| value.map(|val| (key.to_string(), val.to_string())))
                .collect(),
        }
    }

    /// The effective values exposed by this source.
    #[must_use]
    pub fn values(&self) -> &BTreeMap<String, String> {
        &self.values
    }
}

impl Source for AdotenvSource {
    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
        Box::new(self.clone())
    }

    fn collect(&self) -> Result<Map<String, Value>, config::ConfigError> {
        let mut map = Map::new();
        for (key, value) in &self.values {
            map.insert(key.clone(), Value::new(None, value.as_str()));
        }
        Ok(map)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use adotenv::{parse_with, BareKeys, Dialect, Duplicates};
    use config::Config;

    #[test]
    fn config_source_exposes_flat_strings() {
        let config = Config::builder()
            .add_source(AdotenvSource::from_values(BTreeMap::from([
                ("host".to_string(), "localhost".to_string()),
                ("port".to_string(), "8080".to_string()),
            ])))
            .build()
            .unwrap();
        assert_eq!(config.get_string("host").unwrap(), "localhost");
        assert_eq!(config.get_int("port").unwrap(), 8080);
    }

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct TypedConfig {
        host: String,
        port: u16,
    }

    #[test]
    fn typed_deserialization_uses_config_scalar_coercion() {
        let config = Config::builder()
            .add_source(AdotenvSource::from_values(BTreeMap::from([
                ("host".to_string(), "localhost".to_string()),
                ("port".to_string(), "8080".to_string()),
            ])))
            .build()
            .unwrap();
        let typed: TypedConfig = config.try_deserialize().unwrap();
        assert_eq!(
            typed,
            TypedConfig {
                host: "localhost".to_string(),
                port: 8080,
            }
        );
    }

    #[test]
    fn config_uses_native_path_and_case_semantics() {
        let config = Config::builder()
            .add_source(AdotenvSource::from_values(BTreeMap::from([
                ("A.B".to_string(), "dotted".to_string()),
                ("UPPER".to_string(), "upper".to_string()),
            ])))
            .build()
            .unwrap();
        assert_eq!(config.get_string("A.B").unwrap(), "dotted");
        assert!(config.get_string("a.b").is_err());
        let table = config.get_table("A").unwrap();
        assert_eq!(table.keys().collect::<Vec<_>>(), ["B"]);
        assert_eq!(config.get_string("UPPER").unwrap(), "upper");
        assert!(config.get_string("upper").is_err());
    }

    #[test]
    fn scalar_parent_and_dotted_child_cannot_both_be_read() {
        let config = Config::builder()
            .add_source(AdotenvSource::from_values(BTreeMap::from([
                ("A".to_string(), "scalar".to_string()),
                ("A.B".to_string(), "dotted".to_string()),
            ])))
            .build()
            .unwrap();
        // config's source map does not define which shape wins when a scalar
        // parent and a dotted child collide. It must not expose both.
        assert!(config.get_string("A").is_err() || config.get_string("A.B").is_err());
    }

    #[test]
    fn document_source_drives_typed_config_and_brackets_are_array_paths() {
        let (document, _) = parse_with("host=localhost\nport=8080\n", Dialect::PORTABLE);
        let config = Config::builder()
            .add_source(AdotenvSource::from_document(&document))
            .build()
            .unwrap();
        #[derive(serde::Deserialize)]
        struct App {
            host: String,
            port: u16,
        }
        let app: App = config.try_deserialize().unwrap();
        assert_eq!((app.host.as_str(), app.port), ("localhost", 8080));

        let config = Config::builder()
            .add_source(AdotenvSource::from_values(BTreeMap::from([
                ("A[0]".to_string(), "one".to_string()),
                ("A[1]".to_string(), "two".to_string()),
            ])))
            .build()
            .unwrap();
        assert_eq!(config.get_array("A").unwrap().len(), 2);
    }

    #[test]
    fn document_source_honors_duplicate_and_quote_rules() {
        let (document, _) = parse_with(
            "A='first'\nA=second\nB=\"two words\"\nC='$HOME'\nD=\"line\\nbreak\"\n",
            Dialect::PORTABLE,
        );
        let source = AdotenvSource::from_document(&document);
        assert_eq!(source.values().get("A").map(String::as_str), Some("second"));
        assert_eq!(
            source.values().get("B").map(String::as_str),
            Some("two words")
        );
        assert_eq!(source.values().get("C").map(String::as_str), Some("$HOME"));
        assert_eq!(
            source.values().get("D").map(String::as_str),
            Some("line\nbreak")
        );

        let first = Dialect::PORTABLE.with_duplicates(Duplicates::First);
        let (document, _) = parse_with("A='first'\nA=second\n", first);
        let source = AdotenvSource::from_document(&document);
        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
    }

    #[test]
    fn document_source_honors_bare_and_nonparticipating_rules() {
        let empty = Dialect::PORTABLE.with_bare_keys(BareKeys::Empty);
        let (document, _) = parse_with("A=first\nA\nB\n", empty);
        let source = AdotenvSource::from_document(&document);
        assert_eq!(source.values().get("A").map(String::as_str), Some(""));
        assert_eq!(source.values().get("B").map(String::as_str), Some(""));

        let ignore = Dialect::PORTABLE.with_bare_keys(BareKeys::Ignore);
        let (document, _) = parse_with("A=first\nA\nB\n", ignore);
        let source = AdotenvSource::from_document(&document);
        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
        assert!(!source.values().contains_key("B"));
    }

    #[cfg(feature = "load")]
    #[test]
    fn environment_source_drives_a_typed_cascade_config() {
        let dir =
            std::env::temp_dir().join(format!("adotenv-config-cascade-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(".env"), "host=localhost\nport=8080\n").unwrap();
        std::fs::write(dir.join(".env.local"), "port=9090\n").unwrap();
        let environment = adotenv::load::load_cascade(&dir, "").unwrap();
        let config = Config::builder()
            .add_source(AdotenvSource::from_environment(&environment))
            .build()
            .unwrap();
        let typed: TypedConfig = config.try_deserialize().unwrap();
        assert_eq!(
            typed,
            TypedConfig {
                host: "localhost".to_string(),
                port: 9090,
            }
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[cfg(feature = "load")]
    #[test]
    fn environment_source_copies_final_values() {
        let path = std::env::temp_dir().join(format!(
            "adotenv-config-environment-{}.env",
            std::process::id()
        ));
        std::fs::write(&path, "A=from-file\nA=final\nB=two\n").unwrap();
        let environment = adotenv::load::load_files([&path], Dialect::PORTABLE).unwrap();
        let source = AdotenvSource::from_environment(&environment);
        assert_eq!(source.values().get("A").map(String::as_str), Some("final"));
        assert_eq!(source.values().get("B").map(String::as_str), Some("two"));
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn compact_values_and_entries_sources_match_document_rules() {
        let compact = adotenv::parse_values_compact("host=localhost\nport=8080\nBARE\n").unwrap();
        let source = AdotenvSource::from_compact_values(&compact);
        assert_eq!(source.values().len(), 2);
        assert!(!source.values().contains_key("BARE"));
        let config = Config::builder().add_source(source).build().unwrap();
        let typed: TypedConfig = config.try_deserialize().unwrap();
        assert_eq!(
            typed,
            TypedConfig {
                host: "localhost".to_string(),
                port: 8080,
            }
        );

        let entries = adotenv::parse_entries_compact("A=1\nBARE\nEMPTY=\n").unwrap();
        let source = AdotenvSource::from_compact_entries(&entries);
        assert_eq!(source.values().get("A").map(String::as_str), Some("1"));
        assert_eq!(source.values().get("EMPTY").map(String::as_str), Some(""));
        assert!(!source.values().contains_key("BARE"));

        let empty_dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Empty);
        let entries =
            adotenv::parse_entries_compact_with("A=first\nA\nB\n", empty_dialect).unwrap();
        let source = AdotenvSource::from_compact_entries(&entries);
        assert_eq!(source.values().get("A").map(String::as_str), Some(""));
        assert_eq!(source.values().get("B").map(String::as_str), Some(""));

        let ignore_dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Ignore);
        let entries =
            adotenv::parse_entries_compact_with("A=first\nA\nB\n", ignore_dialect).unwrap();
        let source = AdotenvSource::from_compact_entries(&entries);
        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
        assert!(!source.values().contains_key("B"));

        let first_dialect = Dialect::PORTABLE.with_duplicates(Duplicates::First);
        let compact = adotenv::parse_values_compact_with("A=1\nA=2\n", first_dialect).unwrap();
        assert_eq!(
            AdotenvSource::from_compact_values(&compact)
                .values()
                .get("A")
                .map(String::as_str),
            Some("1")
        );

        assert_eq!(
            AdotenvSource::from_compact_values(&CompactValues::default())
                .values()
                .len(),
            0
        );
        assert_eq!(
            AdotenvSource::from_compact_entries(&CompactEntries::default())
                .values()
                .len(),
            0
        );
    }

    #[cfg(feature = "load")]
    #[test]
    fn compact_cascade_drives_typed_config() {
        let dir = std::env::temp_dir().join(format!(
            "adotenv-config-compact-cascade-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(".env"), "host=localhost\nport=8080\n").unwrap();
        std::fs::write(dir.join(".env.local"), "port=9090\n").unwrap();
        let compact = adotenv::load::load_cascade_values_compact(&dir, "").unwrap();
        let config = Config::builder()
            .add_source(AdotenvSource::from_compact_values(&compact))
            .build()
            .unwrap();
        let typed: TypedConfig = config.try_deserialize().unwrap();
        assert_eq!(
            typed,
            TypedConfig {
                host: "localhost".to_string(),
                port: 9090,
            }
        );
        std::fs::remove_dir_all(dir).unwrap();
    }
}