Skip to content

Commit

Permalink
ENH: error handling to avoid half-written files
Browse files Browse the repository at this point in the history
  • Loading branch information
ZLLentz committed Nov 22, 2024
1 parent ad6165b commit 0d6a352
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions camviewer_ui_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2794,9 +2794,19 @@ def write_global_config(gui: GraphicUserInterface) -> None:
@contextlib.contextmanager
def atomic_writer(path: str) -> typing.Iterator[typing.TextIO]:
with tempfile.NamedTemporaryFile("w", delete=False) as fd:
yield fd
# File must be closed before we can chmod and move it
fd.close()
# Set -rw-r--r-- instead of temp file default -rw-------
os.chmod(fd.name, 0o644)
shutil.move(fd.name, path)
try:
yield fd
except Exception as exc:
# There is some issue and the temp file is not complete.
# Avoid the else block, we don't want to keep the corrupt file.
# Show some error instead of bricking the gui
print(f"Error writing {path}: {exc}")
else:
# File must be closed before we can chmod and move it
fd.close()
# Set -rw-r--r-- instead of temp file default -rw-------
os.chmod(fd.name, 0o644)
shutil.move(fd.name, path)
# If the tempfile still exists, we should clean it up.
if os.path.exists(fd.name):
os.remove(fd.name)

0 comments on commit 0d6a352

Please sign in to comment.