Skip to content

Commit

Permalink
Improve file writing
Browse files Browse the repository at this point in the history
  • Loading branch information
gerlero committed Nov 2, 2024
1 parent 37ef20f commit 26527d8
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,21 +250,20 @@ def __setitem__(

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

before = b""
if parsed.contents[:start] and not parsed.contents[:start].endswith(b"\n"):
before = b"\n"
if (
parsed.contents[:start]
and len(keywords) <= 1
and not parsed.contents[:start].endswith(b"\n\n")
):
before = b"\n\n"
if start and not parsed.contents[:start].endswith(b"\n\n"):
if parsed.contents[:start].endswith(b"\n"):
before = b"\n" if len(keywords) <= 1 else b""
else:
before = b"\n\n" if len(keywords) <= 1 else b"\n"
else:
before = b""

after = b""
if parsed.contents[end:].startswith(b"}"):
after = b" " * (len(keywords) - 2)
if not parsed.contents[end:] or not parsed.contents[end:].startswith(b"\n"):
after = b"\n" + after
if not parsed.contents[end:].strip() or parsed.contents[end:].startswith(
b"}"
):
after = b"\n" + b" " * (len(keywords) - 2)
else:
after = b""

indentation = b" " * (len(keywords) - 1)

Expand Down Expand Up @@ -292,7 +291,7 @@ def __setitem__(
elif keywords:
parsed.put(
keywords,
data,
deepcopy(data),
before
+ indentation
+ dumps(keywords[-1])
Expand All @@ -303,7 +302,7 @@ def __setitem__(
)

else:
parsed.put(keywords, data, before + dumps(data, kind=kind) + after)
parsed.put((), deepcopy(data), before + dumps(data, kind=kind) + after)

def __delitem__(self, keywords: str | tuple[str, ...] | None) -> None:
if not keywords:
Expand Down

0 comments on commit 26527d8

Please sign in to comment.