Skip to content

Commit

Permalink
Merge pull request #159 from gerlero/files
Browse files Browse the repository at this point in the history
Add create method to FoamFile
  • Loading branch information
gerlero authored Aug 23, 2024
2 parents ca56353 + 7367066 commit 6a99c19
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
6 changes: 2 additions & 4 deletions foamlib/_cases/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,10 @@ def name(self) -> str:
return self.path.name

def __getitem__(self, key: str) -> FoamFieldFile:
if (self.path / key).is_file():
return FoamFieldFile(self.path / key)
elif (self.path / f"{key}.gz").is_file():
if (self.path / f"{key}.gz").is_file() and not (self.path / key).is_file():
return FoamFieldFile(self.path / f"{key}.gz")
else:
raise KeyError(key)
return FoamFieldFile(self.path / key)

def __contains__(self, obj: object) -> bool:
if isinstance(obj, FoamFieldFile):
Expand Down
32 changes: 32 additions & 0 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
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 .._util import is_sequence
from ._base import FoamFileBase
from ._io import _FoamFileIO
Expand Down Expand Up @@ -96,6 +101,32 @@ def as_dict(self) -> FoamFileBase._Dict:

return ret

def create(self, *, exist_ok: bool = False, parents: bool = False) -> Self:
"""
Create the file.
Parameters
----------
exist_ok : bool, optional
If False (the default), raise a FileExistsError if the file already exists.
If True, do nothing if the file already exists.
parents : bool, optional
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 @@ -160,6 +191,7 @@ def object_(self, value: str) -> None:

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

self["FoamFile"] = {}
self.version = 2.0
Expand Down

0 comments on commit 6a99c19

Please sign in to comment.