Skip to content

Write --write-changes via a tempfile so interrupts cannot empty files - #4028

Merged
larsoner merged 2 commits into
codespell-project:mainfrom
ekanshul:fix-4025-atomic-write-changes
Sep 21, 2026
Merged

larsoner merged 2 commits into
codespell-project:mainfrom
ekanshul:fix-4025-atomic-write-changes

Conversation

@ekanshul

Copy link
Copy Markdown
Contributor

Fixes #4025

--write-changes currently opens the target with "w", which truncates it before the corrected text is written. If the process is killed, the disk is full, or the write fails after that open, the original file is left at 0 bytes.

This writes to a same-directory tempfile and os.replaces it over the original, so a failed update keeps the previous contents. The original file mode is copied onto the tempfile before the replace.

Tests cover a failed os.replace (original text remains, leftover tempfiles are removed) and preservation of POSIX permission bits.

open(..., "w") truncates the target before the new contents are
written, so a kill, full disk, or failed write leaves the original
file at 0 bytes. Write to a same-directory tempfile, copy the
original mode, then os.replace so a failed update keeps the old text.

Fixes codespell-project#4025
@larsoner

Copy link
Copy Markdown
Member

Just a tiny tweak to use realpath, marking for merge-when-green, thanks in advance @ekanshul !

@larsoner
larsoner enabled auto-merge (squash) September 21, 2026 16:32
@larsoner
larsoner merged commit 68804d2 into codespell-project:main Sep 21, 2026
15 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An interrupted --write-changes leaves the file at 0 bytes

2 participants