cfgmatic-source 5.0.1

Configuration sources (file, env, memory) for cfgmatic framework
Documentation
//! Builder for [`SourceCoordinator`](super::SourceCoordinator).

use std::collections::BTreeMap;

use crate::config::{CacheMode, ErrorMode, LoadOptions, MergeStrategy};
use crate::domain::Source;

use super::{SourceCoordinator, entry::SourceEntry};

/// Builder for [`SourceCoordinator`].
#[derive(Default)]
pub struct SourceCoordinatorBuilder {
    sources: Vec<SourceEntry>,
    options: Option<LoadOptions>,
}

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

    /// Add a source with a priority.
    #[must_use]
    pub fn add_source<S: Source + 'static>(mut self, source: S, priority: i32) -> Self {
        let entry = SourceEntry {
            source: Box::new(source),
            priority,
            order: self.sources.len(),
        };
        self.sources.push(entry);
        self
    }

    /// 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.error_mode = ErrorMode::from_fail_fast(fail_fast);
        self.options = Some(options);
        self
    }

    /// Set whether to enable caching.
    #[must_use]
    pub fn cache_enabled(mut self, enabled: bool) -> Self {
        let mut options = self.options.unwrap_or_default();
        options.cache_mode = CacheMode::from_enabled(enabled);
        self.options = Some(options);
        self
    }

    /// Build the `SourceCoordinator`.
    #[must_use]
    pub fn build(self) -> SourceCoordinator {
        SourceCoordinator {
            sources: self.sources,
            options: self.options.unwrap_or_default(),
            cache: BTreeMap::new(),
        }
    }
}

impl std::fmt::Debug for SourceCoordinatorBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SourceCoordinatorBuilder")
            .field("source_count", &self.sources.len())
            .field("options", &self.options)
            .finish()
    }
}