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
478
479
480
481
482
483
484
485
486
487
488
489
//! File source implementation.
//!
//! [`FileSource`] loads configuration from files in various formats
//! (TOML, JSON, YAML). It supports single files and directories.

use std::path::{Path, PathBuf};

use cfgmatic_merge::Merge;

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

/// Builder for [`FileSource`].
#[derive(Debug)]
pub struct FileSourceBuilder {
    paths: Vec<PathBuf>,
    required: bool,
}

impl FileSourceBuilder {
    /// Create a new builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            paths: Vec::new(),
            required: true,
        }
    }

    /// Add a file path.
    #[must_use]
    pub fn path(mut self, path: impl Into<PathBuf>) -> Self {
        self.paths.push(path.into());
        self
    }

    /// Add multiple file paths.
    #[must_use]
    pub fn paths(mut self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
        self.paths.extend(paths.into_iter().map(|p| p.into()));
        self
    }

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

    /// Build the file source.
    ///
    /// # Errors
    ///
    /// Returns an error if no paths are configured.
    pub fn build(self) -> Result<FileSource> {
        if self.paths.is_empty() {
            return Err(SourceError::validation("No file paths configured"));
        }
        Ok(FileSource {
            paths: self.paths,
            required: self.required,
        })
    }
}

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

/// File-based configuration source.
///
/// Loads configuration from files in various formats.
///
/// # Example
///
/// ```rust,ignore
/// use cfgmatic_source::FileSource;
///
/// let source = FileSource::builder()
///     .path("config.toml")
///     .path("config.local.toml")
///     .required(false)
///     .build()?;
///
/// let raw = source.load_raw()?;
/// ```
#[derive(Debug)]
pub struct FileSource {
    /// File paths to load.
    pub(crate) paths: Vec<PathBuf>,
    /// Whether the source is required.
    required: bool,
}

impl FileSource {
    /// Create a new file source.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            paths: vec![path.into()],
            required: true,
        }
    }

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

    /// Detect format from file extension.
    fn detect_format_from_path(path: &Path) -> Option<Format> {
        Format::from_path(path)
    }

    /// Read file contents.
    fn read_file(path: &Path) -> Result<String> {
        std::fs::read_to_string(path)
            .map_err(|e| SourceError::read_failed(&format!("{}: {}", path.display(), e)))
    }

    /// Parse content based on format and convert to JSON value.
    fn parse_to_json_value(
        content: &str,
        format: Format,
        path: &Path,
    ) -> Result<serde_json::Value> {
        match format {
            #[cfg(feature = "toml")]
            Format::Toml => {
                let v: toml::Value = toml::from_str(content).map_err(|e| {
                    SourceError::parse_failed(&path.display().to_string(), "toml", &e.to_string())
                })?;
                serde_json::to_value(v).map_err(|e| SourceError::serialization(&e.to_string()))
            }

            #[cfg(feature = "json")]
            Format::Json => serde_json::from_str(content).map_err(|e| {
                SourceError::parse_failed(&path.display().to_string(), "json", &e.to_string())
            }),

            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::from_str(content).map_err(|e| {
                SourceError::parse_failed(&path.display().to_string(), "yaml", &e.to_string())
            }),

            Format::Unknown => Err(SourceError::unsupported("unknown format")),
        }
    }
}

impl Source for FileSource {
    fn kind(&self) -> SourceKind {
        SourceKind::File
    }

    fn metadata(&self) -> SourceMetadata {
        let path = self.paths.first().cloned().unwrap_or_default();
        SourceMetadata::new("file")
            .with_path(path)
            .with_priority(100)
            .with_optional(!self.required)
    }

    fn load_raw(&self) -> Result<RawContent> {
        // For single file, just load it
        if self.paths.len() == 1 {
            let path = &self.paths[0];
            if !path.exists() {
                if self.required {
                    return Err(SourceError::not_found(&path.display().to_string()));
                }
                return Ok(RawContent::from_string(""));
            }

            let content = Self::read_file(path)?;
            return Ok(RawContent::from_string(content).with_source_path(path.clone()));
        }

        // For multiple files, merge them
        let mut merged = serde_json::Value::Object(serde_json::Map::new());
        let mut any_loaded = false;

        for path in &self.paths {
            if !path.exists() {
                if self.required {
                    return Err(SourceError::not_found(&path.display().to_string()));
                }
                continue;
            }

            let content = Self::read_file(path)?;
            let format = Self::detect_format_from_path(path).ok_or_else(|| {
                SourceError::invalid_format(
                    "config",
                    &path.extension().unwrap_or_default().to_string_lossy(),
                )
            })?;

            let value = Self::parse_to_json_value(&content, format, path)?;

            merged = merged
                .merge_deep(value)
                .map_err(|e| SourceError::serialization(&e.to_string()))?;
            any_loaded = true;
        }

        if !any_loaded && self.required {
            return Err(SourceError::not_found("No configuration files found"));
        }

        let content = serde_json::to_string(&merged)
            .map_err(|e| SourceError::serialization(&e.to_string()))?;

        Ok(RawContent::from_string(content))
    }

    fn detect_format(&self) -> Option<Format> {
        self.paths.first().and_then(|p| Format::from_path(p))
    }

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

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

    #[async_trait]
    impl Source for FileSource {
        async fn load_raw_async(&self) -> Result<RawContent> {
            // For async, we use tokio::fs
            if self.paths.len() == 1 {
                let path = &self.paths[0];
                let path_exists = tokio::fs::try_exists(path)
                    .await
                    .map_err(|e| SourceError::read_failed(&format!("{}: {}", path.display(), e)))?;

                if !path_exists {
                    if self.required {
                        return Err(SourceError::not_found(&path.display().to_string()));
                    }
                    return Ok(RawContent::from_string(""));
                }

                let content = tokio::fs::read_to_string(path)
                    .await
                    .map_err(|e| SourceError::read_failed(&e.to_string()))?;
                return Ok(RawContent::from_string(content).with_source_path(path.clone()));
            }

            // For multiple files, merge them
            let mut merged = serde_json::Value::Object(serde_json::Map::new());
            let mut any_loaded = false;

            for path in &self.paths {
                let path_exists = tokio::fs::try_exists(path)
                    .await
                    .map_err(|e| SourceError::read_failed(&format!("{}: {}", path.display(), e)))?;

                if !path_exists {
                    if self.required {
                        return Err(SourceError::not_found(&path.display().to_string()));
                    }
                    continue;
                }

                let content = tokio::fs::read_to_string(path)
                    .await
                    .map_err(|e| SourceError::read_failed(&e.to_string()))?;

                let format = Self::detect_format_from_path(path).ok_or_else(|| {
                    SourceError::invalid_format(
                        "config",
                        &path.extension().unwrap_or_default().to_string_lossy(),
                    )
                })?;

                let value = Self::parse_to_json_value(&content, format, path)?;

                merged = merged
                    .merge_deep(value)
                    .map_err(|e| SourceError::serialization(&e.to_string()))?;
                any_loaded = true;
            }

            if !any_loaded && self.required {
                return Err(SourceError::not_found("No configuration files found"));
            }

            let content = serde_json::to_string(&merged)
                .map_err(|e| SourceError::serialization(&e.to_string()))?;

            Ok(RawContent::from_string(content))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn create_temp_file(content: &str, extension: &str) -> NamedTempFile {
        let mut file = NamedTempFile::with_suffix(extension).unwrap();
        write!(file, "{}", content).unwrap();
        file
    }

    #[test]
    fn test_file_source_builder() {
        let source = FileSource::builder()
            .path("/etc/config.toml")
            .required(false)
            .build()
            .unwrap();

        assert!(!source.is_required());
        assert_eq!(source.paths.len(), 1);
    }

    #[test]
    fn test_file_source_builder_no_paths() {
        let result = FileSource::builder().build();
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_format() {
        assert_eq!(
            FileSource::detect_format_from_path(Path::new("config.toml")),
            Some(Format::Toml)
        );
        assert_eq!(
            FileSource::detect_format_from_path(Path::new("config.json")),
            Some(Format::Json)
        );
        #[cfg(feature = "yaml")]
        {
            assert_eq!(
                FileSource::detect_format_from_path(Path::new("config.yaml")),
                Some(Format::Yaml)
            );
            assert_eq!(
                FileSource::detect_format_from_path(Path::new("config.yml")),
                Some(Format::Yaml)
            );
        }
        assert_eq!(
            FileSource::detect_format_from_path(Path::new("config.txt")),
            None
        );
    }

    #[cfg(feature = "toml")]
    #[test]
    fn test_load_raw_toml() {
        let content = r#"
        name = "test"
        value = 42
        "#;
        let file = create_temp_file(content, ".toml");

        let source = FileSource::new(file.path());
        let raw = source.load_raw().unwrap();
        let str_content = raw.as_str().unwrap();
        assert!(str_content.as_ref().contains("test"));
    }

    #[cfg(feature = "json")]
    #[test]
    fn test_load_raw_json() {
        let content = r#"{"name": "test", "value": 42}"#;
        let file = create_temp_file(content, ".json");

        let source = FileSource::new(file.path());
        let raw = source.load_raw().unwrap();
        let str_content = raw.as_str().unwrap();
        assert!(str_content.as_ref().contains("test"));
    }

    #[test]
    fn test_load_file_not_found() {
        let source = FileSource::new("/nonexistent/config.toml");
        let result = source.load_raw();
        assert!(result.is_err());
    }

    #[test]
    fn test_load_optional_file_not_found() {
        let source = FileSource::builder()
            .path("/nonexistent/config.toml")
            .required(false)
            .build()
            .unwrap();

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

    #[test]
    fn test_metadata() {
        let source = FileSource::new("config.toml");
        let meta = source.metadata();

        assert_eq!(meta.name, "file");
        assert_eq!(source.kind(), SourceKind::File);
        assert_eq!(meta.priority, 100);
    }

    #[cfg(feature = "async")]
    #[cfg(feature = "toml")]
    #[tokio::test]
    async fn test_load_raw_async_toml() {
        let content = r#"
        name = "async_test"
        value = 123
        "#;
        let file = create_temp_file(content, ".toml");

        let source = FileSource::new(file.path());
        let raw = source.load_raw_async().await.unwrap();
        let str_content = raw.as_str().unwrap();
        assert!(str_content.as_ref().contains("async_test"));
    }

    #[cfg(feature = "async")]
    #[cfg(feature = "json")]
    #[tokio::test]
    async fn test_load_raw_async_json() {
        let content = r#"{"name": "async_test", "value": 123}"#;
        let file = create_temp_file(content, ".json");

        let source = FileSource::new(file.path());
        let raw = source.load_raw_async().await.unwrap();
        let str_content = raw.as_str().unwrap();
        assert!(str_content.as_ref().contains("async_test"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_load_raw_async_file_not_found() {
        let source = FileSource::new("/nonexistent/async_config.toml");
        let result = source.load_raw_async().await;
        assert!(result.is_err());
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_load_raw_async_optional_not_found() {
        let source = FileSource::builder()
            .path("/nonexistent/async_config.toml")
            .required(false)
            .build()
            .unwrap();

        let raw = source.load_raw_async().await.unwrap();
        assert!(raw.is_empty());
    }

    #[cfg(feature = "async")]
    #[cfg(feature = "toml")]
    #[tokio::test]
    async fn test_load_raw_async_multiple_files() {
        let content1 = r#"[section1]
key1 = "value1""#;
        let content2 = r#"[section2]
key2 = "value2""#;
        let file1 = create_temp_file(content1, ".toml");
        let file2 = create_temp_file(content2, ".toml");

        let source = FileSource::builder()
            .path(file1.path())
            .path(file2.path())
            .build()
            .unwrap();

        let raw = source.load_raw_async().await.unwrap();
        let str_content = raw.as_str().unwrap();
        assert!(str_content.as_ref().contains("section1"));
        assert!(str_content.as_ref().contains("section2"));
    }
}