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
//! Memory source implementation for testing.
//!
//! [`MemorySource`] provides an in-memory configuration source
//! primarily intended for testing purposes.

use std::collections::HashMap;

use serde_json::Value;

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

/// Builder for [`MemorySource`].
#[derive(Debug, Default)]
pub struct MemorySourceBuilder {
    data: HashMap<String, Value>,
    required: bool,
    name: Option<String>,
}

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

    /// Insert a key-value pair.
    #[must_use]
    pub fn insert(mut self, key: impl Into<String>, value: Value) -> Self {
        self.data.insert(key.into(), value);
        self
    }

    /// Insert multiple key-value pairs.
    #[must_use]
    pub fn extend(mut self, data: HashMap<String, Value>) -> Self {
        self.data.extend(data);
        self
    }

    /// Set a string value.
    #[must_use]
    pub fn set(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.data.insert(key.into(), Value::String(value.into()));
        self
    }

    /// Set a numeric value.
    #[must_use]
    pub fn set_number(mut self, key: impl Into<String>, value: f64) -> Self {
        self.data.insert(key.into(), serde_json::json!(value));
        self
    }

    /// Set a boolean value.
    #[must_use]
    pub fn set_bool(mut self, key: impl Into<String>, value: bool) -> Self {
        self.data.insert(key.into(), Value::Bool(value));
        self
    }

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

    /// Set a custom name for the source.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Build the memory source.
    #[must_use]
    pub fn build(self) -> MemorySource {
        MemorySource {
            data: self.data,
            required: self.required,
            name: self.name,
        }
    }
}

/// In-memory configuration source for testing.
///
/// This source holds configuration data in memory and is primarily
/// used for testing other components.
///
/// # Example
///
/// ```rust
/// use cfgmatic_source::{MemorySource, Source};
///
/// let source = MemorySource::builder()
///     .set("name", "test-app")
///     .set_number("port", 8080.0)
///     .set_bool("debug", true)
///     .build();
///
/// let raw = source.load_raw().unwrap();
/// assert!(!raw.is_empty());
/// ```
#[derive(Debug, Clone)]
pub struct MemorySource {
    /// Configuration data.
    data: HashMap<String, Value>,
    /// Whether the source is required.
    required: bool,
    /// Custom name for the source.
    name: Option<String>,
}

impl MemorySource {
    /// Create a new empty memory source.
    #[must_use]
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
            required: false,
            name: None,
        }
    }

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

    /// Create a memory source from a JSON value.
    #[must_use]
    pub fn from_json(value: Value) -> Self {
        let data = if let Value::Object(map) = value {
            map.into_iter().collect()
        } else {
            let mut map = HashMap::new();
            map.insert("value".to_string(), value);
            map
        };

        Self {
            data,
            required: false,
            name: None,
        }
    }

    /// Create a memory source from a serializable value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value cannot be serialized to JSON.
    pub fn from_serializable<T: serde::Serialize>(value: &T) -> Result<Self> {
        let json =
            serde_json::to_value(value).map_err(|e| SourceError::serialization(&e.to_string()))?;
        Ok(Self::from_json(json))
    }

    /// Get a value by key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.data.get(key)
    }

    /// Check if a key exists.
    #[must_use]
    pub fn contains(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }

    /// Get the number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Check if the source is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Insert a value.
    pub fn insert(&mut self, key: impl Into<String>, value: Value) {
        self.data.insert(key.into(), value);
    }

    /// Remove a value.
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        self.data.remove(key)
    }

    /// Clear all values.
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Convert data to JSON object.
    fn to_json_object(&self) -> Value {
        Value::Object(self.data.clone().into_iter().collect())
    }
}

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

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

    fn metadata(&self) -> SourceMetadata {
        SourceMetadata::new(self.name.clone().unwrap_or_else(|| "memory".to_string()))
            .with_priority(50)
            .with_optional(!self.required)
    }

    fn load_raw(&self) -> Result<RawContent> {
        if self.data.is_empty() && self.required {
            return Err(SourceError::not_found("Memory source is empty"));
        }

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

        Ok(RawContent::from_string(content))
    }

    fn detect_format(&self) -> Option<Format> {
        // Memory source always produces JSON
        Some(Format::Json)
    }

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

#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_memory_source_new() {
        let source = MemorySource::new();
        assert!(source.is_empty());
        assert!(!source.is_required());
    }

    #[test]
    fn test_memory_source_builder() {
        let source = MemorySource::builder()
            .set("name", "test")
            .set_number("port", 8080.0)
            .set_bool("debug", true)
            .required(true)
            .build();

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

    #[test]
    fn test_memory_source_from_json() {
        let json = json!({
            "name": "myapp",
            "version": "1.0.0"
        });

        let source = MemorySource::from_json(json);
        assert_eq!(source.len(), 2);
        assert_eq!(source.get("name"), Some(&json!("myapp")));
    }

    #[test]
    fn test_memory_source_from_serializable() {
        #[derive(Debug, serde::Serialize)]
        struct Config {
            name: String,
            value: u32,
        }

        let config = Config {
            name: "test".to_string(),
            value: 42,
        };

        let source = MemorySource::from_serializable(&config).unwrap();
        assert_eq!(source.get("name"), Some(&json!("test")));
        assert_eq!(source.get("value"), Some(&json!(42)));
    }

    #[test]
    fn test_memory_source_load_raw() {
        let source = MemorySource::builder()
            .set("name", "test-app")
            .insert("value", serde_json::json!(42))
            .build();

        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_memory_source_load_nested() {
        let source = MemorySource::builder()
            .insert(
                "database",
                json!({
                    "host": "localhost",
                    "port": 5432
                }),
            )
            .build();

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

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

        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct TestConfig {
            database: Database,
        }

        let config: TestConfig = serde_json::from_str(content.as_ref()).unwrap();
        assert_eq!(config.database.host, "localhost");
        assert_eq!(config.database.port, 5432);
    }

    #[test]
    fn test_memory_source_modify() {
        let mut source = MemorySource::new();

        source.insert("key", json!("value"));
        assert!(source.contains("key"));

        source.remove("key");
        assert!(!source.contains("key"));
    }

    #[test]
    fn test_memory_source_clear() {
        let mut source = MemorySource::builder().set("a", "1").set("b", "2").build();

        source.clear();
        assert!(source.is_empty());
    }

    #[test]
    fn test_memory_source_empty_required() {
        let source = MemorySource::builder().required(true).build();

        let result = source.load_raw();
        assert!(result.is_err());
    }

    #[test]
    fn test_memory_source_metadata() {
        let source = MemorySource::builder().name("test-source").build();

        let meta = source.metadata();
        assert_eq!(meta.name, "test-source");
        assert_eq!(source.kind(), SourceKind::Memory);
        assert_eq!(meta.priority, 50);
    }

    #[test]
    fn test_memory_source_default_name() {
        let source = MemorySource::new();
        let meta = source.metadata();
        assert_eq!(meta.name, "memory");
    }

    #[test]
    fn test_memory_source_clone() {
        let source = MemorySource::builder().set("name", "test").build();

        let cloned = source.clone();
        assert_eq!(cloned.len(), source.len());
    }
}