55
66import logging
77import re
8- import tomlkit
98
109
1110logger = 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