Add config module
This commit is contained in:
57
src/config/loader.py
Normal file
57
src/config/loader.py
Normal file
@@ -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()
|
||||||
Reference in New Issue
Block a user