Skip to content

Commit

Permalink
Merge pull request #201 from gerlero/files
Browse files Browse the repository at this point in the history
Fix file IO
  • Loading branch information
gerlero authored Sep 29, 2024
2 parents ab51a87 + d7cecae commit 58e0ed7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 14 deletions.
19 changes: 13 additions & 6 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,17 +184,24 @@ def __setitem__(
elif not isinstance(keywords, tuple):
keywords = (keywords,)

if (
not self
and "FoamFile" not in self
and (not keywords or keywords[0] != "FoamFile")
):
try:
write_header = (
not self
and "FoamFile" not in self
and (not keywords or keywords[0] != "FoamFile")
)
except FileNotFoundError:
write_header = not keywords or keywords[0] != "FoamFile"

if write_header:
self["FoamFile"] = {}
self.version = 2.0
self.format = "ascii"
self.class_ = "dictionary"
self.location = f'"{self.path.parent.name}"'
self.object_ = self.path.name
self.object_ = (
self.path.stem if self.path.suffix == ".gz" else self.path.name
)

kind = Kind.DEFAULT
if keywords == ("internalField",) or (
Expand Down
18 changes: 10 additions & 8 deletions foamlib/_files/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,21 @@ def _read(self, *, missing_ok: bool = False) -> Tuple[bytes, Parsed]:
try:
contents = self.path.read_bytes()
except FileNotFoundError:
if missing_ok:
contents = b""
else:
raise

if self.path.suffix == ".gz":
contents = gzip.decompress(contents)
contents = None
else:
assert isinstance(contents, bytes)
if self.path.suffix == ".gz":
contents = gzip.decompress(contents)

if contents != self.__contents:
self.__contents = contents
self.__parsed = None

assert self.__contents is not None
if self.__contents is None:
if missing_ok:
return b"", Parsed(b"")
else:
raise FileNotFoundError(self.path)

if self.__parsed is None:
parsed = Parsed(self.__contents)
Expand Down
4 changes: 4 additions & 0 deletions tests/test_files/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ def test_write_read(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
d["key"]

with d:
with pytest.raises(FileNotFoundError):
d["key"]

d[None] = "touch"
assert len(d) == 1
assert d[None] == "touch"
Expand Down

0 comments on commit 58e0ed7

Please sign in to comment.