cfgmatic-source 2.2.0

Configuration sources (file, env, remote) 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
//! Loader service for loading configuration from sources.
//!
//! This module provides the [`Loader`] service which is responsible for
//! loading configuration from various sources and parsing it.
//!
//! # Example
//!
//! ```rust,ignore
//! use cfgmatic_source::application::Loader;
//! use cfgmatic_source::infrastructure::FileSource;
//!
//! let loader = Loader::builder()
//!     .fail_fast(false)
//!     .build();
//!
//! let content = loader.load_from_source(&source)?;
//! let config: MyConfig = loader.parse_content(content)?;
//! ```

use serde::de::DeserializeOwned;

use crate::config::{LoadOptions, MergeStrategy};
use crate::domain::{Format, ParsedContent, RawContent, Result, Source, SourceError};

/// Service for loading configuration from sources.
///
/// The Loader is responsible for:
/// - Loading raw content from sources
/// - Detecting and parsing formats
/// - Converting to typed configuration
#[derive(Debug, Clone)]
pub struct Loader {
    /// Loading options.
    options: LoadOptions,

    /// Default format to use when detection fails.
    default_format: Option<Format>,
}

impl Loader {
    /// Create a new Loader with default options.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for constructing a Loader.
    #[must_use]
    pub fn builder() -> LoaderBuilder {
        LoaderBuilder::new()
    }

    /// Get the load options.
    #[must_use]
    pub fn options(&self) -> &LoadOptions {
        &self.options
    }

    /// Load raw content from a source.
    ///
    /// # Errors
    ///
    /// Returns an error if the source cannot be read.
    pub fn load_raw<S: Source>(&self, source: &S) -> Result<RawContent> {
        source.validate()?;
        source.load_raw()
    }

    /// Load and parse content from a source.
    ///
    /// # Errors
    ///
    /// Returns an error if loading or parsing fails.
    pub fn load<S: Source>(&self, source: &S) -> Result<ParsedContent> {
        let raw = self.load_raw(source)?;
        self.parse_raw(raw, source.detect_format())
    }

    /// Load and parse content from a source into a specific type.
    ///
    /// # Errors
    ///
    /// Returns an error if loading, parsing, or deserialization fails.
    pub fn load_as<S: Source, T: DeserializeOwned>(&self, source: &S) -> Result<T> {
        let raw = self.load_raw(source)?;
        let format = source.detect_format().or(self.default_format);

        match format {
            Some(fmt) => fmt.parse_as(raw.as_str()?.as_ref()),
            None => Err(SourceError::unsupported("cannot detect format")),
        }
    }

    /// Parse raw content using a specific format.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails.
    pub fn parse(&self, raw: &RawContent, format: Format) -> Result<ParsedContent> {
        let content = raw.as_str()?;
        format.parse(content.as_ref())
    }

    /// Parse raw content, detecting the format.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails or format cannot be detected.
    pub fn parse_raw(
        &self,
        raw: RawContent,
        detected_format: Option<Format>,
    ) -> Result<ParsedContent> {
        let format = detected_format.or(self.default_format);

        match format {
            Some(fmt) => self.parse(&raw, fmt),
            None => {
                // Try to detect from content
                let content = raw.as_str()?;
                if let Some(fmt) = Format::from_content(content.as_ref()) {
                    return fmt.parse(content.as_ref());
                }
                Err(SourceError::unsupported("cannot detect format"))
            }
        }
    }

    /// Merge multiple parsed contents.
    ///
    /// Uses the merge strategy from options.
    #[must_use]
    pub fn merge(&self, contents: Vec<ParsedContent>) -> ParsedContent {
        if contents.is_empty() {
            return ParsedContent::Null;
        }

        let strategy = self.options.merge_strategy;

        contents
            .into_iter()
            .reduce(|acc, content| match strategy {
                MergeStrategy::Replace => content,
                MergeStrategy::Deep | MergeStrategy::Shallow | MergeStrategy::Strict => {
                    acc.merge(&content)
                }
            })
            .unwrap_or(ParsedContent::Null)
    }

    /// Convert parsed content to a specific type.
    ///
    /// # Errors
    ///
    /// Returns an error if deserialization fails.
    pub fn to_type<T: DeserializeOwned>(&self, content: ParsedContent) -> Result<T> {
        content.to_type()
    }

    /// Load from multiple sources and merge.
    ///
    /// Sources are loaded in order and merged according to the merge strategy.
    /// Optional sources that fail are skipped if `ignore_optional_missing` is true.
    ///
    /// # Errors
    ///
    /// Returns an error if a required source fails and `fail_fast` is true.
    pub fn load_multiple<S: Source>(&self, sources: &[S]) -> Result<ParsedContent> {
        let mut contents = Vec::new();
        let mut errors: Vec<(String, SourceError)> = Vec::new();

        for source in sources {
            match self.load(source) {
                Ok(content) => contents.push(content),
                Err(e) => {
                    if source.is_optional() && self.options.ignore_optional_missing {
                        continue;
                    }
                    if self.options.fail_fast {
                        return Err(e);
                    }
                    errors.push((source.display_name(), e));
                }
            }
        }

        if !errors.is_empty() && contents.is_empty() {
            let error_messages: Vec<String> = errors
                .into_iter()
                .map(|(name, e)| format!("{}: {}", name, e))
                .collect();
            return Err(SourceError::custom(&error_messages.join(", ")));
        }

        Ok(self.merge(contents))
    }
}

impl Default for Loader {
    fn default() -> Self {
        Self {
            options: LoadOptions::default(),
            default_format: None,
        }
    }
}

/// Builder for [`Loader`].
#[derive(Debug, Clone, Default)]
pub struct LoaderBuilder {
    options: Option<LoadOptions>,
    default_format: Option<Format>,
}

impl LoaderBuilder {
    /// Create a new builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the load options.
    #[must_use]
    pub fn options(mut self, options: LoadOptions) -> Self {
        self.options = Some(options);
        self
    }

    /// Set the merge strategy.
    #[must_use]
    pub fn merge_strategy(mut self, strategy: MergeStrategy) -> Self {
        let mut options = self.options.unwrap_or_default();
        options.merge_strategy = strategy;
        self.options = Some(options);
        self
    }

    /// Set whether to fail fast on errors.
    #[must_use]
    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
        let mut options = self.options.unwrap_or_default();
        options.fail_fast = fail_fast;
        self.options = Some(options);
        self
    }

    /// Set the default format when detection fails.
    #[must_use]
    pub fn default_format(mut self, format: Format) -> Self {
        self.default_format = Some(format);
        self
    }

    /// Build the Loader.
    #[must_use]
    pub fn build(self) -> Loader {
        Loader {
            options: self.options.unwrap_or_default(),
            default_format: self.default_format,
        }
    }
}

#[cfg(feature = "async")]
mod async_impl {
    use super::*;

    impl Loader {
        /// Load and parse content from an async source.
        ///
        /// # Errors
        ///
        /// Returns an error if loading or parsing fails.
        pub async fn load_async<S: crate::domain::AsyncSource>(
            &self,
            source: &S,
        ) -> Result<ParsedContent> {
            source.validate()?;
            source.load_async().await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{SourceKind, SourceMetadata};
    use std::collections::BTreeMap;

    /// Test source implementation.
    struct TestSource {
        content: String,
        format: Format,
        optional: bool,
    }

    impl TestSource {
        fn new(content: &str, format: Format) -> Self {
            Self {
                content: content.to_string(),
                format,
                optional: false,
            }
        }

        fn with_optional(mut self, optional: bool) -> Self {
            self.optional = optional;
            self
        }
    }

    impl Source for TestSource {
        fn kind(&self) -> SourceKind {
            SourceKind::Memory
        }

        fn metadata(&self) -> SourceMetadata {
            SourceMetadata::new("test")
        }

        fn load_raw(&self) -> Result<RawContent> {
            Ok(RawContent::from_string(&self.content))
        }

        fn detect_format(&self) -> Option<Format> {
            Some(self.format)
        }

        fn is_optional(&self) -> bool {
            self.optional
        }
    }

    #[test]
    fn test_loader_new() {
        let loader = Loader::new();
        assert_eq!(loader.options().merge_strategy, MergeStrategy::Deep);
    }

    #[test]
    fn test_loader_builder() {
        let loader = Loader::builder()
            .merge_strategy(MergeStrategy::Replace)
            .fail_fast(false)
            .build();

        assert_eq!(loader.options().merge_strategy, MergeStrategy::Replace);
        assert!(!loader.options().fail_fast);
    }

    #[test]
    fn test_loader_load_raw() {
        let source = TestSource::new(r#"key = "value""#, Format::Toml);
        let loader = Loader::new();

        let raw = loader.load_raw(&source).unwrap();
        assert!(!raw.is_empty());
    }

    #[test]
    fn test_loader_load() {
        let source = TestSource::new(r#"key = "value""#, Format::Toml);
        let loader = Loader::new();

        let content = loader.load(&source).unwrap();
        assert!(content.is_object());
    }

    #[test]
    fn test_loader_parse() {
        let raw = RawContent::from_string(r#"{"key": "value"}"#);
        let loader = Loader::new();

        let content = loader.parse(&raw, Format::Json).unwrap();
        assert!(content.is_object());
    }

    #[test]
    fn test_loader_merge_empty() {
        let loader = Loader::new();
        let result = loader.merge(vec![]);
        assert!(result.is_null());
    }

    #[test]
    fn test_loader_merge_single() {
        let loader = Loader::new();
        let mut obj = BTreeMap::new();
        obj.insert(
            "key".to_string(),
            ParsedContent::String("value".to_string()),
        );
        let content = ParsedContent::Object(obj);

        let result = loader.merge(vec![content.clone()]);
        assert_eq!(result, content);
    }

    #[test]
    fn test_loader_merge_multiple() {
        let loader = Loader::builder()
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let mut obj1 = BTreeMap::new();
        obj1.insert("a".to_string(), ParsedContent::Integer(1));

        let mut obj2 = BTreeMap::new();
        obj2.insert("b".to_string(), ParsedContent::Integer(2));

        let result = loader.merge(vec![
            ParsedContent::Object(obj1),
            ParsedContent::Object(obj2),
        ]);

        assert!(result.get("a").is_some());
        assert!(result.get("b").is_some());
    }

    #[test]
    fn test_loader_to_type() {
        use serde::Deserialize;

        #[derive(Debug, Deserialize, PartialEq)]
        struct Config {
            name: String,
        }

        let loader = Loader::new();

        let mut obj = BTreeMap::new();
        obj.insert(
            "name".to_string(),
            ParsedContent::String("test".to_string()),
        );
        let content = ParsedContent::Object(obj);

        let config: Config = loader.to_type(content).unwrap();
        assert_eq!(config.name, "test");
    }

    #[test]
    fn test_loader_load_multiple() {
        let source1 = TestSource::new(r#"{"a": 1}"#, Format::Json);
        let source2 = TestSource::new(r#"{"b": 2}"#, Format::Json);

        let loader = Loader::builder()
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let result = loader.load_multiple(&[source1, source2]).unwrap();
        assert!(result.get("a").is_some());
        assert!(result.get("b").is_some());
    }

    #[test]
    fn test_loader_load_multiple_with_optional() {
        let source1 = TestSource::new(r#"{"a": 1}"#, Format::Json);
        let source2 = TestSource::new(r#"invalid"#, Format::Toml).with_optional(true);

        let loader = Loader::builder().fail_fast(false).build();

        // Should succeed because optional source failure is ignored
        let result = loader.load_multiple(&[source1, source2]).unwrap();
        assert!(result.get("a").is_some());
    }

    #[test]
    fn test_loader_default_format() {
        let source = TestSource::new(r#"{"key": "value"}"#, Format::Unknown);

        let loader = Loader::builder().default_format(Format::Json).build();

        let content = loader.load(&source).unwrap();
        assert!(content.is_object());
    }
}