fix(config): write a migrated config file in place if it is not replaceable

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-20 18:39:14 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent f3773de8f8
commit fed03a0069
2 changed files with 29 additions and 8 deletions
+10 -5
View File
@@ -615,18 +615,19 @@ def remove_empty(obj: dict) -> dict:
def _replace_config_file(config_file: Path, content: str) -> None: def _replace_config_file(config_file: Path, content: str) -> None:
"""Replace the configuration file atomically. """Replace the content of the configuration file, atomically where possible.
The content is written to a temporary file next to the configuration file, which then The content is written to a temporary file next to the configuration file, which then
replaces it. If writing fails, the configuration file is left untouched. The new file keeps replaces it. If writing fails, the configuration file is left untouched. The new file keeps
the permission bits of the old one. the permission bits of the old one. A file that can not be replaced, e.g. a single-file
bind mount of a container, is written in place instead.
Args: Args:
config_file (Path): The existing configuration file. config_file (Path): The existing configuration file.
content (str): The new content of the configuration file. content (str): The new content of the configuration file.
Raises: Raises:
OSError: If the temporary file can not be written or can not replace the file. OSError: If the content can not be written.
""" """
fd, tmp_name = tempfile.mkstemp( fd, tmp_name = tempfile.mkstemp(
dir=config_file.parent, prefix=f".{config_file.name}.", suffix=".tmp" dir=config_file.parent, prefix=f".{config_file.name}.", suffix=".tmp"
@@ -637,10 +638,14 @@ def _replace_config_file(config_file: Path, content: str) -> None:
f_out.flush() f_out.flush()
os.fsync(f_out.fileno()) os.fsync(f_out.fileno())
os.chmod(tmp_name, stat.S_IMODE(config_file.stat().st_mode)) os.chmod(tmp_name, stat.S_IMODE(config_file.stat().st_mode))
try:
os.replace(tmp_name, config_file) os.replace(tmp_name, config_file)
except BaseException: except OSError as e:
logger.debug(f"Could not replace '{config_file}' ({e}), writing it in place.")
with config_file.open("w", encoding="utf-8") as f_out:
f_out.write(content)
finally:
Path(tmp_name).unlink(missing_ok=True) Path(tmp_name).unlink(missing_ok=True)
raise
def migrate_config_file(config_file: Path, backup_file: Path) -> bool: def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
+18 -2
View File
@@ -1,5 +1,6 @@
# Test data directory and known migration pairs # Test data directory and known migration pairs
import copy import copy
import errno
import json import json
import os import os
import shutil import shutil
@@ -180,16 +181,31 @@ class TestConfigMigration:
def test_migrate_config_file_write_failure_keeps_original( def test_migrate_config_file_write_failure_keeps_original(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
"""A migrated file that can not replace the old one leaves the old file in place.""" """A migrated configuration that can not be written leaves the old file in place."""
original = tmp_config_file.read_bytes() original = tmp_config_file.read_bytes()
backup_file = tmp_config_file.with_suffix(".bak") backup_file = tmp_config_file.with_suffix(".bak")
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError("replace failed"))) monkeypatch.setattr(os, "fsync", Mock(side_effect=OSError("disk full")))
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False
assert tmp_config_file.read_bytes() == original assert tmp_config_file.read_bytes() == original
assert not list(tmp_config_file.parent.glob("*.tmp")) assert not list(tmp_config_file.parent.glob("*.tmp"))
def test_migrate_config_file_writes_in_place_if_not_replaceable(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A file that can not be replaced, e.g. a single-file bind mount, is written in place."""
original = tmp_config_file.read_bytes()
backup_file = tmp_config_file.with_suffix(".bak")
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError(errno.EBUSY, "busy")))
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is True
assert backup_file.read_bytes() == original
migrated_data = json.loads(tmp_config_file.read_text(encoding="utf-8"))
assert migrated_data["general"]["version"] == __version__
assert not list(tmp_config_file.parent.glob("*.tmp"))
@pytest.mark.parametrize("old_file, expected_file", MIGRATION_PAIRS) @pytest.mark.parametrize("old_file, expected_file", MIGRATION_PAIRS)
def test_migrate_old_version_config(self, tmp_path: Path, old_file: Path, expected_file: Path): def test_migrate_old_version_config(self, tmp_path: Path, old_file: Path, expected_file: Path):