fix(config): write a migrated config file in place only with a backup

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 fed03a0069
commit 867bc38fc0
2 changed files with 56 additions and 6 deletions
+19 -6
View File
@@ -13,6 +13,7 @@ from typing import (
Callable, Callable,
Dict, Dict,
List, List,
Optional,
Set, Set,
Tuple, Tuple,
Union, Union,
@@ -614,17 +615,21 @@ def remove_empty(obj: dict) -> dict:
return obj return obj
def _replace_config_file(config_file: Path, content: str) -> None: def _replace_config_file(config_file: Path, content: str, backup_file: Optional[Path]) -> None:
"""Replace the content of the configuration file, atomically where possible. """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. A file that can not be replaced, e.g. a single-file the permission bits of the old one.
bind mount of a container, is written in place instead.
A file that can not be replaced, e.g. a single-file bind mount of a container, is written in
place instead, but only if there is a backup of it. If writing in place fails, the file is
restored from the backup.
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.
backup_file (Optional[Path]): A copy of the configuration file, None if there is none.
Raises: Raises:
OSError: If the content can not be written. OSError: If the content can not be written.
@@ -641,9 +646,15 @@ def _replace_config_file(config_file: Path, content: str) -> None:
try: try:
os.replace(tmp_name, config_file) os.replace(tmp_name, config_file)
except OSError as e: except OSError as e:
if backup_file is None:
raise
logger.debug(f"Could not replace '{config_file}' ({e}), writing it in place.") logger.debug(f"Could not replace '{config_file}' ({e}), writing it in place.")
with config_file.open("w", encoding="utf-8") as f_out: try:
f_out.write(content) with config_file.open("w", encoding="utf-8") as f_out:
f_out.write(content)
except OSError:
shutil.copyfile(backup_file, config_file)
raise
finally: finally:
Path(tmp_name).unlink(missing_ok=True) Path(tmp_name).unlink(missing_ok=True)
@@ -703,8 +714,10 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
# Backup existing file - we already know it is existing. Copy it: the file stays in # Backup existing file - we already know it is existing. Copy it: the file stays in
# place until the migrated configuration replaces it. # place until the migrated configuration replaces it.
backed_up_file: Optional[Path] = None
try: try:
shutil.copy2(config_file, backup_file) shutil.copy2(config_file, backup_file)
backed_up_file = backup_file
logger.info(f"Backed up old configuration to '{backup_file}'.") logger.info(f"Backed up old configuration to '{backup_file}'.")
except Exception as e_copy: except Exception as e_copy:
logger.warning( logger.warning(
@@ -713,7 +726,7 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
# Write migrated configuration # Write migrated configuration
try: try:
_replace_config_file(config_file, json_str) _replace_config_file(config_file, json_str, backed_up_file)
except Exception as e_write: except Exception as e_write:
logger.error(f"Failed to write migrated configuration to '{config_file}': {e_write}") logger.error(f"Failed to write migrated configuration to '{config_file}': {e_write}")
return False return False
+37
View File
@@ -206,6 +206,43 @@ class TestConfigMigration:
assert migrated_data["general"]["version"] == __version__ assert migrated_data["general"]["version"] == __version__
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_only_with_backup(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A file that can not be replaced and not be backed up is left as it is."""
original = tmp_config_file.read_bytes()
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError(errno.EBUSY, "busy")))
monkeypatch.setattr(shutil, "copy2", Mock(side_effect=OSError(errno.EACCES, "denied")))
result = configmigrate.migrate_config_file(
tmp_config_file, tmp_config_file.with_suffix(".bak")
)
assert result is False
assert tmp_config_file.read_bytes() == original
def test_migrate_config_file_restores_backup_if_writing_in_place_fails(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
original = tmp_config_file.read_bytes()
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError(errno.EBUSY, "busy")))
path_open = Path.open
def open_full_disk(path: Path, mode: str = "r", *args: Any, **kwargs: Any) -> Any:
if path == tmp_config_file and "w" in mode:
path_open(path, "w").close()
raise OSError(errno.ENOSPC, "No space left on device")
return path_open(path, mode, *args, **kwargs)
monkeypatch.setattr(Path, "open", open_full_disk)
result = configmigrate.migrate_config_file(
tmp_config_file, tmp_config_file.with_suffix(".bak")
)
assert result is False
assert tmp_config_file.read_bytes() == original
@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):