From d7cecae9bb05e285124477d9bf2bbc5396e0fe53 Mon Sep 17 00:00:00 2001 From: Gabriel Gerlero Date: Sun, 29 Sep 2024 20:47:50 -0300 Subject: [PATCH] Fix file IO --- foamlib/_files/_files.py | 19 +++++++++++++------ foamlib/_files/_io.py | 18 ++++++++++-------- tests/test_files/test_files.py | 4 ++++ 3 files changed, 27 insertions(+), 14 deletions(-) diff --git a/foamlib/_files/_files.py b/foamlib/_files/_files.py index db3afc2..45a9554 100644 --- a/foamlib/_files/_files.py +++ b/foamlib/_files/_files.py @@ -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 ( diff --git a/foamlib/_files/_io.py b/foamlib/_files/_io.py index 1c898f0..bc8002f 100644 --- a/foamlib/_files/_io.py +++ b/foamlib/_files/_io.py @@ -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) diff --git a/tests/test_files/test_files.py b/tests/test_files/test_files.py index b4a4967..00839bc 100644 --- a/tests/test_files/test_files.py +++ b/tests/test_files/test_files.py @@ -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"