From 517716ad572237f140ee4678eb9f59dd2db9419f Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Thu, 29 Jan 2026 21:23:35 +0000 Subject: [PATCH] Add config module --- src/config/loader.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/config/loader.py diff --git a/src/config/loader.py b/src/config/loader.py new file mode 100644 index 0000000..9d172a0 --- /dev/null +++ b/src/config/loader.py @@ -0,0 +1,57 @@ +"""Configuration loader module.""" + +from pathlib import Path +from typing import List, Optional + +import yaml + +from ..models import Rule + + +class ConfigLoader: + def __init__(self): + self._config_paths = [ + Path.cwd() / ".shell-safe-validator.yaml", + Path.home() / ".config" / "shell-safe-validator" / "rules.yaml", + ] + self._default_config_path = Path(__file__).parent.parent.parent / "config" / "default_rules.yaml" + + def load_default_rules(self) -> List[Rule]: + if self._default_config_path.exists(): + return self.load_from_file(self._default_config_path) + return [] + + def load_from_file(self, path: Path) -> List[Rule]: + rules = [] + try: + with open(path, "r") as f: + config = yaml.safe_load(f) + if config and "rules" in config: + for rule_data in config["rules"]: + if rule_data.get("enabled", True): + rules.append(Rule.from_dict(rule_data)) + except yaml.YAMLError as e: + raise ValueError(f"Invalid YAML syntax: {e}") + return rules + + def load_user_rules(self) -> List[Rule]: + rules = [] + for config_path in self._config_paths: + if config_path.exists(): + rules.extend(self.load_from_file(config_path)) + return rules + + def load_merged_rules(self, custom_rules: Optional[List[Rule]] = None) -> List[Rule]: + rules = self.load_default_rules() + user_rules = self.load_user_rules() + rule_dict = {r.id: r for r in rules} + for r in user_rules: + rule_dict[r.id] = r + return list(rule_dict.values()) + + +def load_rules(config_path: Optional[str] = None) -> List[Rule]: + loader = ConfigLoader() + if config_path: + return loader.load_from_file(Path(config_path)) + return loader.load_merged_rules()