Skip to content

Commit

Permalink
Merge pull request #200 from gerlero/files
Browse files Browse the repository at this point in the history
Replace create method of FoamFile
  • Loading branch information
gerlero authored Sep 29, 2024
2 parents 3ab1fa2 + d969c85 commit ab51a87
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 46 deletions.
53 changes: 12 additions & 41 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@
else:
from typing import Iterator, Mapping, MutableMapping, Sequence

if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self

from ._base import FoamFileBase
from ._io import _FoamFileIO
from ._serialization import Kind, dumpb
Expand Down Expand Up @@ -101,28 +96,6 @@ def as_dict(self) -> FoamFileBase._Dict:

return cast(FoamFileBase._Dict, ret)

def create(self, *, exist_ok: bool = False, parents: bool = False) -> Self:
"""
Create the file.
:param exist_ok: If False, raise a FileExistsError if the file already exists.
:param parents: If True, also create parent directories as needed.
"""
if self.path.exists():
if not exist_ok:
raise FileExistsError(self.path)
else:
return self

if parents:
self.path.parent.mkdir(parents=True, exist_ok=True)

self.path.touch()
self._write_header()

return self

@property
def version(self) -> float:
"""Alias of `self["FoamFile", "version"]`."""
Expand Down Expand Up @@ -185,17 +158,6 @@ def object_(self) -> str:
def object_(self, value: str) -> None:
self["FoamFile", "object"] = value

def _write_header(self) -> None:
assert "FoamFile" not in self
assert not self

self["FoamFile"] = {}
self.version = 2.0
self.format = "ascii"
self.class_ = "dictionary"
self.location = f'"{self.path.parent.name}"'
self.object_ = self.path.name

def __getitem__(
self, keywords: Optional[Union[str, Tuple[str, ...]]]
) -> Union["FoamFile.Data", "FoamFile.SubDict"]:
Expand All @@ -222,8 +184,17 @@ def __setitem__(
elif not isinstance(keywords, tuple):
keywords = (keywords,)

if not self and "FoamFile" not in self and keywords[0] != "FoamFile":
self._write_header()
if (
not self
and "FoamFile" not in self
and (not keywords or keywords[0] != "FoamFile")
):
self["FoamFile"] = {}
self.version = 2.0
self.format = "ascii"
self.class_ = "dictionary"
self.location = f'"{self.path.parent.name}"'
self.object_ = self.path.name

kind = Kind.DEFAULT
if keywords == ("internalField",) or (
Expand Down Expand Up @@ -253,7 +224,7 @@ def __setitem__(
self[keywords] = data

else:
contents, parsed = self._read()
contents, parsed = self._read(missing_ok=True)

start, end = parsed.entry_location(keywords, missing_ok=True)

Expand Down
12 changes: 9 additions & 3 deletions foamlib/_files/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __init__(self, path: Union[str, Path]) -> None:

def __enter__(self) -> Self:
if self.__defer_io == 0:
self._read()
self._read(missing_ok=True)
self.__defer_io += 1
return self

Expand All @@ -44,9 +44,15 @@ def __exit__(
assert self.__contents is not None
self._write(self.__contents)

def _read(self) -> Tuple[bytes, Parsed]:
def _read(self, *, missing_ok: bool = False) -> Tuple[bytes, Parsed]:
if not self.__defer_io:
contents = self.path.read_bytes()
try:
contents = self.path.read_bytes()
except FileNotFoundError:
if missing_ok:
contents = b""
else:
raise

if self.path.suffix == ".gz":
contents = gzip.decompress(contents)
Expand Down
11 changes: 9 additions & 2 deletions tests/test_files/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@

def test_write_read(tmp_path: Path) -> None:
path = tmp_path / "testDict"
path.touch()

d = FoamFile(path)
assert d.path == path
with pytest.raises(FileNotFoundError):
d["key"]

d[None] = "touch"
assert len(d) == 1
assert d[None] == "touch"
assert list(d) == [None]
del d[None]

assert not d
assert len(d) == 0
assert list(d) == []
Expand Down

0 comments on commit ab51a87

Please sign in to comment.