confers 0.2.2

A modern, type-safe configuration management library with validation, diff, and hot-reload support
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! ConfigBuilder - A config-rs compatible API for confers
//!
//! This module provides a Builder-style API that is compatible with config-rs,
//! making migration from config-rs to confers much easier.
//!
//! # Configuration Source Priority
//!
//! Configuration sources are applied in the order they are added, with later sources
//! overriding earlier ones. The priority order is:
//!
//! 1. **Default values** (lowest priority) - Set via `set_default()`
//! 2. **File sources** - Added via `add_source(File::with_name(...))`
//! 3. **Environment variables** (highest priority) - Added via `add_source(Environment::with_prefix(...))`
//!
//! # Merging Strategy
//!
//! - Default values are merged together into a single configuration object
//! - Configuration sources are merged sequentially, with later sources overriding earlier ones
//! - Nested values are merged at the field level, not at the object level
//! - If a parent key exists but is not an object type, setting a nested value will return an error
//!
//! # Performance Considerations
//!
//! - All default values are combined into a single map before merging, reducing unnecessary operations
//! - File format detection is done once per file source
//! - Configuration extraction uses figment's efficient deserialization
//! - For large configurations with many defaults, consider using `Default` trait instead
//!
//! # Example
//!
//! ```rust,no_run
//! use confers::{ConfigBuilder, Environment, File};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct MyConfig {
//!     server: ServerConfig,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ServerConfig {
//!     port: u16,
//!     host: String,
//! }
//!
//! let config: MyConfig = ConfigBuilder::new()
//!     .set_default("server.port", 8899)?
//!     .set_default("server.host", "0.0.0.0")?
//!     .add_source(File::with_name("config/default").required(false))
//!     .add_source(Environment::with_prefix("CRAWLRS").separator("__"))
//!     .build()?;
//! # Ok::<(), confers::ConfigError>(())
//! ```

use crate::error::ConfigError;
use crate::utils::FileFormat;
use figment::providers::{Env, Format, Json, Serialized, Toml, Yaml};
use figment::{Figment, Profile};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// Configuration builder with config-rs compatible API
///
/// This builder provides a migration-friendly API that closely mirrors config-rs,
/// allowing for gradual migration with minimal code changes.
///
/// # Example
///
/// ```rust,no_run
/// use confers::{ConfigBuilder, Environment, File};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// struct MyConfig {
///     server: ServerConfig,
/// }
///
/// #[derive(Debug, Serialize, Deserialize)]
/// struct ServerConfig {
///     port: u16,
///     host: String,
/// }
///
/// let config: MyConfig = ConfigBuilder::new()
///     .set_default("server.port", 8899)?
///     .set_default("server.host", "0.0.0.0")?
///     .add_source(File::with_name("config/default").required(false))
///     .add_source(Environment::with_prefix("CRAWLRS").separator("__"))
///     .build()?;
/// # Ok::<(), confers::ConfigError>(())
/// ```
#[derive(Clone, Default)]
pub struct ConfigBuilder {
    /// Internal figment for configuration
    figment: Figment,
    /// Default values as a map
    defaults: Vec<(String, serde_json::Value)>,
}

impl ConfigBuilder {
    /// Create a new configuration builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a default value for a configuration key
    ///
    /// This method allows setting default values one at a time, similar to config-rs.
    /// The key can use dot notation for nested values (e.g., "server.port").
    ///
    /// # Arguments
    ///
    /// * `key` - Configuration key (supports dot notation for nested values)
    /// * `value` - Default value (must be JSON-serializable)
    ///
    /// # Example
    ///
    /// ```rust
    /// use confers::ConfigBuilder;
    ///
    /// let builder = ConfigBuilder::new()
    ///     .set_default("server.port", 8080)?
    ///     .set_default("server.host", "localhost")?
    ///     .set_default("debug", true)?;
    /// # Ok::<(), confers::ConfigError>(())
    /// ```
    pub fn set_default<K, V>(mut self, key: K, value: V) -> Result<Self, ConfigError>
    where
        K: AsRef<str>,
        V: Serialize + Into<serde_json::Value>,
    {
        let key_str = key.as_ref().to_string();
        let json_value = serde_json::to_value(&value).map_err(|e| {
            ConfigError::SerializationError(format!("Failed to serialize default value: {}", e))
        })?;

        self.defaults.push((key_str, json_value));
        Ok(self)
    }

    /// Add a configuration source
    ///
    /// This method adds a configuration source to the builder.
    /// Sources are loaded in the order they are added, with later sources overriding earlier ones.
    ///
    /// # Arguments
    ///
    /// * `source` - Configuration source to add
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use confers::{ConfigBuilder, Environment, File};
    ///
    /// let builder = ConfigBuilder::new()
    ///     .add_source(File::with_name("config/default"))
    ///     .add_source(Environment::with_prefix("APP").separator("__"));
    /// # Ok::<(), confers::ConfigError>(())
    /// ```
    pub fn add_source<S>(mut self, source: S) -> Self
    where
        S: Into<Source>,
    {
        let source = source.into();
        self.figment = self.figment.merge(source.into_figment());
        self
    }

    /// Build the configuration
    ///
    /// This method builds the final configuration by merging all sources and defaults.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Configuration type (must be deserializable)
    ///
    /// # Returns
    ///
    /// Returns the deserialized configuration or an error
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use confers::ConfigBuilder;
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Debug, Serialize, Deserialize)]
    /// struct Config {
    ///     port: u16,
    ///     host: String,
    /// }
    ///
    /// let config: Config = ConfigBuilder::new()
    ///     .set_default("port", 8080)?
    ///     .set_default("host", "localhost")?
    ///     .build()?;
    /// # Ok::<(), confers::ConfigError>(())
    /// ```
    pub fn build<T>(self) -> Result<T, ConfigError>
    where
        T: DeserializeOwned + Serialize,
    {
        // Apply defaults first
        let mut figment = self.figment;

        // Merge all defaults into a single map for better performance
        let mut defaults_map = serde_json::Map::new();
        for (key, value) in self.defaults {
            insert_nested_value(&mut defaults_map, &key, value)?;
        }

        if !defaults_map.is_empty() {
            let defaults_value = serde_json::Value::Object(defaults_map);
            figment = figment.merge(figment::providers::Serialized::defaults(defaults_value));
        }

        // Extract the configuration
        figment.extract().map_err(|e| {
            ConfigError::ParseError(format!(
                "Failed to extract configuration: {}. Check if all required fields are provided and have correct types.",
                e
            ))
        })
    }

    /// Build the configuration with validation
    ///
    /// This method builds the configuration and validates it using the `Validate` trait.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Configuration type (must be deserializable and implement `Validate`)
    ///
    /// # Returns
    ///
    /// Returns the validated configuration or an error
    #[cfg(feature = "validation")]
    pub fn build_with_validation<T>(self) -> Result<T, ConfigError>
    where
        T: DeserializeOwned + Serialize + validator::Validate,
    {
        let config = self.build::<T>()?;

        config.validate().map_err(|e| {
            ConfigError::ValidationError(format!("Configuration validation failed: {}", e))
        })?;

        Ok(config)
    }

    /// Clear all default values
    ///
    /// This method removes all previously set default values.
    ///
    /// # Example
    ///
    /// ```rust
    /// use confers::ConfigBuilder;
    ///
    /// let builder = ConfigBuilder::new()
    ///     .set_default("port", 8080)?
    ///     .clear_defaults();
    /// # Ok::<(), confers::ConfigError>(())
    /// ```
    pub fn clear_defaults(mut self) -> Self {
        self.defaults.clear();
        self
    }

    /// Get the number of default values set
    ///
    /// # Returns
    ///
    /// The number of default values currently set
    pub fn defaults_count(&self) -> usize {
        self.defaults.len()
    }
}

/// Helper function to insert nested values using dot notation (internal use only)
pub(crate) fn insert_nested_value(
    map: &mut serde_json::Map<String, serde_json::Value>,
    key: &str,
    value: serde_json::Value,
) -> Result<(), ConfigError> {
    if key.is_empty() {
        return Err(ConfigError::ParseError("Key cannot be empty".to_string()));
    }

    let parts: Vec<&str> = key.split('.').collect();

    if parts.len() == 1 {
        map.insert(parts[0].to_string(), value);
        return Ok(());
    }

    let current_key = parts[0].to_string();
    let remaining_key = parts[1..].join(".");

    if !map.contains_key(&current_key) {
        map.insert(
            current_key.clone(),
            serde_json::Value::Object(serde_json::Map::new()),
        );
    } else {
        // Check if existing value is an object type
        if !matches!(map[&current_key], serde_json::Value::Object(_)) {
            return Err(ConfigError::ParseError(format!(
                "Cannot set nested value '{}' because '{}' is not an object",
                remaining_key, current_key
            )));
        }
    }

    if let serde_json::Value::Object(ref mut nested_map) = map[&current_key] {
        insert_nested_value(nested_map, &remaining_key, value)?;
    }

    Ok(())
}

/// Configuration source
///
/// Represents various configuration sources such as files, environment variables, etc.
#[derive(Clone)]
pub enum Source {
    /// File configuration source
    File(FileSource),
    /// Environment configuration source
    Environment(EnvironmentSource),
}

impl std::fmt::Debug for Source {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Source::File(file) => write!(f, "File({:?})", file),
            Source::Environment(env) => write!(f, "Environment({:?})", env),
        }
    }
}

impl Source {
    fn into_figment(self) -> Figment {
        match self {
            Source::File(file) => file.into_figment(),
            Source::Environment(env) => env.into_figment(),
        }
    }
}

impl From<FileSource> for Source {
    fn from(file: FileSource) -> Self {
        Source::File(file)
    }
}

impl From<EnvironmentSource> for Source {
    fn from(env: EnvironmentSource) -> Self {
        Source::Environment(env)
    }
}

/// File configuration source
///
/// Represents a configuration file with optional format detection.
#[derive(Clone, Debug)]
pub struct FileSource {
    /// File name or path (can include or exclude extension)
    name: PathBuf,
    /// File format (None for auto-detection)
    format: Option<FileFormat>,
    /// Whether the file is required
    required: bool,
}

impl FileSource {
    /// Create a new file source from a file name
    ///
    /// # Arguments
    ///
    /// * `name` - File name (can include or exclude extension)
    ///
    /// # Example
    ///
    /// ```rust
    /// use confers::File;
    ///
    /// let file = File::with_name("config/default");
    /// ```
    pub fn with_name(name: impl AsRef<Path>) -> Self {
        let path = name.as_ref();

        // Validate path is not empty
        if path.as_os_str().is_empty() {
            #[cfg(feature = "tracing")]
            tracing::warn!("File path is empty, using default configuration");
            return Self {
                name: PathBuf::from("config"),
                format: None,
                required: false,
            };
        }

        // Validate path doesn't contain path traversal attacks
        let path_str = path.to_string_lossy();

        // Security: Check for various path traversal patterns
        let suspicious_patterns = [
            "..",      // Standard traversal
            "./",      // Current directory reference
            "//",      // Double slash
            "\\",      // Windows backslash (can bypass some checks)
            "%2e%2e",  // URL encoded ".."
            "%2e%2e/", // URL encoded "../"
            "..%2f",   // Mixed encoding
        ];

        let is_suspicious = suspicious_patterns
            .iter()
            .any(|pattern| path_str.contains(pattern));

        if is_suspicious {
            #[cfg(feature = "tracing")]
            tracing::error!(
                "Path contains suspicious patterns that may indicate a path traversal attempt: {}. Using safe default.",
                path_str
            );
            return Self {
                name: PathBuf::from("config"),
                format: None,
                required: false,
            };
        }

        // Additional security: Ensure path is within allowed directories
        // This prevents paths like /etc/passwd or other sensitive files
        let sensitive_prefixes = [
            "/etc/",
            "/usr/",
            "/var/log/",
            "/root/",
            "/home/",
            "C:\\Windows\\",
            "C:\\Program Files\\",
        ];

        let lower_path = path_str.to_lowercase();
        let is_sensitive = sensitive_prefixes
            .iter()
            .any(|prefix| lower_path.starts_with(prefix));

        if is_sensitive {
            #[cfg(feature = "tracing")]
            tracing::error!(
                "Path points to sensitive system directory: {}. Using safe default.",
                path_str
            );
            return Self {
                name: PathBuf::from("config"),
                format: None,
                required: false,
            };
        }

        // Canonicalize path to resolve any symlinks or relative paths
        // This helps prevent symlink attacks
        let canonical_path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());

        // Final check: ensure the canonical path is still safe
        let canonical_str = canonical_path.to_string_lossy();
        let canonical_sensitive = sensitive_prefixes
            .iter()
            .any(|prefix| canonical_str.to_lowercase().starts_with(prefix));

        if canonical_sensitive {
            #[cfg(feature = "tracing")]
            tracing::error!(
                "Resolved path points to sensitive system directory: {}. Using safe default.",
                canonical_str
            );
            return Self {
                name: PathBuf::from("config"),
                format: None,
                required: false,
            };
        }

        Self {
            name: canonical_path,
            format: None,
            required: false,
        }
    }

    /// Set the file as required
    ///
    /// If the file is required and doesn't exist, an error will be returned.
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Set the file format explicitly
    pub fn format(mut self, format: FileFormat) -> Self {
        self.format = Some(format);
        self
    }

    fn into_figment(self) -> Figment {
        let path = self.name;

        // Determine format: use explicit format, or detect from extension, or default to TOML
        let format = self
            .format
            .or_else(|| {
                path.extension()
                    .and_then(|ext| ext.to_str())
                    .and_then(|ext| FileFormat::from_str(ext).ok())
            })
            .unwrap_or(FileFormat::Toml); // Default to TOML if no extension matches

        match format {
            FileFormat::Toml => Figment::from(Toml::file(path)),
            FileFormat::Json => Figment::from(Json::file(path)),
            FileFormat::Yaml => Figment::from(Yaml::file(path)),
            FileFormat::Ini => {
                let content = std::fs::read_to_string(&path).unwrap_or_default();
                let ini_value = serde_ini::from_str::<serde_json::Value>(&content)
                    .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
                Figment::from(Serialized::from(ini_value, Profile::Default))
            }
            FileFormat::Unknown => Figment::from(Toml::file(path)), // Default to TOML for unknown
        }
    }
}

/// Environment configuration source
///
/// Represents environment variables as a configuration source.
#[derive(Clone, Debug)]
pub struct EnvironmentSource {
    /// Prefix for environment variables
    prefix: Option<String>,
    /// Separator for nested keys (default: "_")
    separator: String,
}

impl EnvironmentSource {
    /// Create a new environment source with a prefix
    ///
    /// # Arguments
    ///
    /// * `prefix` - Environment variable prefix
    ///
    /// # Example
    ///
    /// ```rust
    /// use confers::Environment;
    ///
    /// let env = Environment::with_prefix("APP");
    /// ```
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        let prefix_str = prefix.into();
        if prefix_str.is_empty() {
            #[cfg(feature = "tracing")]
            tracing::warn!("Empty prefix for environment variables, no prefix will be applied");
        }
        Self {
            prefix: if prefix_str.is_empty() {
                None
            } else {
                Some(prefix_str)
            },
            separator: "_".to_string(),
        }
    }

    /// Set the separator for nested keys
    ///
    /// # Arguments
    ///
    /// * `separator` - Separator string (e.g., "_", "__", ".")
    ///
    /// # Example
    ///
    /// ```rust
    /// use confers::Environment;
    ///
    /// let env = Environment::with_prefix("APP").separator("__");
    /// ```
    pub fn separator(mut self, separator: impl Into<String>) -> Self {
        let sep = separator.into();
        if sep.is_empty() {
            #[cfg(feature = "tracing")]
            tracing::warn!(
                "Empty separator for environment variables may cause unexpected behavior"
            );
        }
        self.separator = sep;
        self
    }

    fn into_figment(self) -> Figment {
        if let Some(prefix) = self.prefix {
            Figment::from(Env::prefixed(&prefix).split(&self.separator))
        } else {
            Figment::from(Env::raw())
        }
    }
}

/// Type alias for File source (config-rs compatibility)
pub type File = FileSource;

/// Type alias for Environment source (config-rs compatibility)
pub type Environment = EnvironmentSource;

/// Extension trait for saving configuration
pub trait ConfigSaveExt {
    /// Save configuration to a file (infer format from extension)
    fn save(&self, path: impl AsRef<std::path::Path>) -> Result<u64, ConfigError>;
    /// Save configuration with explicit format
    fn save_to_with_format(
        &self,
        path: impl AsRef<std::path::Path>,
        format: FileFormat,
    ) -> Result<u64, ConfigError>;
}

impl<T> ConfigSaveExt for T
where
    T: Serialize,
{
    fn save(&self, path: impl AsRef<std::path::Path>) -> Result<u64, ConfigError> {
        let ext = path
            .as_ref()
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_lowercase())
            .unwrap_or_else(|| "json".to_string());

        let format = match ext.as_str() {
            "toml" => FileFormat::Toml,
            "yaml" | "yml" => FileFormat::Yaml,
            "ini" => FileFormat::Ini,
            _ => FileFormat::Json,
        };

        self.save_to_with_format(path, format)
    }

    fn save_to_with_format(
        &self,
        path: impl AsRef<std::path::Path>,
        format: FileFormat,
    ) -> Result<u64, ConfigError> {
        use std::fs::File;
        use std::io::Write;

        let data = serde_json::to_value(self).map_err(|e| {
            ConfigError::SerializationError(format!("Failed to serialize config: {}", e))
        })?;

        let content = crate::utils::file_format::serialize_to_format(&data, format)
            .map_err(ConfigError::SerializationError)?;

        let mut file = File::create(path)
            .map_err(|e| ConfigError::IoError(format!("Failed to create file: {}", e)))?;

        file.write_all(content.as_bytes())
            .map_err(|e| ConfigError::IoError(format!("Failed to write file: {}", e)))?;

        Ok(content.len() as u64)
    }
}