app.rs 75 lignes · 2382 octets
//! Application configuration

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Returns the application display name from `APP_NAME` env var,
/// falling back to "My App". Used as the default everywhere branding appears.
pub fn default_app_name() -> String {
    std::env::var("APP_NAME").unwrap_or_else(|_| "My App".to_string())
}

/// Application configuration with feature flags
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    /// Human-readable application name (env: `APP_NAME`).
    pub app_name: String,
    /// Application version string taken from `Cargo.toml`.
    pub app_version: String,
    /// Map of feature flag names to enabled/disabled state.
    pub features: HashMap<String, bool>,
    /// UI theme identifier (env: `APP_THEME`).
    pub theme: String,
    /// Whether the application is running in debug/development mode.
    pub debug_mode: bool,
}

impl AppConfig {
    /// Create a new `AppConfig` using default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Return `true` if the named feature flag is enabled.
    pub fn is_feature_enabled(&self, feature: &str) -> bool {
        self.features.get(feature).copied().unwrap_or(false)
    }

    /// Enable the named feature flag.
    pub fn enable_feature(&mut self, feature: &str) {
        self.features.insert(feature.to_string(), true);
    }

    /// Disable the named feature flag.
    pub fn disable_feature(&mut self, feature: &str) {
        self.features.insert(feature.to_string(), false);
    }

    /// Load application configuration from environment variables.
    pub fn from_env() -> Self {
        let mut config = Self::default();
        if let Ok(name) = std::env::var("APP_NAME") {
            config.app_name = name;
        }
        if let Ok(theme) = std::env::var("APP_THEME") {
            config.theme = theme;
        }
        if let Ok(debug) = std::env::var("APP_DEBUG") {
            config.debug_mode = debug.parse().unwrap_or(false);
        }
        config
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        let features = HashMap::new();
        Self {
            app_name: default_app_name(),
            app_version: env!("CARGO_PKG_VERSION").to_string(),
            features,
            theme: "light".to_string(),
            debug_mode: false,
        }
    }
}