Files
shell-safe-validator/src/config/loader.py
2026-01-29 21:26:50 +00:00

53 lines
1.7 KiB
Python

"""Configuration loader."""
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):
if self._default_config_path.exists():
return self.load_from_file(self._default_config_path)
return []
def load_from_file(self, path):
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):
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=None):
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=None):
loader = ConfigLoader()
if config_path:
return loader.load_from_file(Path(config_path))
return loader.load_merged_rules()