89 lines
3.5 KiB
Python
89 lines
3.5 KiB
Python
import os
|
|
import yaml
|
|
from typing import Optional, Dict
|
|
from core.models import (
|
|
AppConfig, TelegramConfig, DiscordConfig, GitConfig,
|
|
MonitoringConfig, LoggingConfig, TaskConfig
|
|
)
|
|
from core.logger import log_err, log_warn
|
|
|
|
|
|
class ConfigManager:
|
|
def __init__(self, config_path: str = "config.yaml"):
|
|
self.config_path = config_path
|
|
self._last_mtime: float = 0.0
|
|
|
|
def load(self, exit_on_fail: bool = False) -> Optional[AppConfig]:
|
|
"""Безопасная загрузка конфигурации без падения процесса"""
|
|
if not os.path.exists(self.config_path):
|
|
log_err(f"Конфиг {self.config_path} не найден!")
|
|
if exit_on_fail:
|
|
raise FileNotFoundError(f"Config file not found: {self.config_path}")
|
|
return None
|
|
|
|
try:
|
|
with open(self.config_path, "r", encoding="utf-8") as f:
|
|
raw_data = yaml.safe_load(f)
|
|
|
|
if raw_data is None:
|
|
log_warn(f"Конфиг {self.config_path} пуст")
|
|
raw_data = {}
|
|
|
|
if not isinstance(raw_data, dict):
|
|
raise ValueError("Корневой элемент YAML должен быть словарем (dict)")
|
|
|
|
telegram = TelegramConfig.from_dict(raw_data.get("telegram") or {})
|
|
discord = DiscordConfig.from_dict(raw_data.get("discord") or {})
|
|
git = GitConfig.from_dict(raw_data.get("git") or {})
|
|
monitoring = MonitoringConfig.from_dict(raw_data.get("monitoring") or {})
|
|
logging_cfg = LoggingConfig.from_dict(raw_data.get("logging") or {})
|
|
|
|
raw_tasks = raw_data.get("tasks") or []
|
|
tasks: Dict[str, TaskConfig] = {}
|
|
|
|
if isinstance(raw_tasks, list):
|
|
for item in raw_tasks:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
name = str(item.get("name", "")).strip()
|
|
if not name:
|
|
log_warn("Пропущена задача без указания имени")
|
|
continue
|
|
if name in tasks:
|
|
log_warn(f"Дублирующееся имя задачи '{name}', перезаписываем")
|
|
tasks[name] = TaskConfig.from_dict(item)
|
|
elif isinstance(raw_tasks, dict):
|
|
for name, item in raw_tasks.items():
|
|
if isinstance(item, dict):
|
|
item["name"] = name
|
|
tasks[name] = TaskConfig.from_dict(item)
|
|
|
|
self._last_mtime = os.path.getmtime(self.config_path)
|
|
return AppConfig(
|
|
telegram=telegram,
|
|
discord=discord,
|
|
git=git,
|
|
monitoring=monitoring,
|
|
logging=logging_cfg,
|
|
tasks=tasks
|
|
)
|
|
|
|
except Exception as e:
|
|
log_err(f"Ошибка парсинга конфига {self.config_path}: {e}")
|
|
if exit_on_fail:
|
|
raise e
|
|
return None
|
|
|
|
def check_modified(self) -> bool:
|
|
"""Проверка изменения файла на диске"""
|
|
try:
|
|
if not os.path.exists(self.config_path):
|
|
return False
|
|
mtime = os.path.getmtime(self.config_path)
|
|
if mtime != self._last_mtime:
|
|
self._last_mtime = mtime
|
|
return True
|
|
except Exception:
|
|
pass
|
|
return False
|