Files
luk/src/utils/shared_config.py
Bendt a41d59e529 WIP
2025-12-18 22:11:47 -05:00

115 lines
3.0 KiB
Python

"""Shared configuration for all LUK TUI applications.
This module provides shared settings that apply across all apps,
such as theme configuration.
"""
import logging
import os
from pathlib import Path
from typing import Optional
try:
import toml
except ImportError:
toml = None # type: ignore
logger = logging.getLogger(__name__)
# Available Textual themes
AVAILABLE_THEMES = [
"textual-dark",
"textual-light",
"nord",
"gruvbox",
"catppuccin-mocha",
"dracula",
"monokai",
"solarized-light",
"tokyo-night",
]
# Default shared configuration
DEFAULT_SHARED_CONFIG = {
"theme": {
"name": "monokai", # Default Textual theme
},
}
def get_shared_config_path() -> Path:
"""Get the shared config file path."""
config_home = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
return Path(config_home) / "luk" / "shared.toml"
def load_shared_config() -> dict:
"""Load shared configuration from TOML file.
Returns merged config with defaults for any missing values.
"""
config = DEFAULT_SHARED_CONFIG.copy()
config_path = get_shared_config_path()
if config_path.exists() and toml is not None:
try:
user_config = toml.load(config_path)
# Deep merge user config into defaults
for section, values in user_config.items():
if section in config and isinstance(config[section], dict):
config[section].update(values)
else:
config[section] = values
logger.info(f"Loaded shared config from {config_path}")
except Exception as e:
logger.warning(f"Error loading shared config: {e}")
else:
logger.debug(f"No shared config at {config_path}, using defaults")
return config
def get_theme_name() -> str:
"""Get the configured theme name."""
config = load_shared_config()
return config.get("theme", {}).get("name", "monokai")
def create_default_shared_config() -> None:
"""Create a default shared.toml config file if it doesn't exist."""
config_path = get_shared_config_path()
if config_path.exists():
return
if toml is None:
logger.warning("toml module not available, cannot create config")
return
# Ensure parent directory exists
config_path.parent.mkdir(parents=True, exist_ok=True)
with open(config_path, "w") as f:
toml.dump(DEFAULT_SHARED_CONFIG, f)
logger.info(f"Created default shared config at {config_path}")
# Global cached config
_shared_config: Optional[dict] = None
def get_shared_config() -> dict:
"""Get the cached shared config, loading if necessary."""
global _shared_config
if _shared_config is None:
_shared_config = load_shared_config()
return _shared_config
def reload_shared_config() -> dict:
"""Force reload of shared config from disk."""
global _shared_config
_shared_config = load_shared_config()
return _shared_config