|
| 1 | +import pickle |
| 2 | +from pathlib import Path |
| 3 | +from typing import TypeVar |
| 4 | + |
| 5 | +from pcontract.data import Collection |
| 6 | + |
| 7 | +T = TypeVar("T", bound="FileBackend") |
| 8 | + |
| 9 | + |
| 10 | +class FileBackend: |
| 11 | + def __init__(self, filename: str | Path = None) -> None: |
| 12 | + if isinstance(filename, str): |
| 13 | + filename = Path(filename) |
| 14 | + |
| 15 | + self._filename = filename |
| 16 | + self._file = None |
| 17 | + self._collection = None |
| 18 | + |
| 19 | + def init(self, *args, **kwargs) -> None: |
| 20 | + if self._collection: |
| 21 | + raise ValueError("The collection is already initialized.") |
| 22 | + |
| 23 | + self._collection = Collection.init(*args, **kwargs) |
| 24 | + self._filename = self._collection.uuid |
| 25 | + self._dump() |
| 26 | + |
| 27 | + def branch(self, *args, **kwargs) -> None: |
| 28 | + self._collection.branch(*args, **kwargs) |
| 29 | + self._dump() |
| 30 | + |
| 31 | + def explain(self): |
| 32 | + return self._collection.explain() |
| 33 | + |
| 34 | + def gantt(self): |
| 35 | + return self._collection.gantt() |
| 36 | + |
| 37 | + def __enter__(self: T) -> T: |
| 38 | + if self._filename is not None: |
| 39 | + with open(self._filename, "rb") as f: |
| 40 | + self._collection = pickle.load(f) |
| 41 | + return self |
| 42 | + |
| 43 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 44 | + if self._file is not None: |
| 45 | + self._file.close() |
| 46 | + |
| 47 | + def _dump(self): |
| 48 | + if self._file is None: |
| 49 | + self._file = open(self._filename, "wb") |
| 50 | + pickle.dump(self._collection, self._file) |
| 51 | + |
| 52 | + |
| 53 | +def file(filename: str | Path = None) -> FileBackend: |
| 54 | + return FileBackend(filename) |
0 commit comments