|
| 1 | +# SPDX-FileCopyrightText: 2025 German Aerospace Center (DLR) |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +# SPDX-FileContributor: Michael Meinel |
| 6 | + |
| 7 | +import json |
| 8 | +import os.path |
| 9 | +import pathlib |
| 10 | + |
| 11 | + |
| 12 | +class HermesCache: |
| 13 | + def __init__(self, cache_dir: pathlib.Path): |
| 14 | + self._cache_dir = cache_dir |
| 15 | + self._cached_data = {} |
| 16 | + |
| 17 | + def __enter__(self): |
| 18 | + if self._cache_dir.is_dir(): |
| 19 | + for filepath in self._cache_dir.glob('*'): |
| 20 | + basename, _ = os.path.splitext(filepath.name) |
| 21 | + self._cached_data[basename] = json.load(filepath.open('r')) |
| 22 | + |
| 23 | + return self |
| 24 | + |
| 25 | + def __getitem__(self, item: str) -> dict: |
| 26 | + if item not in self._cached_data: |
| 27 | + filepath = self._cache_dir / f'{item}.json' |
| 28 | + if filepath.is_file(): |
| 29 | + self._cached_data[item] = json.load(filepath.open('r')) |
| 30 | + |
| 31 | + return self._cached_data[item] |
| 32 | + |
| 33 | + def __setitem__(self, key: str, value: dict): |
| 34 | + self._cached_data[key] = value |
| 35 | + |
| 36 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 37 | + if exc_type is None: |
| 38 | + self._cache_dir.mkdir(exist_ok=True, parents=True) |
| 39 | + |
| 40 | + for basename, data in self._cached_data.items(): |
| 41 | + cachefile = self._cache_dir / f'{basename}.json' |
| 42 | + json.dump(data, cachefile.open('w')) |
| 43 | + |
| 44 | + |
| 45 | +class HermesContext: |
| 46 | + CACHE_DIR_NAME = '.hermes' |
| 47 | + |
| 48 | + def __init__(self, project_dir: pathlib.Path = pathlib.Path.cwd()): |
| 49 | + self.project_dir = project_dir |
| 50 | + self.cache_dir = project_dir / self.CACHE_DIR_NAME |
| 51 | + |
| 52 | + self._current_step = [] |
| 53 | + |
| 54 | + def prepare_step(self, step: str, *depends: str) -> None: |
| 55 | + self._current_step.append(step) |
| 56 | + |
| 57 | + def finalize_step(self, step: str) -> None: |
| 58 | + if len(self._current_step) < 1: |
| 59 | + raise ValueError("There is no step to end.") |
| 60 | + if self._current_step[-1] != step: |
| 61 | + raise ValueError(f"Cannot end step {step} while in {self._current_step[-1]}.") |
| 62 | + self._current_step.pop() |
| 63 | + |
| 64 | + def __getitem__(self, source_name: str) -> HermesCache: |
| 65 | + if len(self._current_step) < 1: |
| 66 | + raise HermesContexError("Prepare a step first.") |
| 67 | + subdir = self.cache_dir / self._current_step[-1] / source_name |
| 68 | + return HermesCache(subdir) |
| 69 | + |
| 70 | + |
| 71 | +class HermesContexError(Exception): |
| 72 | + pass |
0 commit comments