Skip to content

Commit 2860b1b

Browse files
committed
fix: Defer tomlkit import using tomllib fallback strategy
1 parent 49bb647 commit 2860b1b

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

src/mxdev/uv.py

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,35 @@ def write(self, state: State) -> None:
3535
logger.error("[%s] Failed to read pyproject.toml: %s", self.namespace, e)
3636
return
3737

38-
if "[tool.uv]" not in content:
39-
logger.debug(
40-
"[%s] Project not explicitly managed by uv ([tool.uv] managed=true missing), skipping.", self.namespace
41-
)
38+
# Attempt to parse using standard library (Python 3.11+)
39+
try:
40+
import tomllib
41+
42+
parsed = tomllib.loads(content)
43+
if parsed.get("tool", {}).get("uv", {}).get("managed") is not True:
44+
logger.debug(
45+
"[%s] Project not explicitly managed by uv ([tool.uv] managed=true missing), skipping.",
46+
self.namespace,
47+
)
48+
return
49+
except ImportError:
50+
# Fallback for Python 3.10: fast string check to avoid tomlkit overhead
51+
if "[tool.uv]" not in content:
52+
logger.debug(
53+
"[%s] Project not explicitly managed by uv ([tool.uv] managed=true missing), skipping.",
54+
self.namespace,
55+
)
56+
return
57+
except Exception:
58+
# If the parser fails (e.g., malformed TOML), just skip.
4259
return
4360

61+
# Now we are confident it's a uv project, require our heavy dependency
4462
try:
45-
import tomlkit
63+
from typing import TYPE_CHECKING
64+
65+
if not TYPE_CHECKING:
66+
import tomlkit
4667
except ImportError:
4768
raise RuntimeError("tomlkit is required for the uv hook. Install it with: pip install mxdev[uv]")
4869

tests/test_uv.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def test_hook_raises_runtime_error_if_tomlkit_missing(mocker, tmp_path, monkeypa
292292
config = Configuration("mx.ini")
293293
state = State(config)
294294

295-
(tmp_path / "pyproject.toml").write_text("[tool.uv]\\nmanaged = true\\n")
295+
(tmp_path / "pyproject.toml").write_text("[tool.uv]\nmanaged = true\n")
296296

297297
mocker.patch.dict(sys.modules, {"tomlkit": None})
298298
# Also need to make the import fail
@@ -321,7 +321,7 @@ def test_hook_does_not_require_tomlkit_if_not_uv_managed(mocker, tmp_path, monke
321321
config = Configuration("mx.ini")
322322
state = State(config)
323323

324-
(tmp_path / "pyproject.toml").write_text("[project]\\nname = 'test'\\n")
324+
(tmp_path / "pyproject.toml").write_text("[project]\nname = 'test'\n")
325325

326326
mocker.patch.dict(sys.modules, {"tomlkit": None})
327327
import builtins

0 commit comments

Comments
 (0)