Skip to main content

adotenv_config/
lib.rs

1//! `config` crate source adapter for literal adotenv documents and loaded
2//! environments.
3//!
4//! The source exposes only effective literal `String` values. Duplicate policy
5//! and lookup participation follow the document or environment being wrapped.
6//! With the `load` feature it also accepts a `LoadedEnvironment`.
7//!
8//! Key names are handed to `config` unchanged. `config` 0.15 keeps key case,
9//! treats `.` as a nested path separator and treats `[`/`]` as array-path
10//! syntax; for example, `A[0]` and `A[1]` can become an array under `A`. A dotted key and a scalar key
11//! with the same parent name collide: with `A=1` and `A.B=2`, `config` exposes
12//! either the scalar or the nested table, not both. The winner is an
13//! implementation detail of `config`'s source map, so normalize or rename
14//! keys before building a source when both shapes are needed.
15
16use std::collections::BTreeMap;
17
18#[cfg(feature = "load")]
19use adotenv::load::LoadedEnvironment;
20use adotenv::{CompactEntries, CompactValues, Document};
21use config::{Map, Source, Value};
22
23/// A `config` source containing the adapter's effective string values.
24#[derive(Debug, Clone, Default)]
25pub struct AdotenvSource {
26    values: BTreeMap<String, String>,
27}
28
29impl AdotenvSource {
30    /// Build a source from an explicit key/value map.
31    ///
32    /// Keys are passed through unchanged. A key containing `.` becomes a
33    /// nested path and a key containing `[`/`]` can become an array path under
34    /// `config`; if another key names the same parent, the shapes collide and
35    /// `config` exposes only one of them. Normalize or rename such keys before
36    /// constructing the source.
37    #[must_use]
38    pub fn from_values(values: BTreeMap<String, String>) -> Self {
39        Self { values }
40    }
41
42    /// Build a source from final values in a loaded environment.
43    ///
44    /// Available only with the `load` feature.
45    #[cfg(feature = "load")]
46    #[must_use]
47    pub fn from_environment(environment: &LoadedEnvironment) -> Self {
48        Self {
49            values: environment
50                .values()
51                .map(|(key, value)| (key.to_string(), value.to_string()))
52                .collect(),
53        }
54    }
55
56    /// Build a source from a document's effective literal declarations.
57    ///
58    /// Duplicate keys follow the document's dialect. Nonparticipating and empty
59    /// keys are omitted; bare declarations contribute `""` only under
60    /// `BareKeys::Empty`.
61    #[must_use]
62    pub fn from_document(document: &Document<'_>) -> Self {
63        let values = document
64            .effective_entries()
65            .map(|entry| (entry.key().to_string(), entry.value().to_string()))
66            .collect();
67        Self { values }
68    }
69
70    /// Build a source from compact effective literal values.
71    ///
72    /// Accepts the output of `parse_values_compact*`, `load_values_compact*`,
73    /// or `load_cascade_values_compact*`.
74    #[must_use]
75    pub fn from_compact_values(values: &CompactValues) -> Self {
76        Self {
77            values: values
78                .iter()
79                .map(|(key, value)| (key.to_string(), value.to_string()))
80                .collect(),
81        }
82    }
83
84    /// Build a source from compact winning entries.
85    ///
86    /// Bare declarations retained as `None` under `BareKeys::Preserve` are
87    /// omitted; bare declarations converted to `""` under `BareKeys::Empty`
88    /// are included.
89    #[must_use]
90    pub fn from_compact_entries(entries: &CompactEntries) -> Self {
91        Self {
92            values: entries
93                .iter()
94                .filter_map(|(key, value)| value.map(|val| (key.to_string(), val.to_string())))
95                .collect(),
96        }
97    }
98
99    /// The effective values exposed by this source.
100    #[must_use]
101    pub fn values(&self) -> &BTreeMap<String, String> {
102        &self.values
103    }
104}
105
106impl Source for AdotenvSource {
107    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
108        Box::new(self.clone())
109    }
110
111    fn collect(&self) -> Result<Map<String, Value>, config::ConfigError> {
112        let mut map = Map::new();
113        for (key, value) in &self.values {
114            map.insert(key.clone(), Value::new(None, value.as_str()));
115        }
116        Ok(map)
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use adotenv::{parse_with, BareKeys, Dialect, Duplicates};
124    use config::Config;
125
126    #[test]
127    fn config_source_exposes_flat_strings() {
128        let config = Config::builder()
129            .add_source(AdotenvSource::from_values(BTreeMap::from([
130                ("host".to_string(), "localhost".to_string()),
131                ("port".to_string(), "8080".to_string()),
132            ])))
133            .build()
134            .unwrap();
135        assert_eq!(config.get_string("host").unwrap(), "localhost");
136        assert_eq!(config.get_int("port").unwrap(), 8080);
137    }
138
139    #[derive(Debug, serde::Deserialize, PartialEq)]
140    struct TypedConfig {
141        host: String,
142        port: u16,
143    }
144
145    #[test]
146    fn typed_deserialization_uses_config_scalar_coercion() {
147        let config = Config::builder()
148            .add_source(AdotenvSource::from_values(BTreeMap::from([
149                ("host".to_string(), "localhost".to_string()),
150                ("port".to_string(), "8080".to_string()),
151            ])))
152            .build()
153            .unwrap();
154        let typed: TypedConfig = config.try_deserialize().unwrap();
155        assert_eq!(
156            typed,
157            TypedConfig {
158                host: "localhost".to_string(),
159                port: 8080,
160            }
161        );
162    }
163
164    #[test]
165    fn config_uses_native_path_and_case_semantics() {
166        let config = Config::builder()
167            .add_source(AdotenvSource::from_values(BTreeMap::from([
168                ("A.B".to_string(), "dotted".to_string()),
169                ("UPPER".to_string(), "upper".to_string()),
170            ])))
171            .build()
172            .unwrap();
173        assert_eq!(config.get_string("A.B").unwrap(), "dotted");
174        assert!(config.get_string("a.b").is_err());
175        let table = config.get_table("A").unwrap();
176        assert_eq!(table.keys().collect::<Vec<_>>(), ["B"]);
177        assert_eq!(config.get_string("UPPER").unwrap(), "upper");
178        assert!(config.get_string("upper").is_err());
179    }
180
181    #[test]
182    fn scalar_parent_and_dotted_child_cannot_both_be_read() {
183        let config = Config::builder()
184            .add_source(AdotenvSource::from_values(BTreeMap::from([
185                ("A".to_string(), "scalar".to_string()),
186                ("A.B".to_string(), "dotted".to_string()),
187            ])))
188            .build()
189            .unwrap();
190        // config's source map does not define which shape wins when a scalar
191        // parent and a dotted child collide. It must not expose both.
192        assert!(config.get_string("A").is_err() || config.get_string("A.B").is_err());
193    }
194
195    #[test]
196    fn document_source_drives_typed_config_and_brackets_are_array_paths() {
197        let (document, _) = parse_with("host=localhost\nport=8080\n", Dialect::PORTABLE);
198        let config = Config::builder()
199            .add_source(AdotenvSource::from_document(&document))
200            .build()
201            .unwrap();
202        #[derive(serde::Deserialize)]
203        struct App {
204            host: String,
205            port: u16,
206        }
207        let app: App = config.try_deserialize().unwrap();
208        assert_eq!((app.host.as_str(), app.port), ("localhost", 8080));
209
210        let config = Config::builder()
211            .add_source(AdotenvSource::from_values(BTreeMap::from([
212                ("A[0]".to_string(), "one".to_string()),
213                ("A[1]".to_string(), "two".to_string()),
214            ])))
215            .build()
216            .unwrap();
217        assert_eq!(config.get_array("A").unwrap().len(), 2);
218    }
219
220    #[test]
221    fn document_source_honors_duplicate_and_quote_rules() {
222        let (document, _) = parse_with(
223            "A='first'\nA=second\nB=\"two words\"\nC='$HOME'\nD=\"line\\nbreak\"\n",
224            Dialect::PORTABLE,
225        );
226        let source = AdotenvSource::from_document(&document);
227        assert_eq!(source.values().get("A").map(String::as_str), Some("second"));
228        assert_eq!(
229            source.values().get("B").map(String::as_str),
230            Some("two words")
231        );
232        assert_eq!(source.values().get("C").map(String::as_str), Some("$HOME"));
233        assert_eq!(
234            source.values().get("D").map(String::as_str),
235            Some("line\nbreak")
236        );
237
238        let first = Dialect::PORTABLE.with_duplicates(Duplicates::First);
239        let (document, _) = parse_with("A='first'\nA=second\n", first);
240        let source = AdotenvSource::from_document(&document);
241        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
242    }
243
244    #[test]
245    fn document_source_honors_bare_and_nonparticipating_rules() {
246        let empty = Dialect::PORTABLE.with_bare_keys(BareKeys::Empty);
247        let (document, _) = parse_with("A=first\nA\nB\n", empty);
248        let source = AdotenvSource::from_document(&document);
249        assert_eq!(source.values().get("A").map(String::as_str), Some(""));
250        assert_eq!(source.values().get("B").map(String::as_str), Some(""));
251
252        let ignore = Dialect::PORTABLE.with_bare_keys(BareKeys::Ignore);
253        let (document, _) = parse_with("A=first\nA\nB\n", ignore);
254        let source = AdotenvSource::from_document(&document);
255        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
256        assert!(!source.values().contains_key("B"));
257    }
258
259    #[cfg(feature = "load")]
260    #[test]
261    fn environment_source_drives_a_typed_cascade_config() {
262        let dir =
263            std::env::temp_dir().join(format!("adotenv-config-cascade-{}", std::process::id()));
264        std::fs::create_dir_all(&dir).unwrap();
265        std::fs::write(dir.join(".env"), "host=localhost\nport=8080\n").unwrap();
266        std::fs::write(dir.join(".env.local"), "port=9090\n").unwrap();
267        let environment = adotenv::load::load_cascade(&dir, "").unwrap();
268        let config = Config::builder()
269            .add_source(AdotenvSource::from_environment(&environment))
270            .build()
271            .unwrap();
272        let typed: TypedConfig = config.try_deserialize().unwrap();
273        assert_eq!(
274            typed,
275            TypedConfig {
276                host: "localhost".to_string(),
277                port: 9090,
278            }
279        );
280        std::fs::remove_dir_all(dir).unwrap();
281    }
282
283    #[cfg(feature = "load")]
284    #[test]
285    fn environment_source_copies_final_values() {
286        let path = std::env::temp_dir().join(format!(
287            "adotenv-config-environment-{}.env",
288            std::process::id()
289        ));
290        std::fs::write(&path, "A=from-file\nA=final\nB=two\n").unwrap();
291        let environment = adotenv::load::load_files([&path], Dialect::PORTABLE).unwrap();
292        let source = AdotenvSource::from_environment(&environment);
293        assert_eq!(source.values().get("A").map(String::as_str), Some("final"));
294        assert_eq!(source.values().get("B").map(String::as_str), Some("two"));
295        let _ = std::fs::remove_file(path);
296    }
297
298    #[test]
299    fn compact_values_and_entries_sources_match_document_rules() {
300        let compact = adotenv::parse_values_compact("host=localhost\nport=8080\nBARE\n").unwrap();
301        let source = AdotenvSource::from_compact_values(&compact);
302        assert_eq!(source.values().len(), 2);
303        assert!(!source.values().contains_key("BARE"));
304        let config = Config::builder().add_source(source).build().unwrap();
305        let typed: TypedConfig = config.try_deserialize().unwrap();
306        assert_eq!(
307            typed,
308            TypedConfig {
309                host: "localhost".to_string(),
310                port: 8080,
311            }
312        );
313
314        let entries = adotenv::parse_entries_compact("A=1\nBARE\nEMPTY=\n").unwrap();
315        let source = AdotenvSource::from_compact_entries(&entries);
316        assert_eq!(source.values().get("A").map(String::as_str), Some("1"));
317        assert_eq!(source.values().get("EMPTY").map(String::as_str), Some(""));
318        assert!(!source.values().contains_key("BARE"));
319
320        let empty_dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Empty);
321        let entries =
322            adotenv::parse_entries_compact_with("A=first\nA\nB\n", empty_dialect).unwrap();
323        let source = AdotenvSource::from_compact_entries(&entries);
324        assert_eq!(source.values().get("A").map(String::as_str), Some(""));
325        assert_eq!(source.values().get("B").map(String::as_str), Some(""));
326
327        let ignore_dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Ignore);
328        let entries =
329            adotenv::parse_entries_compact_with("A=first\nA\nB\n", ignore_dialect).unwrap();
330        let source = AdotenvSource::from_compact_entries(&entries);
331        assert_eq!(source.values().get("A").map(String::as_str), Some("first"));
332        assert!(!source.values().contains_key("B"));
333
334        let first_dialect = Dialect::PORTABLE.with_duplicates(Duplicates::First);
335        let compact = adotenv::parse_values_compact_with("A=1\nA=2\n", first_dialect).unwrap();
336        assert_eq!(
337            AdotenvSource::from_compact_values(&compact)
338                .values()
339                .get("A")
340                .map(String::as_str),
341            Some("1")
342        );
343
344        assert_eq!(
345            AdotenvSource::from_compact_values(&CompactValues::default())
346                .values()
347                .len(),
348            0
349        );
350        assert_eq!(
351            AdotenvSource::from_compact_entries(&CompactEntries::default())
352                .values()
353                .len(),
354            0
355        );
356    }
357
358    #[cfg(feature = "load")]
359    #[test]
360    fn compact_cascade_drives_typed_config() {
361        let dir = std::env::temp_dir().join(format!(
362            "adotenv-config-compact-cascade-{}",
363            std::process::id()
364        ));
365        std::fs::create_dir_all(&dir).unwrap();
366        std::fs::write(dir.join(".env"), "host=localhost\nport=8080\n").unwrap();
367        std::fs::write(dir.join(".env.local"), "port=9090\n").unwrap();
368        let compact = adotenv::load::load_cascade_values_compact(&dir, "").unwrap();
369        let config = Config::builder()
370            .add_source(AdotenvSource::from_compact_values(&compact))
371            .build()
372            .unwrap();
373        let typed: TypedConfig = config.try_deserialize().unwrap();
374        assert_eq!(
375            typed,
376            TypedConfig {
377                host: "localhost".to_string(),
378                port: 9090,
379            }
380        );
381        std::fs::remove_dir_all(dir).unwrap();
382    }
383}