Skip to content

Commit 05df311

Browse files
committed
fix: Clean up temporary files on write failure
1 parent 86f69c7 commit 05df311

2 files changed

Lines changed: 8 additions & 0 deletions

File tree

src/mxdev/uv.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,21 @@ def write(self, state: State) -> None:
5959
logger.info("[%s] Updating pyproject.toml...", self.namespace)
6060
self._update_pyproject(doc, state)
6161

62+
tmp = None
6263
try:
6364
with tempfile.NamedTemporaryFile(
6465
mode="w", dir=pyproject_path.parent, suffix=".tmp", delete=False, encoding="utf-8"
6566
) as f:
6667
tomlkit.dump(doc, f)
6768
tmp = f.name
6869
os.replace(tmp, str(pyproject_path))
70+
tmp = None # success, don't clean up
6971
logger.info("[%s] Successfully updated pyproject.toml", self.namespace)
7072
except OSError as e:
7173
logger.error("[%s] Failed to write pyproject.toml: %s", self.namespace, e)
74+
finally:
75+
if tmp and os.path.exists(tmp):
76+
os.unlink(tmp)
7277

7378
def _update_pyproject(self, doc: "tomlkit.TOMLDocument", state: State) -> None:
7479
"""Modify the pyproject.toml document based on mxdev state."""

tests/test_uv.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,9 @@ def test_hook_handles_oserror_on_write(mocker, tmp_path, monkeypatch):
280280

281281
mock_logger.error.assert_called_with("[%s] Failed to write pyproject.toml: %s", "uv", mocker.ANY)
282282

283+
# Ensure no .tmp files are left behind
284+
assert len(list(tmp_path.glob("*.tmp"))) == 0
285+
283286

284287
def test_hook_raises_runtime_error_if_tomlkit_missing(mocker, tmp_path, monkeypatch):
285288
monkeypatch.chdir(tmp_path)

0 commit comments

Comments
 (0)