feat: add preset resolver
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
__all__ = ("PresetResolver",)
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable
|
||||
|
||||
import tomli
|
||||
|
||||
from ..util import merge_dicts
|
||||
from .model import Preset
|
||||
|
||||
|
||||
class PresetResolver:
|
||||
_source_cache: Dict[Path, dict] = {}
|
||||
|
||||
def __init__(self, basepath: Path):
|
||||
self._basepath = basepath
|
||||
|
||||
def iter_sources(self) -> Iterable[Path]:
|
||||
for filepath in (Path(__file__).parent / "default").iterdir():
|
||||
yield filepath
|
||||
user_preset = Path.home() / ".preset.toml"
|
||||
if user_preset.exists():
|
||||
yield user_preset
|
||||
projectpath = self._basepath
|
||||
while projectpath.exists():
|
||||
project_preset = projectpath / ".preset.toml"
|
||||
if project_preset.exists():
|
||||
yield project_preset
|
||||
if projectpath.parent == projectpath:
|
||||
break
|
||||
projectpath = projectpath.parent
|
||||
|
||||
def resolve_preset(self) -> Preset:
|
||||
result_preset_data = {}
|
||||
for filepath in self.iter_sources():
|
||||
if filepath not in self._source_cache:
|
||||
with open(filepath, "rb") as fd:
|
||||
self._source_cache[filepath] = tomli.load(fd)
|
||||
merge_dicts(result_preset_data, self._source_cache[filepath])
|
||||
return Preset(**result_preset_data)
|
||||
Reference in New Issue
Block a user