cfgmatic-source 5.0.1

Configuration sources (file, env, memory) for cfgmatic framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Environment variable source implementation.
//!
//! [`EnvSource`] loads configuration from environment variables.
//! Supports prefix filtering, key mapping, and nested structures.

use std::collections::HashMap;

use crate::constants::{DEFAULT_ENV_PREFIX, ENV_KEY_SEPARATOR};
use crate::domain::{Format, RawContent, Result, Source, SourceError, SourceKind, SourceMetadata};

/// Configuration for environment source.
#[derive(Debug, Clone)]
pub struct EnvConfig {
    /// Prefix for environment variables (default: "APP").
    pub prefix: String,
    /// Separator for nested keys (default: "_").
    pub separator: char,
    /// Whether to convert keys to lowercase.
    pub lowercase_keys: bool,
    /// Custom key mappings.
    pub key_mappings: HashMap<String, String>,
}

impl Default for EnvConfig {
    fn default() -> Self {
        Self {
            prefix: DEFAULT_ENV_PREFIX.to_string(),
            separator: ENV_KEY_SEPARATOR,
            lowercase_keys: true,
            key_mappings: HashMap::new(),
        }
    }
}

impl EnvConfig {
    /// Create a new env config with defaults.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the prefix for environment variables.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Set the separator for nested keys.
    #[must_use]
    pub const fn separator(mut self, sep: char) -> Self {
        self.separator = sep;
        self
    }

    /// Set whether to convert keys to lowercase.
    #[must_use]
    pub const fn lowercase_keys(mut self, lowercase: bool) -> Self {
        self.lowercase_keys = lowercase;
        self
    }

    /// Add a custom key mapping.
    #[must_use]
    pub fn with_mapping(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
        self.key_mappings.insert(from.into(), to.into());
        self
    }
}

/// Builder for [`EnvSource`].
#[derive(Debug)]
pub struct EnvSourceBuilder {
    config: EnvConfig,
    required: bool,
    overrides: HashMap<String, String>,
}

impl EnvSourceBuilder {
    /// Create a new builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: EnvConfig::default(),
            required: false,
            overrides: HashMap::new(),
        }
    }

    /// Set the env configuration.
    #[must_use]
    pub fn config(mut self, config: EnvConfig) -> Self {
        self.config = config;
        self
    }

    /// Set the prefix for environment variables.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config.prefix = prefix.into();
        self
    }

    /// Set whether the source is required.
    #[must_use]
    pub const fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Add an override value (useful for testing).
    #[must_use]
    pub fn with_override(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.overrides.insert(key.into(), value.into());
        self
    }

    /// Add multiple override values.
    #[must_use]
    pub fn with_overrides(mut self, overrides: HashMap<String, String>) -> Self {
        self.overrides.extend(overrides);
        self
    }

    /// Build the env source.
    #[must_use]
    pub fn build(self) -> EnvSource {
        EnvSource {
            config: self.config,
            required: self.required,
            overrides: self.overrides,
        }
    }
}

impl Default for EnvSourceBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Environment-based configuration source.
///
/// Loads configuration from environment variables.
///
/// # Example
///
/// ```rust,no_run
/// use cfgmatic_source::{EnvSource, Source};
///
/// let source = EnvSource::builder()
///     .prefix("MYAPP")
///     .required(false)
///     .build();
///
/// let raw = source.load_raw()?;
/// # Ok::<(), cfgmatic_source::SourceError>(())
/// ```
#[derive(Debug)]
pub struct EnvSource {
    /// Environment configuration.
    config: EnvConfig,
    /// Whether the source is required.
    required: bool,
    /// Override values (for testing).
    overrides: HashMap<String, String>,
}

impl EnvSource {
    /// Create a new env source with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: EnvConfig::default(),
            required: false,
            overrides: HashMap::new(),
        }
    }

    /// Create a builder for env source.
    #[must_use]
    pub fn builder() -> EnvSourceBuilder {
        EnvSourceBuilder::new()
    }

    /// Create an env source with a specific prefix.
    #[must_use]
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            config: EnvConfig {
                prefix: prefix.into(),
                ..EnvConfig::default()
            },
            required: false,
            overrides: HashMap::new(),
        }
    }

    /// Collect all matching environment variables.
    fn collect_vars(&self) -> HashMap<String, String> {
        let mut result = HashMap::new();
        let prefix_with_sep = format!("{}{}", self.config.prefix, self.config.separator);

        // First, add overrides that match prefix
        for (key, value) in &self.overrides {
            if key.starts_with(&prefix_with_sep) {
                result.insert(key.clone(), value.clone());
            }
        }

        // Then, add actual environment variables
        for (key, value) in std::env::vars() {
            if key.starts_with(&prefix_with_sep) {
                result.insert(key, value);
            }
        }

        result
    }

    /// Convert collected vars to a JSON-like structure.
    fn vars_to_nested_map(&self, vars: HashMap<String, String>) -> serde_json::Value {
        let prefix_with_sep = format!("{}{}", self.config.prefix, self.config.separator);
        let mut result = serde_json::Map::new();

        for (key, value) in vars {
            // Remove prefix
            let key_without_prefix = key.strip_prefix(&prefix_with_sep).unwrap_or(&key);

            // Apply key mapping if exists
            let mapped_key = self
                .config
                .key_mappings
                .get(key_without_prefix)
                .map_or(key_without_prefix, String::as_str);

            // Apply lowercase transformation if configured
            let final_key = if self.config.lowercase_keys {
                mapped_key.to_lowercase()
            } else {
                mapped_key.to_string()
            };

            // Split by separator and create nested structure
            let parts: Vec<&str> = final_key.split(self.config.separator).collect();
            Self::insert_nested(&mut result, &parts, value);
        }

        serde_json::Value::Object(result)
    }

    /// Insert a value into a nested map structure.
    fn insert_nested(
        map: &mut serde_json::Map<String, serde_json::Value>,
        parts: &[&str],
        value: String,
    ) {
        if parts.is_empty() {
            return;
        }

        if parts.len() == 1 {
            // Try to parse as JSON value, otherwise use as string
            let json_value =
                serde_json::from_str(&value).unwrap_or(serde_json::Value::String(value));
            map.insert(parts[0].to_string(), json_value);
            return;
        }

        let first = parts[0];
        let rest = &parts[1..];

        let child = map
            .entry(first.to_string())
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));

        if let serde_json::Value::Object(child_map) = child {
            Self::insert_nested(child_map, rest, value);
        }
    }
}

impl Default for EnvSource {
    fn default() -> Self {
        Self::new()
    }
}

impl Source for EnvSource {
    fn kind(&self) -> SourceKind {
        SourceKind::Env
    }

    fn metadata(&self) -> SourceMetadata {
        SourceMetadata::new(format!("env:{}", self.config.prefix))
            .with_env_var(&self.config.prefix)
            .with_priority(200)
            .with_optional(!self.required)
    }

    fn load_raw(&self) -> Result<RawContent> {
        let vars = self.collect_vars();

        if vars.is_empty() && self.required {
            return Err(SourceError::not_found(
                "No matching environment variables found",
            ));
        }

        let json_value = self.vars_to_nested_map(vars);
        let content = serde_json::to_string(&json_value)
            .map_err(|e| SourceError::serialization(&e.to_string()))?;

        Ok(RawContent::from_string(content))
    }

    fn detect_format(&self) -> Option<Format> {
        // Environment variables are converted to JSON
        Some(Format::Json)
    }

    fn is_required(&self) -> bool {
        self.required
    }
}

#[cfg(test)]
#[allow(
    clippy::items_after_statements,
    clippy::iter_on_single_items,
    clippy::approx_constant
)]
mod tests {
    use super::*;

    #[test]
    fn test_env_config_default() {
        let config = EnvConfig::default();
        assert_eq!(config.prefix, "APP");
        assert_eq!(config.separator, '_');
        assert!(config.lowercase_keys);
    }

    #[test]
    fn test_env_config_builder() {
        let config = EnvConfig::new()
            .prefix("MYAPP")
            .separator(':')
            .lowercase_keys(false);

        assert_eq!(config.prefix, "MYAPP");
        assert_eq!(config.separator, ':');
        assert!(!config.lowercase_keys);
    }

    #[test]
    fn test_env_source_builder() {
        let source = EnvSource::builder().prefix("TEST").required(true).build();

        assert!(source.is_required());
        assert_eq!(source.config.prefix, "TEST");
    }

    #[test]
    fn test_env_source_with_overrides() {
        // Test that overrides are stored correctly
        let source = EnvSource::builder()
            .prefix("TEST")
            .with_override("TEST_NAME", "test-value")
            .with_override("TEST_NESTED_KEY", "nested-value")
            .build();

        // Verify overrides are stored
        assert_eq!(
            source.overrides.get("TEST_NAME"),
            Some(&"test-value".to_string())
        );
        assert_eq!(
            source.overrides.get("TEST_NESTED_KEY"),
            Some(&"nested-value".to_string())
        );
    }

    #[test]
    fn test_vars_to_nested_map() {
        // Test vars_to_nested_map with manual vars
        let source = EnvSource::with_prefix("TEST");
        let vars: HashMap<String, String> = [
            ("TEST_NAME".to_string(), "myapp".to_string()),
            ("TEST_SERVER_HOST".to_string(), "localhost".to_string()),
            ("TEST_SERVER_PORT".to_string(), "8080".to_string()),
        ]
        .into_iter()
        .collect();

        let nested = source.vars_to_nested_map(vars);

        assert_eq!(nested.get("name"), Some(&serde_json::json!("myapp")));
        assert!(nested.get("server").is_some());

        let server = nested.get("server").unwrap().as_object().unwrap();
        assert_eq!(server.get("host"), Some(&serde_json::json!("localhost")));
        assert_eq!(server.get("port"), Some(&serde_json::json!(8080)));
    }

    #[test]
    fn test_load_raw_with_overrides() {
        // Test load_raw creates valid JSON from overrides
        let source = EnvSource {
            config: EnvConfig::new().prefix("TEST"),
            required: false,
            overrides: [
                ("TEST_NAME".to_string(), "test-app".to_string()),
                ("TEST_VALUE".to_string(), "42".to_string()),
            ]
            .into_iter()
            .collect(),
        };

        let raw = source.load_raw().unwrap();
        let content = raw.as_str().unwrap();

        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct TestConfig {
            name: String,
            value: u32,
        }

        let config: TestConfig = serde_json::from_str(content.as_ref()).unwrap();
        assert_eq!(config.name, "test-app");
        assert_eq!(config.value, 42);
    }

    #[test]
    fn test_metadata() {
        let source = EnvSource::with_prefix("MYAPP");
        let meta = source.metadata();

        assert_eq!(meta.name, "env:MYAPP");
        assert_eq!(source.kind(), SourceKind::Env);
        assert_eq!(meta.priority, 200);
    }

    #[test]
    fn test_key_mapping() {
        let config = EnvConfig::new()
            .prefix("TEST")
            .with_mapping("OLD_KEY", "remapped");

        let source = EnvSource {
            config,
            required: false,
            overrides: [("TEST_OLD_KEY".to_string(), "value".to_string())]
                .into_iter()
                .collect(),
        };

        // Test that mapping works - collect vars then transform
        let vars = source.collect_vars();
        assert!(!vars.is_empty());

        let nested = source.vars_to_nested_map(vars);
        // After mapping OLD_KEY -> remapped and lowercase, we get "remapped"
        assert_eq!(nested.get("remapped"), Some(&serde_json::json!("value")));
    }

    #[test]
    fn test_empty_source() {
        let source = EnvSource::builder()
            .prefix("NONEXISTENT_PREFIX_XYZ")
            .required(false)
            .build();

        let raw = source.load_raw().unwrap();
        let content = raw.as_str().unwrap();

        // Should return empty JSON object
        assert_eq!(content.as_ref(), "{}");
    }

    #[test]
    fn test_json_value_parsing() {
        // Test that JSON values are correctly parsed from env vars
        let source = EnvSource {
            config: EnvConfig::new().prefix("TEST"),
            required: false,
            overrides: [
                ("TEST_NUMBERS".to_string(), "[1, 2, 3]".to_string()),
                ("TEST_ENABLED".to_string(), "true".to_string()),
                ("TEST_RATIO".to_string(), "3.14".to_string()),
            ]
            .into_iter()
            .collect(),
        };

        let raw = source.load_raw().unwrap();
        let content = raw.as_str().unwrap();

        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct TestConfig {
            numbers: Vec<i32>,
            enabled: bool,
            ratio: f64,
        }

        let config: TestConfig = serde_json::from_str(content.as_ref()).unwrap();
        assert_eq!(config.numbers, vec![1, 2, 3]);
        assert!(config.enabled);
        assert!((config.ratio - 3.14).abs() < 0.001);
    }
}