config-resolver 0.2.1

A modular configuration resolver for auto-detecting and resolving runtime values (IPs, ports, peer IDs)
Documentation
use crate::create_default_registry;
use crate::error::Error;
use crate::registry::ConfigRegistry;
use crate::types::ConfigUnit;
use std::sync::OnceLock;

static GLOBAL_REGISTRY: OnceLock<ConfigRegistry> = OnceLock::new();

/// Initializes the global registry with a custom registry.
///
/// # Errors
///
/// Returns an error if the global registry has already been initialized.
pub fn init_global_registry(registry: ConfigRegistry) -> Result<(), Error> {
    GLOBAL_REGISTRY
        .set(registry)
        .map_err(|_| Error::ParseError("Global registry already initialized".to_string()))
}

/// Returns a reference to the global registry, initializing it with standard providers if not already set.
pub fn get_global_registry() -> &'static ConfigRegistry {
    GLOBAL_REGISTRY.get_or_init(create_default_registry)
}

/// A helper function designed for `clap`'s `value_parser` to resolve config specs synchronously.
///
/// # Example
/// ```ignore
/// #[derive(clap::Parser)]
/// struct Args {
///     #[arg(long, default_value = "1000", value_parser = config_resolver::clap_value_parser::<u32>)]
///     peer_id: u32,
/// }
/// ```
pub fn clap_value_parser<T: ConfigUnit + 'static>(s: &str) -> Result<T, String> {
    get_global_registry()
        .resolve_sync(s)
        .map_err(|e| e.to_string())
}