Skip to content

Commit 24c505b

Browse files
committed
refactor: Lazy load tomlkit, use atomic writes, and fix path resolution
1 parent bed9e2c commit 24c505b

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/mxdev/uv.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import logging
77
import re
8-
import tomlkit
98

109

1110
logger = logging.getLogger("mxdev")
@@ -25,15 +24,20 @@ def read(self, state: State) -> None:
2524
pass
2625

2726
def write(self, state: State) -> None:
28-
pyproject_path = Path("pyproject.toml")
27+
try:
28+
import tomlkit
29+
except ImportError:
30+
raise RuntimeError("tomlkit is required for the uv hook. Install it with: pip install mxdev[uv]")
31+
32+
pyproject_path = Path(state.configuration.settings.get("directory", ".")) / "pyproject.toml"
2933
if not pyproject_path.exists():
3034
logger.debug("[%s] pyproject.toml not found, skipping.", self.namespace)
3135
return
3236

3337
try:
3438
with pyproject_path.open("r", encoding="utf-8") as f:
3539
doc = tomlkit.load(f)
36-
except Exception as e:
40+
except OSError as e:
3741
logger.error("[%s] Failed to read pyproject.toml: %s", self.namespace, e)
3842
return
3943

@@ -49,14 +53,23 @@ def write(self, state: State) -> None:
4953
self._update_pyproject(doc, state)
5054

5155
try:
52-
with pyproject_path.open("w", encoding="utf-8") as f:
56+
import os
57+
import tempfile
58+
59+
with tempfile.NamedTemporaryFile(
60+
mode="w", dir=pyproject_path.parent, suffix=".tmp", delete=False, encoding="utf-8"
61+
) as f:
5362
tomlkit.dump(doc, f)
63+
tmp = f.name
64+
os.replace(tmp, str(pyproject_path))
5465
logger.info("[%s] Successfully updated pyproject.toml", self.namespace)
55-
except Exception as e:
66+
except OSError as e:
5667
logger.error("[%s] Failed to write pyproject.toml: %s", self.namespace, e)
5768

5869
def _update_pyproject(self, doc: Any, state: State) -> None:
5970
"""Modify the pyproject.toml document based on mxdev state."""
71+
import tomlkit
72+
6073
if not state.configuration.packages:
6174
return
6275

0 commit comments

Comments
 (0)