Skip to content

Commit 9272aca

Browse files
committed
Add file backend
1 parent c408bcb commit 9272aca

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

pcontract/backends.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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)

pcontract/data.py

+1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ def __init__(
9393
) -> None:
9494
self.items: list[Branch] = items
9595
self.klass: Type[Branch] = klass
96+
self.uuid: str = uuid.uuid4().hex
9697

9798
def __repr__(self) -> str:
9899
return "<%s %s>" % (self.__class__.__name__, repr(self.items))

0 commit comments

Comments
 (0)