Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Centralize uv and PEP 723 operations (#10695)

Trevor Manz2337d081b9b2
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 88fc6c710e..1000c571b5 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -542,9 +542,9 @@ def _extract_header_comments(ir: NotebookSerializationV1) -> str | None:
if header:
return str(header)
if pyproject:
- from marimo._utils.scripts import wrap_script_metadata
+ from marimo._environments.script_metadata import wrap_block
- return wrap_script_metadata(pyproject)
+ return wrap_block(pyproject)
return None
except (yaml.YAMLError, AssertionError):
pass
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 21a527dbf1..c0adb31829 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -19,13 +19,20 @@ from marimo import _loggers
from marimo._cli.errors import MarimoCLIMissingDependencyError
from marimo._cli.print import bold, echo, green, muted
from marimo._config.settings import GLOBAL_SETTINGS
-from marimo._dependencies.dependencies import DependencyManager
+from marimo._environments import script_metadata
+from marimo._environments.uv import (
+ UvCommandError,
+ UvMissingScriptMetadataError,
+ UvNotFoundError,
+ find_uv_bin,
+ is_uv_available,
+ require_uv_bin,
+ uv,
+)
from marimo._utils.inline_script_metadata import (
PyProjectReader,
- has_marimo_in_script_metadata,
is_marimo_dependency,
)
-from marimo._utils.uv import find_uv_bin
from marimo._utils.versions import is_editable
from marimo._version import __version__
@@ -62,7 +69,7 @@ def maybe_prompt_run_in_sandbox(name: str | None) -> bool:
return False
# Notebook has inlined dependencies.
- if DependencyManager.which("uv"):
+ if is_uv_available():
if GLOBAL_SETTINGS.YES:
return True
@@ -214,21 +221,19 @@ def _uv_export_script_requirements_txt(
if not name:
return []
- result = subprocess.run(
+ script = Path(name).absolute()
+ result = uv(
[
- find_uv_bin(),
"export",
"--no-hashes",
"--no-annotate",
"--no-header",
"--script",
- name,
+ str(script),
],
- check=True,
- capture_output=True,
- text=True,
+ cwd=str(script.parent),
)
- script_dir = Path(name).resolve().parent
+ script_dir = script.parent
return [
_resolve_local_path_line(line, script_dir)
for line in result.stdout.split("\n")
@@ -239,8 +244,16 @@ def _resolve_requirements_txt_lines(pyproject: PyProjectReader) -> list[str]:
if pyproject.name and pyproject.name.endswith(".py"):
try:
return _uv_export_script_requirements_txt(pyproject.name)
- except subprocess.CalledProcessError:
- pass # Fall back if uv fails
+ except UvMissingScriptMetadataError:
+ # No PEP 723 block yet; marimo's own reader handles that fine.
+ pass
+ except UvCommandError as e:
+ LOGGER.warning(
+ "`uv export` failed for %s; falling back to marimo's own "
+ "dependency resolution: %s",
+ pyproject.name,
+ e.stderr.strip(),
+ )
return pyproject.requirements_txt_lines
@@ -361,91 +374,6 @@ def construct_uv_command(
return uv_cmd + cmd
-def _ensure_python_version_in_script_metadata(name: str) -> None:
- """Add requires-python to script metadata if not present.
-
- Inserts a requires-python line directly into the existing PEP 723
- metadata block without re-serializing, to avoid reformatting diffs.
- """
- import re
-
- from marimo._utils.scripts import read_pyproject_from_script
-
- with open(name, encoding="utf-8") as f:
- content = f.read()
-
- project = read_pyproject_from_script(content)
- if project is None:
- # No script metadata exists
- return
-
- if "requires-python" in project:
- return
-
- version_tuple = platform.python_version_tuple()
- requires_line = (
- f'# requires-python = ">={version_tuple[0]}.{version_tuple[1]}"\n'
- )
-
- # Insert directly after the opening "# /// script" marker to avoid
- # re-serializing the entire block and causing formatting churn.
- new_content = re.sub(
- r"^# /// script$",
- "# /// script\n" + requires_line.rstrip(),
- content,
- count=1,
- flags=re.MULTILINE,
- )
-
- if new_content != content:
- with open(name, "w", encoding="utf-8") as f:
- f.write(new_content)
-
-
-def _ensure_marimo_in_script_metadata(name: str | None) -> None:
- """Ensure marimo is in the script metadata.
-
- If the file has no PEP 723 script metadata or marimo is not listed
- as a dependency, add marimo using uv.
- """
- # Only applicable to `.py` files.
- if name is None or not name.endswith(".py"):
- return
-
- # If the file doesn't exist or is empty, don't create it here - let marimo
- # create the notebook normally with proper structure
- if not os.path.exists(name) or os.path.getsize(name) == 0:
- return
-
- # Check if script metadata exists and whether marimo is present
- # Returns: True (has marimo), False (no marimo), None (no metadata)
- has_marimo = has_marimo_in_script_metadata(name)
- if has_marimo is True:
- # marimo is already present
- return
-
- # Add marimo to script metadata using uv
- # This will create the script metadata block if it doesn't exist
- try:
- result = subprocess.run(
- [find_uv_bin(), "add", "--script", name, "marimo"],
- check=True,
- capture_output=True,
- text=True,
- # stdin=DEVNULL prevents hanging on Windows when uv might
- # wait for input
- stdin=subprocess.DEVNULL,
- timeout=30,
- )
- LOGGER.info(f"Added marimo to script metadata: {result.stdout}")
- except subprocess.CalledProcessError as e:
- LOGGER.warning(f"Failed to add marimo to script metadata: {e.stderr}")
- except subprocess.TimeoutExpired:
- LOGGER.warning("Timed out adding marimo to script metadata")
- except Exception as e:
- LOGGER.warning(f"Failed to add marimo to script metadata: {e}")
-
-
def run_in_sandbox(
args: list[str],
*,
@@ -465,18 +393,29 @@ def run_in_sandbox(
For "multi" sandbox mode (directory), see IPCKernelManagerImpl which
creates per-notebook sandboxed kernels.
"""
- # If we fall back to the plain "uv" path, ensure it's actually on the system
- if find_uv_bin() == "uv" and not DependencyManager.which("uv"):
+ try:
+ require_uv_bin()
+ except UvNotFoundError as e:
raise MarimoCLIMissingDependencyError(
"uv must be installed to use --sandbox.",
"uv",
additional_tip="Install uv from https://github.com/astral-sh/uv",
- )
+ ) from e
- # Ensure marimo and python version are in the script metadata before running
- _ensure_marimo_in_script_metadata(name)
+ # Ensure marimo and the python version are in the script metadata before
+ # running. Adding marimo is best-effort: the sandbox still runs without
+ # it, since the requirements normalization injects marimo.
if name is not None and name.endswith(".py"):
- _ensure_python_version_in_script_metadata(name)
+ try:
+ script_metadata.ensure_marimo(name)
+ except script_metadata.ScriptMetadataError as e:
+ if isinstance(e.__cause__, subprocess.TimeoutExpired):
+ LOGGER.warning("Timed out adding marimo to script metadata")
+ else:
+ LOGGER.warning("%s", e)
+ except Exception as e:
+ LOGGER.warning(f"Failed to add marimo to script metadata: {e}")
+ script_metadata.ensure_requires_python(name)
uv_cmd = construct_uv_command(
args,
@@ -611,19 +550,13 @@ def build_sandbox_venv(
Raises:
RuntimeError: If dependency installation fails.
"""
- uv_bin = find_uv_bin()
-
# Create temp directory for sandbox venv
sandbox_dir = tempfile.mkdtemp(prefix="marimo-sandbox-")
venv_path = os.path.join(sandbox_dir, "venv")
# Phase 1: Create venv
echo(f"Creating sandbox environment: {muted(venv_path)}", err=True)
- subprocess.run(
- [uv_bin, "venv", "--seed", venv_path],
- check=True,
- capture_output=True,
- )
+ uv(["venv", "--seed", venv_path])
# Get venv Python path
if sys.platform == "win32":
@@ -644,22 +577,20 @@ def build_sandbox_venv(
for editable in editable_reqs:
# Extract path from "-e /path/to/package"
editable_path = editable[3:].strip()
- result = subprocess.run(
- [
- uv_bin,
- "pip",
- "install",
- "--python",
- venv_python,
- "-e",
- editable_path,
- ],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
+ try:
+ uv(
+ [
+ "pip",
+ "install",
+ "--python",
+ venv_python,
+ "-e",
+ editable_path,
+ ]
+ )
+ except UvCommandError as e:
echo(
- f"Warning: Editable install failed: {result.stderr}",
+ f"Warning: Editable install failed: {e.stderr}",
err=True,
)
@@ -669,25 +600,14 @@ def build_sandbox_venv(
with open(req_file, "w", encoding="utf-8") as f:
f.write("\n".join(regular_reqs))
- result = subprocess.run(
- [
- uv_bin,
- "pip",
- "install",
- "--python",
- venv_python,
- "-r",
- req_file,
- ],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
+ try:
+ uv(["pip", "install", "--python", venv_python, "-r", req_file])
+ except UvCommandError as e:
# Clean up on failure
cleanup_sandbox_dir(sandbox_dir)
raise RuntimeError(
- f"Failed to install sandbox dependencies: {result.stderr}"
- )
+ f"Failed to install sandbox dependencies: {e.stderr}"
+ ) from e
return sandbox_dir, venv_python
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 3d1eef1f4f..dbbf362243 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -435,10 +435,10 @@ class ScriptConfigManager(PartialMarimoConfigReader):
if not filepath.is_file():
return {}
- from marimo._utils.scripts import read_pyproject_from_script
+ from marimo._environments import script_metadata
script_content = filepath.read_text(encoding="utf-8")
- script_config = read_pyproject_from_script(script_content)
+ script_config = script_metadata.loads(script_content)
if script_config is None:
return {}
diff --git a/marimo/_convert/ipynb/to_ir.py b/marimo/_convert/ipynb/to_ir.py
index 880e7ef24a..63e1f26296 100644
--- a/marimo/_convert/ipynb/to_ir.py
+++ b/marimo/_convert/ipynb/to_ir.py
@@ -1382,8 +1382,8 @@ def build_metadata(
Uses PyProjectReader utilities to parse existing metadata and properly
merge dependencies.
"""
+ from marimo._environments import script_metadata
from marimo._utils.inline_script_metadata import PyProjectReader
- from marimo._utils.scripts import write_pyproject_to_script
# If no exclamation mark processing happened or no packages found
if not extra_metadata or not extra_metadata.pip_packages:
@@ -1407,7 +1407,7 @@ def build_metadata(
project = {"dependencies": pip_packages}
# Convert project dict to PEP 723 format using utility
- return write_pyproject_to_script(project)
+ return script_metadata.dumps(project)
def _transform_sources(
diff --git a/marimo/_convert/markdown/to_ir.py b/marimo/_convert/markdown/to_ir.py
index 0c1fe55301..10a8f15aa1 100644
--- a/marimo/_convert/markdown/to_ir.py
+++ b/marimo/_convert/markdown/to_ir.py
@@ -202,8 +202,8 @@ class SafeWrap(Generic[T]):
def _tree_to_ir(root: Element) -> SafeWrap[NotebookSerializationV1]:
from marimo._ast.app_config import _AppConfig
from marimo._ast.parse import NON_MARIMO_MARKDOWN_VIOLATION
+ from marimo._environments.script_metadata import wrap_block
from marimo._utils import yaml
- from marimo._utils.scripts import wrap_script_metadata
app_config = app_config_from_root(root)
config_only = _AppConfig.sanitize(app_config)
@@ -233,7 +233,7 @@ def _tree_to_ir(root: Element) -> SafeWrap[NotebookSerializationV1]:
if frontmatter:
header_value = yaml.dump(frontmatter, sort_keys=False)
elif pyproject and not header_str:
- header_value = wrap_script_metadata(pyproject)
+ header_value = wrap_block(pyproject)
elif header_str:
header_value = header_str
else:
diff --git a/marimo/_environments/__init__.py b/marimo/_environments/__init__.py
new file mode 100644
index 0000000000..fe2d2e388e
--- /dev/null
+++ b/marimo/_environments/__init__.py
@@ -0,0 +1 @@
+# Copyright 2026 Marimo. All rights reserved.
diff --git a/marimo/_environments/errors.py b/marimo/_environments/errors.py
new file mode 100644
index 0000000000..a83bab7e3f
--- /dev/null
+++ b/marimo/_environments/errors.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The base error for environment-manager failures.
+
+Every failure invoking an environment manager -- or the manifest edits
+delegated to one -- derives from this type, so callers of
+backend-agnostic seams catch one error instead of enumerating backends.
+"""
+
+from __future__ import annotations
+
+
+class EnvironmentManagerError(Exception):
+ """Base for failures invoking an environment manager."""
diff --git a/marimo/_environments/script_metadata.py b/marimo/_environments/script_metadata.py
new file mode 100644
index 0000000000..4e99d61ebe
--- /dev/null
+++ b/marimo/_environments/script_metadata.py
@@ -0,0 +1,346 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The PEP 723 inline script metadata block.
+
+This module is the single reader and writer for the `# /// script` block in
+marimo notebooks. In-place edits of a user's file delegate to
+`uv ... --script` so uv owns the TOML edit and the user's formatting
+survives; whole-block generation (converters, codegen, export) serializes
+with tomlkit.
+
+Markdown notebooks (.md/.qmd) carry the block in their frontmatter; edit
+verbs round-trip the header verbatim through a carrier, a hidden sidecar
+next to the notebook, so uv anchors relative paths in the metadata
+against the notebook's directory. uv also runs from that directory, so
+directory-scoped uv configuration applies.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import platform
+import re
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from marimo import _loggers
+from marimo._environments.errors import EnvironmentManagerError
+from marimo._environments.uv import UvError, uv
+from marimo._utils.toml import toml_reader
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Iterator, Sequence
+
+LOGGER = _loggers.marimo_logger()
+
+REGEX = (
+ r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s"
+ r"(?P<content>(^#(?! ///$)(| .*)$\s)+)^# ///$"
+)
+
+
+class ScriptMetadataError(EnvironmentManagerError):
+ """A script metadata edit could not be completed."""
+
+
+def loads(script: str) -> dict[str, Any] | None:
+ """Parse the `# /// script` block, or None if the script has none.
+
+ Adapted from https://peps.python.org/pep-0723/#reference-implementation
+ """
+ name = "script"
+ matches = list(
+ filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
+ )
+ if len(matches) > 1:
+ raise ValueError(f"Multiple {name} blocks found")
+ elif len(matches) == 1:
+ content = "".join(
+ line[2:] if line.startswith("# ") else line[1:]
+ for line in matches[0].group("content").splitlines(keepends=True)
+ )
+ return toml_reader.reads(content)
+ else:
+ return None
+
+
+def dumps(project: dict[str, Any]) -> str:
+ """Serialize a project dict to a `# /// script` block."""
+ import tomlkit
+
+ return wrap_block(tomlkit.dumps(project))
+
+
+def wrap_block(toml_content: str) -> str:
+ """Wrap raw TOML content in `# /// script` markers."""
+ result_lines = ["# /// script"]
+ for line in toml_content.rstrip().split("\n"):
+ result_lines.append(f"# {line}")
+ result_lines.append("# ///")
+ return "\n".join(result_lines)
+
+
+def replace_block(script: str, block: str) -> str:
+ """Replace the script's existing `# /// script` block with `block`."""
+ # A callable replacement keeps backslashes in `block` literal.
+ return re.sub(REGEX, lambda _: block, script, count=1)
+
+
+def with_python_version_requirement(project: dict[str, Any]) -> dict[str, Any]:
+ # TODO(akshayka): consider locking the Python version for greater
+ # reproducibility, instead of returning a lowerbound
+ project = project.copy()
+ version_tuple = platform.python_version_tuple()
+ project["requires-python"] = f">={version_tuple[0]}.{version_tuple[1]}"
+ return project
+
+
+def add_dependencies(
+ path: str, packages: Sequence[str], *, upgrade: bool = False
+) -> None:
+ """Add packages to the script's metadata via `uv add --script`."""
+ if not packages:
+ return
+ args = ["--quiet", "add", "--script"]
+
+ def edit(target: str, cwd: str) -> None:
+ uv(
+ [*args, target, *(["--upgrade"] if upgrade else []), *packages],
+ cwd=cwd,
+ )
+
+ _edit(path, edit)
+
+
+def remove_dependencies(path: str, packages: Sequence[str]) -> None:
+ """Remove packages from the script's metadata via `uv remove --script`."""
+ if not packages:
+ return
+
+ def edit(target: str, cwd: str) -> None:
+ uv(
+ ["--quiet", "remove", "--script", target, *packages],
+ cwd=cwd,
+ )
+
+ _edit(path, edit)
+
+
+def ensure_marimo(path: str) -> None:
+ """Add marimo to the script metadata if it is not already a dependency.
+
+ Creates the metadata block if the file has none. No-op for non-`.py`
+ targets and for missing or empty files, whose block is the notebook
+ serializer's to create.
+ """
+ if not path.endswith(".py"):
+ return
+ if not os.path.exists(path) or os.path.getsize(path) == 0:
+ return
+
+ from marimo._utils.inline_script_metadata import (
+ has_marimo_in_script_metadata,
+ )
+
+ if has_marimo_in_script_metadata(path) is True:
+ return
+
+ def edit(target: str, cwd: str) -> None:
+ uv(["add", "--script", target, "marimo"], timeout=30, cwd=cwd)
+
+ _edit(path, edit)
+
+
+def ensure_requires_python(path: str) -> None:
+ """Add `requires-python` to existing script metadata if not present.
+
+ Splices the line directly after the opening marker instead of
+ re-serializing, to avoid reformatting the user's block. No-op if the
+ file has no metadata block.
+ """
+ with open(path, encoding="utf-8") as f:
+ content = f.read()
+
+ project = loads(content)
+ if project is None or "requires-python" in project:
+ return
+
+ version_tuple = platform.python_version_tuple()
+ requires_line = (
+ f'# requires-python = ">={version_tuple[0]}.{version_tuple[1]}"'
+ )
+ new_content = re.sub(
+ r"^# /// script$",
+ f"# /// script\n{requires_line}",
+ content,
+ count=1,
+ flags=re.MULTILINE,
+ )
+ if new_content != content:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(new_content)
+
+
+def _edit(path: str, edit: Callable[[str, str], None]) -> None:
+ """Apply an edit and normalize expected operational failures.
+
+ Edits receive the file uv operates on and the working directory for
+ the uv invocation, which is always the notebook's own directory so
+ that directory-scoped uv configuration is discovered.
+ """
+ try:
+ if path.endswith((".md", ".qmd")):
+ _edit_frontmatter(path, edit)
+ else:
+ # uv resolves a relative --script target against the cwd this
+ # module pins, so hand it an absolute path.
+ absolute = os.path.abspath(path)
+ edit(absolute, os.path.dirname(absolute))
+ except (UvError, subprocess.TimeoutExpired, OSError) as error:
+ raise ScriptMetadataError(
+ f"Failed to update script metadata for {path}: {error}"
+ ) from error
+
+
+@dataclass(frozen=True)
+class _Frontmatter:
+ """A markdown notebook's frontmatter and its metadata block."""
+
+ data: dict[str, Any]
+ body: str
+ # The comment-wrapped `# /// script` block.
+ header: str
+ # Whether the block came from the `pyproject` frontmatter key.
+ is_pyproject: bool
+
+
+def _read_frontmatter(path: str) -> _Frontmatter:
+ from marimo._convert.markdown.to_ir import extract_frontmatter
+ from marimo._utils import yaml
+ from marimo._utils.inline_script_metadata import (
+ get_headers_from_frontmatter,
+ )
+
+ with open(path, encoding="utf-8", newline="") as f:
+ content = f.read()
+ data, _ = extract_frontmatter(content)
+ match = yaml.YAML_FRONT_MATTER_REGEX.match(content)
+ # Preserve everything after the closing marker, including its newline.
+ body = content[match.end(1) + len("---") :] if match else "\n" + content
+ headers = get_headers_from_frontmatter(data)
+ is_pyproject = bool(headers.get("pyproject", ""))
+ header = (
+ headers.get("pyproject", "")
+ if is_pyproject
+ else headers.get("header", "")
+ )
+ return _Frontmatter(
+ data=data,
+ body=body,
+ header=header,
+ is_pyproject=is_pyproject or not bool(header),
+ )
+
+
+# Bumping the version orphans every older carrier; `_sweep_carriers`
+# recognizes and removes all versions.
+_CARRIER_VERSION = 1
+
+
+def _carrier_prefix(path: str) -> str:
+ """The ownership-signed carrier prefix for a notebook.
+
+ Deterministic per notebook filename, so a carrier is recognizably
+ marimo's: safe to overwrite, sweep, and ignore.
+ """
+ return f".marimo-v{_CARRIER_VERSION}-{os.path.basename(path)}"
+
+
+# A carrier lives for one uv command; a stray this old is stranded.
+_SWEEP_AGE_SECONDS = 15 * 60
+
+
+def _sweep_carriers(directory: str, path: str) -> None:
+ """Removes stranded carriers for the notebook, best effort.
+
+ Carriers are deleted after use; a killed process can strand one.
+ Only strays older than `_SWEEP_AGE_SECONDS` are removed, sparing a
+ concurrent process's in-flight carrier.
+ """
+ import time
+
+ pattern = f".marimo-v*-{os.path.basename(path)}*.py"
+ cutoff = time.time() - _SWEEP_AGE_SECONDS
+ for stray in Path(directory).glob(pattern):
+ try:
+ if stray.stat().st_mtime < cutoff:
+ stray.unlink()
+ except OSError:
+ LOGGER.debug("Could not remove carrier %s", stray)
+
+
+def _carrier(notebook: str, content: str) -> Iterator[str]:
+ """A sidecar script uv can operate on, next to the notebook.
+
+ uv anchors relative paths in script metadata to the script's own
+ directory, so a manifest that lives in frontmatter must be
+ materialized beside its notebook before uv can act on it. The
+ versioned, deterministic name (`.marimo-v<N>-<name>.<rand>.py`)
+ marks the file as marimo's: safe to overwrite, sweep, and ignore.
+ Entry sweeps carriers stranded by killed processes; exit always
+ removes the carrier, best effort.
+ """
+ absolute = os.path.abspath(notebook)
+ directory = os.path.dirname(absolute)
+ _sweep_carriers(directory, absolute)
+ descriptor, target = tempfile.mkstemp(
+ dir=directory, prefix=f"{_carrier_prefix(absolute)}.", suffix=".py"
+ )
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as f:
+ f.write(content)
+ yield target
+ finally:
+ try:
+ os.unlink(target)
+ except OSError:
+ LOGGER.debug("Could not remove carrier %s", target)
+
+
+def _edit_frontmatter(path: str, edit: Callable[[str, str], None]) -> None:
+ """Edits metadata carried in markdown frontmatter.
+
+ The header is materialized verbatim as a carrier next to the
+ notebook, so uv resolves relative paths in the metadata against the
+ notebook's directory. Each edit gets its own carrier, deleted when
+ the edit finishes. The document is rewritten only if the edit
+ succeeds.
+ """
+ from marimo._utils import yaml
+
+ front = _read_frontmatter(path)
+
+ notebook_dir = os.path.dirname(os.path.abspath(path))
+ with _carrier(path, front.header) as target:
+ edit(target, notebook_dir)
+ with open(target, encoding="utf-8") as f:
+ header = f.read()
+
+ data = front.data
+ if front.is_pyproject:
+ # Strip '# ' and the leading/trailing /// markers
+ header = "\n".join(
+ [line[2:] for line in header.strip().splitlines()[1:-1]]
+ )
+ data["pyproject"] = header
+ else:
+ data["header"] = header
+
+ header = yaml.marimo_compat_dump(data, sort_keys=False)
+ document = f"---\n{header.strip()}\n---{front.body}"
+ with open(path, "w", encoding="utf-8", newline="") as f:
+ f.write(document)
diff --git a/marimo/_environments/uv.py b/marimo/_environments/uv.py
new file mode 100644
index 0000000000..e1a92118d2
--- /dev/null
+++ b/marimo/_environments/uv.py
@@ -0,0 +1,175 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Single entry point for invoking the uv CLI.
+
+All marimo code that shells out to uv and captures its output goes through
+`uv()`. Failures surface as `UvCommandError` (or a refined subclass when the
+failure mode is recognized), so callers recover on typed errors instead of
+matching stderr text at each call site.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from typing import TYPE_CHECKING
+
+from marimo._environments.errors import EnvironmentManagerError
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping, Sequence
+
+UV_INSTALL_HINT = (
+ "Install uv from https://docs.astral.sh/uv/getting-started/installation/"
+)
+
+
+class UvError(EnvironmentManagerError):
+ """Base for all failures invoking uv."""
+
+
+class UvNotFoundError(UvError):
+ """uv is not installed or not on the PATH."""
+
+ def __init__(self, message: str | None = None) -> None:
+ super().__init__(message or f"uv must be installed. {UV_INSTALL_HINT}")
+
+
+class UvCommandError(UvError):
+ """A uv command exited with a nonzero status.
+
+ Refined subclasses identify failure modes marimo recovers from; catching
+ `UvCommandError` always remains a safe catch-all, so callers degrade
+ gracefully if uv's output changes and a refinement stops matching.
+ """
+
+ def __init__(
+ self,
+ command: Sequence[str],
+ returncode: int,
+ stdout: str,
+ stderr: str,
+ ) -> None:
+ self.command = list(command)
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+ super().__init__(
+ f"`{' '.join(self.command)}` exited with code {returncode}:\n"
+ + (stderr.strip() or stdout.strip())
+ )
+
+
+class UvMissingScriptMetadataError(UvCommandError):
+ """The target script has no PEP 723 inline metadata block."""
+
+
+class UvResolutionError(UvCommandError):
+ """uv could not resolve the requested set of dependencies."""
+
+
+class UvCacheWriteError(UvCommandError):
+ """uv could not write to its distribution cache (e.g. read-only FS)."""
+
+
+# Failure modes recognized in uv's stderr, most specific first. Each pattern
+# is matched case-insensitively and annotated with the uv version it was
+# validated against; tests exercise real uv so CI notices drift.
+_REFINEMENTS: list[tuple[tuple[str, ...], type[UvCommandError]]] = [
+ # uv 0.12.0
+ (
+ ("does not contain a pep 723 metadata tag",),
+ UvMissingScriptMetadataError,
+ ),
+ # uv 0.12.0
+ (("no solution found when resolving",), UvResolutionError),
+ # uv ~0.9.7
+ (
+ (
+ "failed to write to the distribution cache",
+ "operation not permitted",
+ ),
+ UvCacheWriteError,
+ ),
+]
+
+
+def _refine(completed: subprocess.CompletedProcess[str]) -> UvCommandError:
+ stderr_lowered = completed.stderr.lower()
+ error_type: type[UvCommandError] = UvCommandError
+ for patterns, refined in _REFINEMENTS:
+ if any(pattern in stderr_lowered for pattern in patterns):
+ error_type = refined
+ break
+ return error_type(
+ completed.args,
+ completed.returncode,
+ completed.stdout,
+ completed.stderr,
+ )
+
+
+def find_uv_bin() -> str:
+ return os.environ.get("UV", "uv")
+
+
+def is_uv_available() -> bool:
+ """Whether uv can be invoked.
+
+ An explicit `UV` environment variable is trusted as-is (uv sets it when it
+ spawns marimo, and it may point outside the PATH); otherwise the PATH is
+ checked for a `uv` binary.
+ """
+ uv_bin = find_uv_bin()
+ return uv_bin != "uv" or shutil.which("uv") is not None
+
+
+def require_uv_bin() -> str:
+ """Return the uv binary to invoke, raising `UvNotFoundError` if absent."""
+ if not is_uv_available():
+ raise UvNotFoundError()
+ return find_uv_bin()
+
+
+def uv(
+ args: Sequence[str],
+ *,
+ env: Mapping[str, str] | None = None,
+ cwd: str | None = None,
+ timeout: float | None = None,
+) -> subprocess.CompletedProcess[str]:
+ """Run a uv command and capture its output.
+
+ Raises `UvNotFoundError` if uv is not installed and `UvCommandError` (or
+ a refined subclass) on nonzero exit. `subprocess.TimeoutExpired`
+ propagates when `timeout` elapses. When `env` is given it replaces the
+ inherited environment. Not for interactive or streaming use: output is
+ captured, and stdin is closed so uv can never hang waiting for input.
+ """
+ command = [find_uv_bin(), *args]
+ try:
+ completed = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ stdin=subprocess.DEVNULL,
+ env=dict(env) if env is not None else None,
+ cwd=cwd,
+ timeout=timeout,
+ # A kernel interrupt must not propagate to uv; run it in its
+ # own session (ignored on Windows).
+ start_new_session=True,
+ )
+ except OSError as e:
+ # subprocess raises FileNotFoundError for a missing cwd on POSIX and
+ # NotADirectoryError on Windows. Preserve that error before refining a
+ # missing executable to UvNotFoundError.
+ if cwd is not None:
+ os.stat(cwd)
+ if isinstance(e, FileNotFoundError):
+ raise UvNotFoundError() from e
+ raise
+ if completed.returncode != 0:
+ raise _refine(completed)
+ return completed
diff --git a/marimo/_export/local_modules.py b/marimo/_export/local_modules.py
index 21c7ca8f17..e321d38ea2 100644
--- a/marimo/_export/local_modules.py
+++ b/marimo/_export/local_modules.py
@@ -28,8 +28,7 @@ from operator import attrgetter
from pathlib import Path
from typing import TYPE_CHECKING, Literal
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._utils.uv import find_uv_bin
+from marimo._environments.uv import UvNotFoundError, require_uv_bin
if TYPE_CHECKING:
from collections.abc import Collection, Mapping, Sequence
@@ -44,7 +43,7 @@ class LocalWheelError(Exception):
class UVNotFoundError(LocalWheelError):
- pass
+ """uv is required for html-wasm export but was not found."""
@dataclass(frozen=True)
@@ -244,13 +243,13 @@ def _ruff_graph_command(
def _uv_bin() -> str:
- uv_bin = find_uv_bin()
- if uv_bin == "uv" and not DependencyManager.which("uv"):
+ try:
+ return require_uv_bin()
+ except UvNotFoundError as e:
raise UVNotFoundError(
"uv must be installed to resolve local imports for "
"html-wasm export."
- )
- return uv_bin
+ ) from e
def _ruff_src_config(roots: Sequence[Path]) -> str:
diff --git a/marimo/_export/local_wheels.py b/marimo/_export/local_wheels.py
index a6ecb3a432..a5e3d80e3a 100644
--- a/marimo/_export/local_wheels.py
+++ b/marimo/_export/local_wheels.py
@@ -32,17 +32,13 @@ from typing import TYPE_CHECKING
from urllib.parse import quote, unquote, urlparse
from urllib.request import url2pathname
+from marimo._environments import script_metadata
from marimo._export.local_modules import (
LocalModule,
LocalWheelError,
module_python_files,
)
from marimo._utils.inline_script_metadata import PyProjectReader
-from marimo._utils.scripts import (
- REGEX,
- read_pyproject_from_script,
- write_pyproject_to_script,
-)
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
@@ -109,9 +105,7 @@ def resolve_metadata_wheel_dependencies(
"""
if not file_path.is_python():
return ()
- project = read_pyproject_from_script(
- file_path.path.read_text(encoding="utf-8")
- )
+ project = script_metadata.loads(file_path.path.read_text(encoding="utf-8"))
return (
()
if project is None
@@ -147,7 +141,7 @@ def with_wheel_dependencies(
if not wheel_dependencies:
return code
- project = read_pyproject_from_script(code) or {}
+ project = script_metadata.loads(code) or {}
dependencies = project.get("dependencies")
if not isinstance(dependencies, list):
dependencies = []
@@ -182,10 +176,10 @@ def with_wheel_dependencies(
project["dependencies"] = dependencies
_remove_uv_sources(project, set(replacements))
- metadata = write_pyproject_to_script(project)
- if read_pyproject_from_script(code) is None:
+ metadata = script_metadata.dumps(project)
+ if script_metadata.loads(code) is None:
return f"{metadata}\n\n{code}"
- return re.sub(REGEX, metadata, code, count=1)
+ return script_metadata.replace_block(code, metadata)
@contextmanager
diff --git a/marimo/_metadata/opengraph.py b/marimo/_metadata/opengraph.py
index 3ff3434db6..422e2c2572 100644
--- a/marimo/_metadata/opengraph.py
+++ b/marimo/_metadata/opengraph.py
@@ -15,8 +15,8 @@ from urllib.parse import urlparse
import msgspec
from marimo import _loggers
+from marimo._environments import script_metadata
from marimo._utils.paths import MARIMO_DIR_NAME, notebook_output_dir
-from marimo._utils.scripts import read_pyproject_from_script
LOGGER = _loggers.marimo_logger()
@@ -140,7 +140,7 @@ def read_opengraph_from_file(filepath: str) -> OpenGraphConfig | None:
"""Read OpenGraph metadata from a notebook's PEP 723 header."""
try:
script = Path(filepath).read_text(encoding="utf-8")
- project = read_pyproject_from_script(script) or {}
+ project = script_metadata.loads(script) or {}
except Exception:
# Parsing errors are treated as "no metadata" so that listing and thumbnail generation don't spam warnings on malformed headers.
return None
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 233b222df3..812bb26119 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -5,7 +5,6 @@ import json
import os
import subprocess
import sys
-import tempfile
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING
@@ -15,6 +14,8 @@ if TYPE_CHECKING:
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
+from marimo._environments import script_metadata
+from marimo._environments.uv import UvCommandError, find_uv_bin, uv
from marimo._runtime.packages._micropip_streaming import (
stream_transaction_install,
)
@@ -32,7 +33,6 @@ from marimo._runtime.packages.utils import (
split_packages,
)
from marimo._utils.platform import is_pyodide
-from marimo._utils.uv import find_uv_bin
from marimo._utils.uv_tree import DependencyTreeNode, parse_uv_tree
from marimo._utils.versions import (
extract_extras,
@@ -561,99 +561,19 @@ class UvPackageManager(PypiPackageManager):
if _is_direct_reference(im) or _is_installed(im)
]
- if filepath.endswith((".md", ".qmd")):
- # md and qmd require writing to a faux python file first.
- return self._process_md_changes(
- filepath, packages_to_add, packages_to_remove, upgrade=upgrade
- )
- return self._process_changes_for_script_metadata(
- filepath, packages_to_add, packages_to_remove, upgrade=upgrade
- )
-
- def _process_md_changes(
- self,
- filepath: str,
- packages_to_add: list[str],
- packages_to_remove: list[str],
- upgrade: bool,
- ) -> bool:
- from marimo._convert.markdown.to_ir import extract_frontmatter
- from marimo._utils import yaml
- from marimo._utils.inline_script_metadata import (
- get_headers_from_frontmatter,
- )
-
- # Get script metadata
- with open(filepath, encoding="utf-8") as f:
- frontmatter, body = extract_frontmatter(f.read())
- headers = get_headers_from_frontmatter(frontmatter)
- pyproject = bool(headers.get("pyproject", ""))
- header = (
- headers.get("pyproject", "")
- if pyproject
- else headers.get("header", "")
- )
- pyproject = pyproject or not bool(header)
-
- # Write out and process the header
- with tempfile.NamedTemporaryFile(
- mode="w", delete=False, suffix=".py", encoding="utf-8"
- ) as temp_file:
- temp_file.write(header)
- temp_file.flush()
- # Have UV modify it
- result = self._process_changes_for_script_metadata(
- temp_file.name,
- packages_to_add,
- packages_to_remove,
- upgrade=upgrade,
- )
- with open(temp_file.name, encoding="utf-8") as f:
- header = f.read()
- # Clean up the temporary file
- os.unlink(temp_file.name)
-
- # Write back the changes to the original file
- if pyproject:
- # Strip '# '
- # and leading/trailing ///
- header = "\n".join(
- [line[2:] for line in header.strip().splitlines()[1:-1]]
- )
- frontmatter["pyproject"] = header
- else:
- frontmatter["header"] = header
-
- header = yaml.marimo_compat_dump(
- frontmatter,
- sort_keys=False,
- )
- document = ["---", header.strip(), "---", body]
- with open(filepath, "w", encoding="utf-8") as f:
- f.write("\n".join(document))
-
- return result
-
- def _process_changes_for_script_metadata(
- self,
- filepath: str,
- packages_to_add: list[str],
- packages_to_remove: list[str],
- upgrade: bool,
- ) -> bool:
success = True
- if packages_to_add:
- cmd = [self._uv_bin, "--quiet", "add", "--script", filepath]
- if upgrade:
- cmd.append("--upgrade")
- cmd.extend(packages_to_add)
- success &= self._run_sync(cmd, log_callback=None)
- if packages_to_remove:
- success &= self._run_sync(
- [self._uv_bin, "--quiet", "remove", "--script", filepath]
- + packages_to_remove,
- log_callback=None,
+ try:
+ script_metadata.add_dependencies(
+ filepath, packages_to_add, upgrade=upgrade
)
+ except script_metadata.ScriptMetadataError as e:
+ LOGGER.warning("%s", e)
+ success = False
+ try:
+ script_metadata.remove_dependencies(filepath, packages_to_remove)
+ except script_metadata.ScriptMetadataError as e:
+ LOGGER.warning("%s", e)
+ success = False
return success
def _get_version_map(self) -> VersionMap:
@@ -772,18 +692,12 @@ class UvPackageManager(PypiPackageManager):
if filename is None and not self.is_in_uv_project:
return None
- tree_cmd = [self._uv_bin, "tree", "--no-dedupe"]
+ tree_cmd = ["tree", "--no-dedupe"]
if filename:
tree_cmd += ["--script", filename]
try:
- result = run_package_command(
- tree_cmd,
- capture_output=True,
- text=True,
- encoding="utf-8",
- check=True,
- )
+ result = uv(tree_cmd)
tree = parse_uv_tree(result.stdout)
# If in a uv project and the only top-level item is the project itself,
@@ -793,7 +707,7 @@ class UvPackageManager(PypiPackageManager):
return tree
- except subprocess.CalledProcessError:
+ except UvCommandError:
# Only log error if the script has dependency metadata
if filename and self._has_script_metadata(filename):
LOGGER.error(f"Failed to get dependency tree for {filename}")
diff --git a/marimo/_session/_venv.py b/marimo/_session/_venv.py
index 6a00b8641c..2d3418dd20 100644
--- a/marimo/_session/_venv.py
+++ b/marimo/_session/_venv.py
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING
from marimo import _loggers
from marimo._cli.print import echo
-from marimo._utils.uv import find_uv_bin
+from marimo._environments.uv import UvCommandError, uv
from marimo._version import __version__
if TYPE_CHECKING:
@@ -207,18 +207,13 @@ def install_marimo_into_venv(venv_python: str) -> None:
Args:
venv_python: Path to the venv's Python interpreter.
"""
- uv_bin = find_uv_bin()
-
packages = [f"marimo=={__version__}"] + get_ipc_kernel_deps()
echo("Installing marimo into configured venv...", err=True)
- result = subprocess.run(
- [uv_bin, "pip", "install", "--python", venv_python] + packages,
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
+ try:
+ uv(["pip", "install", "--python", venv_python] + packages)
+ except UvCommandError as e:
LOGGER.warning(
- f"Failed to install marimo into configured venv: {result.stderr}"
+ f"Failed to install marimo into configured venv: {e.stderr}"
)
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index 0620756a93..e6be930e72 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -11,6 +11,9 @@ from marimo._ast import load
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import overloads_from_env
from marimo._ast.cell import CellConfig
+from marimo._environments.script_metadata import (
+ with_python_version_requirement,
+)
from marimo._messaging.notebook.changes import (
Transaction,
)
@@ -32,7 +35,6 @@ from marimo._utils.generated_with import (
)
from marimo._utils.http import HTTPException, HTTPStatus
from marimo._utils.marimo_path import MarimoPath
-from marimo._utils.scripts import with_python_version_requirement
LOGGER = _loggers.marimo_logger()
@@ -232,11 +234,9 @@ class AppFileManager:
from marimo._config.settings import GLOBAL_SETTINGS
if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:
- from marimo._utils.scripts import (
- write_pyproject_to_script,
- )
+ from marimo._environments import script_metadata
- header = write_pyproject_to_script(
+ header = script_metadata.dumps(
with_python_version_requirement(
{
"dependencies": ["marimo"],
diff --git a/marimo/_utils/health.py b/marimo/_utils/health.py
index bc981c218d..ac61af23a4 100644
--- a/marimo/_utils/health.py
+++ b/marimo/_utils/health.py
@@ -72,26 +72,18 @@ def get_node_version() -> str | None:
def get_uv_version() -> str | None:
- from marimo._utils.uv import find_uv_bin
+ from marimo._environments.uv import UvError, uv
try:
- process = subprocess.Popen(
- [find_uv_bin(), "--version"],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- )
- stdout, stderr = communicate_with_timeout(process)
- if stderr:
- return None
- if stdout and (stripped := stdout.strip()):
+ result = uv(["--version"], timeout=TIMEOUT)
+ if stripped := result.stdout.strip():
# `uv --version` outputs "uv X.Y.Z (hash date)"
return stripped.removeprefix("uv ")
else:
return None
- except OSError:
- # Missing binary, or a platform without subprocess (e.g. Emscripten,
- # which raises OSError "Function not implemented").
+ except (UvError, subprocess.TimeoutExpired, OSError):
+ # OSError: platform without subprocess (e.g. Emscripten, which
+ # raises "Function not implemented").
return None
diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.py
index 9afbe3c1dc..f2bd6a81d1 100644
--- a/marimo/_utils/inline_script_metadata.py
+++ b/marimo/_utils/inline_script_metadata.py
@@ -10,9 +10,9 @@ from typing import TYPE_CHECKING, Any, cast
from marimo import _loggers
from marimo._cli.files.file_path import FileContentReader
from marimo._cli.print import echo
+from marimo._environments import script_metadata
from marimo._utils.code import hash_code
from marimo._utils.paths import normalize_path
-from marimo._utils.scripts import read_pyproject_from_script
if TYPE_CHECKING:
from marimo._utils.marimo_path import MarimoPath
@@ -43,7 +43,7 @@ class PyProjectReader:
@staticmethod
def from_script(script: str) -> PyProjectReader:
return PyProjectReader(
- project=read_pyproject_from_script(script) or {},
+ project=script_metadata.loads(script) or {},
config_path=None,
name=None,
)
@@ -101,7 +101,7 @@ def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:
try:
contents, _ = FileContentReader().read_file(name)
if name.endswith(".py"):
- return read_pyproject_from_script(contents)
+ return script_metadata.loads(contents)
if not (name.endswith((".md", ".qmd"))):
raise ValueError(
@@ -119,7 +119,7 @@ def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:
"Both header and pyproject provide dependencies. "
"Preferring pyproject."
)
- return read_pyproject_from_script(header)
+ return script_metadata.loads(header)
except FileNotFoundError:
return None
except Exception:
@@ -281,13 +281,7 @@ def with_pinned_dependencies(
rewritten. If the script has no PEP 723 block, `code` is returned
unchanged.
"""
- from marimo._utils.scripts import (
- REGEX,
- read_pyproject_from_script,
- write_pyproject_to_script,
- )
-
- project = read_pyproject_from_script(code)
+ project = script_metadata.loads(code)
if project is None:
return code
@@ -309,8 +303,7 @@ def with_pinned_dependencies(
marimo_tool["export"] = export_section
export_section["lock_kind"] = lock_kind
- new_block = write_pyproject_to_script(project)
- return re.sub(REGEX, new_block, code, count=1)
+ return script_metadata.replace_block(code, script_metadata.dumps(project))
def pin_pep723_dependencies_for_wasm(code: str, path: MarimoPath) -> str:
@@ -411,15 +404,13 @@ def get_headers_from_markdown(contents: str) -> dict[str, str]:
def get_headers_from_frontmatter(
frontmatter: dict[str, Any],
) -> dict[str, str]:
- from marimo._utils.scripts import wrap_script_metadata
-
headers = {"pyproject": "", "header": ""}
pyproject = frontmatter.get("pyproject", "")
if pyproject:
if not pyproject.startswith("#"):
# Wrap raw TOML content in PEP 723 format
- pyproject = wrap_script_metadata(pyproject)
+ pyproject = script_metadata.wrap_block(pyproject)
headers["pyproject"] = pyproject
headers["header"] = frontmatter.get("header", "")
return headers
diff --git a/marimo/_utils/scripts.py b/marimo/_utils/scripts.py
index a511730b8e..579e75fefe 100644
--- a/marimo/_utils/scripts.py
+++ b/marimo/_utils/scripts.py
@@ -1,103 +1,19 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import platform
-import re
-from typing import Any
-
-from marimo._utils.toml import toml_reader
-
-REGEX = (
- r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$"
+# Moved to marimo._environments.script_metadata; re-exported for compatibility.
+from marimo._environments.script_metadata import (
+ REGEX,
+ dumps as write_pyproject_to_script,
+ loads as read_pyproject_from_script,
+ with_python_version_requirement,
+ wrap_block as wrap_script_metadata,
)
-
-def with_python_version_requirement(project: dict[str, Any]) -> dict[str, Any]:
- # TODO(akshayka): consider locking the Python version for greater
- # reproducibility, instead of returning a lowerbound
- project = project.copy()
- version_tuple = platform.python_version_tuple()
- project["requires-python"] = f">={version_tuple[0]}.{version_tuple[1]}"
- return project
-
-
-def read_pyproject_from_script(script: str) -> dict[str, Any] | None:
- """
- Read the pyproject.toml file from the script.
-
- Adapted from https://peps.python.org/pep-0723/#reference-implementation
- """
- name = "script"
- matches = list(
- filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
- )
- if len(matches) > 1:
- raise ValueError(f"Multiple {name} blocks found")
- elif len(matches) == 1:
- content = "".join(
- line[2:] if line.startswith("# ") else line[1:]
- for line in matches[0].group("content").splitlines(keepends=True)
- )
-
- pyproject = toml_reader.reads(content)
- return pyproject
- else:
- return None
-
-
-def write_pyproject_to_script(project: dict[str, Any]) -> str:
- """
- Convert a project dict to PEP 723 inline script metadata format.
-
- Adapted from https://peps.python.org/pep-0723/#reference-implementation
-
- Args:
- project: Dictionary containing project metadata (dependencies,
- requires-python, etc.)
-
- Returns:
- PEP 723 formatted string with "# /// script" markers
- """
- from marimo._dependencies.dependencies import DependencyManager
-
- # Convert project dict to TOML
- if DependencyManager.tomlkit.has():
- import tomlkit
-
- toml_content = tomlkit.dumps(project)
- else:
- # Fallback to simple formatting if tomlkit not available
- # This should rarely happen in practice
- import json
-
- lines = []
- if "dependencies" in project:
- lines.append(
- f"dependencies = {json.dumps(project['dependencies'])}"
- )
- if "requires-python" in project:
- lines.append(
- f"requires-python = {json.dumps(project['requires-python'])}"
- )
- toml_content = "\n".join(lines) + "\n" if lines else ""
-
- # Wrap in PEP 723 comment format
- return wrap_script_metadata(toml_content)
-
-
-def wrap_script_metadata(toml_content: str) -> str:
- """
- Wrap TOML content in PEP 723 inline script metadata markers.
-
- Args:
- toml_content: Raw TOML content string
-
- Returns:
- PEP 723 formatted string with "# /// script" markers
- """
- result_lines = ["# /// script"]
- for line in toml_content.rstrip().split("\n"):
- result_lines.append(f"# {line}")
- result_lines.append("# ///")
-
- return "\n".join(result_lines)
+__all__ = [
+ "REGEX",
+ "read_pyproject_from_script",
+ "with_python_version_requirement",
+ "wrap_script_metadata",
+ "write_pyproject_to_script",
+]
diff --git a/marimo/_utils/uv.py b/marimo/_utils/uv.py
index b30adc963f..c2bacba2da 100644
--- a/marimo/_utils/uv.py
+++ b/marimo/_utils/uv.py
@@ -1,9 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import os
+# Moved to marimo._environments.uv; re-exported for compatibility.
+from marimo._environments.uv import find_uv_bin
-
-# Could be replaced with `find_uv_bin` from uv Python package in the future
-def find_uv_bin() -> str:
- return os.environ.get("UV", "uv")
+__all__ = ["find_uv_bin"]
diff --git a/pyproject.toml b/pyproject.toml
index 6b28de4118..b799341c3e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -549,6 +549,7 @@ markers = [
"unit: marks tests as unit tests",
"flaky: marks tests that are known to be flaky",
"requires(dep1, dep2, ...): requires one or more dependencies to be installed",
+ "network: requires internet access to package indexes (deselect with '-m \"not network\"')",
]
[tool.coverage.run]
diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.py
index 2adea29017..d36b3c3ec0 100644
--- a/tests/_cli/test_sandbox.py
+++ b/tests/_cli/test_sandbox.py
@@ -1,21 +1,21 @@
from __future__ import annotations
import os
+import subprocess
from pathlib import Path
-from typing import Any
from unittest.mock import patch
import pytest
from marimo._cli.sandbox import (
SandboxMode,
- _ensure_marimo_in_script_metadata,
- _ensure_python_version_in_script_metadata,
_normalize_sandbox_dependencies,
+ _uv_export_script_requirements_txt,
build_sandbox_venv,
cleanup_sandbox_dir,
construct_uv_command,
resolve_sandbox_mode,
+ run_in_sandbox,
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._utils.inline_script_metadata import PyProjectReader
@@ -23,8 +23,30 @@ from marimo._utils.inline_script_metadata import PyProjectReader
HAS_UV = DependencyManager.which("uv")
-@patch("marimo._cli.sandbox.is_editable", return_value=False)
-def test_normalize_marimo_dependencies(mock_is_editable: Any):
+def test_dependency_export_uses_notebook_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ notebook = tmp_path / "notebooks" / "nb.py"
+ notebook.parent.mkdir()
+ monkeypatch.chdir(tmp_path)
+
+ def export(
+ args: list[str], *, cwd: str
+ ) -> subprocess.CompletedProcess[str]:
+ target = args[args.index("--script") + 1]
+ assert target == str(notebook)
+ assert cwd == str(notebook.parent)
+ return subprocess.CompletedProcess(args, 0, stdout="-e ../lib")
+
+ monkeypatch.setattr("marimo._cli.sandbox.uv", export)
+
+ assert _uv_export_script_requirements_txt("notebooks/nb.py") == [
+ f"-e {tmp_path / 'lib'}"
+ ]
+
+
+def test_normalize_marimo_dependencies(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr("marimo._cli.sandbox.is_editable", lambda _: False)
# Test adding marimo when not present
assert _normalize_sandbox_dependencies(
["numpy"], "1.0.0", additional_features=[]
@@ -32,7 +54,6 @@ def test_normalize_marimo_dependencies(mock_is_editable: Any):
"numpy",
"marimo==1.0.0",
]
- assert mock_is_editable.call_count == 1
# Test preferring bracketed version
assert _normalize_sandbox_dependencies(
@@ -44,11 +65,6 @@ def test_normalize_marimo_dependencies(mock_is_editable: Any):
["marimo[extras]>=0.1.0", "numpy"], "1.0.0", additional_features=[]
) == ["numpy", "marimo[extras]>=0.1.0"]
- # Test adding version when none exists
- assert _normalize_sandbox_dependencies(
- ["marimo[extras]", "numpy"], "1.0.0", additional_features=[]
- ) == ["numpy", "marimo[extras]==1.0.0"]
-
# Test keeping only one marimo dependency
assert _normalize_sandbox_dependencies(
["marimo>=0.1.0", "marimo[extras]>=0.2.0", "numpy"],
@@ -99,10 +115,10 @@ def test_normalize_marimo_dependencies(mock_is_editable: Any):
) == ["numpy", f"marimo{spec}"]
-@patch("marimo._cli.sandbox.is_editable", return_value=True)
def test_normalize_marimo_dependencies_editable(
- mock_is_editable: Any,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
+ monkeypatch.setattr("marimo._cli.sandbox.is_editable", lambda _: True)
deps = _normalize_sandbox_dependencies(
["numpy"], "1.0.0", additional_features=[]
)
@@ -118,7 +134,6 @@ def test_normalize_marimo_dependencies_editable(
assert deps[0] == "numpy"
assert deps[1].startswith("-e")
assert deps[1].endswith("[lsp,recommended]")
- assert mock_is_editable.call_count == 2
deps = _normalize_sandbox_dependencies(
["numpy", "marimo"], "1.0.0", additional_features=[]
@@ -284,6 +299,37 @@ def test_construct_uv_cmd_empty_dependencies() -> None:
assert "--no-project" in uv_cmd
+def test_run_in_sandbox_reports_wrapped_metadata_timeout() -> None:
+ from marimo._environments import script_metadata
+
+ timeout = subprocess.TimeoutExpired(["uv", "add"], timeout=30)
+ metadata_error = script_metadata.ScriptMetadataError("update failed")
+ metadata_error.__cause__ = timeout
+
+ with (
+ patch("marimo._cli.sandbox.require_uv_bin"),
+ patch(
+ "marimo._cli.sandbox.script_metadata.ensure_marimo",
+ side_effect=metadata_error,
+ ),
+ patch("marimo._cli.sandbox.script_metadata.ensure_requires_python"),
+ patch(
+ "marimo._cli.sandbox.construct_uv_command",
+ return_value=["uv", "run"],
+ ),
+ patch("marimo._cli.sandbox.subprocess.Popen") as popen,
+ patch("marimo._cli.sandbox.signal.signal"),
+ patch("marimo._cli.sandbox.LOGGER.warning") as warning,
+ ):
+ popen.return_value.wait.return_value = 0
+
+ assert run_in_sandbox(["edit", "notebook.py"], name="notebook.py") == 0
+
+ warning.assert_called_once_with(
+ "Timed out adding marimo to script metadata"
+ )
+
+
def test_construct_uv_cmd_with_complex_args() -> None:
# Test complex command arguments are preserved
args = [
@@ -447,8 +493,8 @@ import marimo
# Mock the prompt to return True (simulating user typing 'y')
with patch("marimo._cli.sandbox.click.confirm", return_value=True):
with patch(
- "marimo._cli.sandbox.DependencyManager.which",
- return_value="/usr/bin/uv",
+ "marimo._cli.sandbox.is_uv_available",
+ return_value=True,
):
with patch(
"marimo._cli.sandbox.sys.stdin.isatty", return_value=True
@@ -544,198 +590,6 @@ import marimo
assert uv_cmd[python_idx + 1] == platform.python_version()
[email protected](not HAS_UV, reason="uv required")
-def test_ensure_marimo_in_script_metadata_adds_marimo(tmp_path: Path) -> None:
- """Test that marimo is added to script metadata when missing."""
- script_path = tmp_path / "test.py"
- script_path.write_text(
- """# /// script
-# dependencies = ["numpy"]
-# ///
-import marimo
-"""
- )
-
- _ensure_marimo_in_script_metadata(str(script_path))
-
- content = script_path.read_text()
- assert "marimo" in content
- assert "numpy" in content
-
-
-def test_ensure_marimo_in_script_metadata_noop_when_present(
- tmp_path: Path,
-) -> None:
- """Test that file is unchanged when marimo and requires-python already present."""
- original = """# /// script
-# requires-python = ">=3.10"
-# dependencies = ["marimo", "numpy"]
-# ///
-import marimo
-"""
- script_path = tmp_path / "test.py"
- script_path.write_text(original)
-
- _ensure_marimo_in_script_metadata(str(script_path))
- _ensure_python_version_in_script_metadata(str(script_path))
-
- assert script_path.read_text() == original
-
-
[email protected](not HAS_UV, reason="uv required")
-def test_ensure_marimo_in_script_metadata_adds_when_no_metadata(
- tmp_path: Path,
-) -> None:
- """Test that script metadata is added when it doesn't exist."""
- original = """import marimo
-app = marimo.App()
-"""
- script_path = tmp_path / "test.py"
- script_path.write_text(original)
-
- _ensure_marimo_in_script_metadata(str(script_path))
- _ensure_python_version_in_script_metadata(str(script_path))
-
- content = script_path.read_text()
- assert "# /// script" in content
- assert "marimo" in content
- assert "requires-python" in content
-
-
[email protected](not HAS_UV, reason="uv required")
-def test_ensure_marimo_in_script_metadata_adds_python_version(
- tmp_path: Path,
-) -> None:
- """Test that requires-python is added to script metadata."""
- import platform
-
- script_path = tmp_path / "test.py"
- script_path.write_text("""# /// script
-# dependencies = ["numpy"]
-# ///
-import marimo
-""")
-
- _ensure_marimo_in_script_metadata(str(script_path))
- _ensure_python_version_in_script_metadata(str(script_path))
-
- content = script_path.read_text()
- assert "requires-python" in content
- major, minor = platform.python_version_tuple()[:2]
- assert f">={major}.{minor}" in content
-
-
-def test_ensure_python_version_in_script_metadata(tmp_path: Path) -> None:
- """Test that requires-python is added when missing."""
- import platform
-
- script_path = tmp_path / "test.py"
- script_path.write_text("""# /// script
-# dependencies = ["marimo", "numpy"]
-# ///
-import marimo
-""")
-
- _ensure_python_version_in_script_metadata(str(script_path))
-
- content = script_path.read_text()
- assert "requires-python" in content
- major, minor = platform.python_version_tuple()[:2]
- assert f">={major}.{minor}" in content
-
-
-def test_ensure_python_version_preserves_formatting(tmp_path: Path) -> None:
- """Test that adding requires-python preserves formatting and only modifies the header.
-
- Regression test for #8054. Also verifies that similar patterns in file (e.g., docstrings) are not affected.
- """
- import platform
-
- # Multi-line deps list that would be reformatted by re-serialization,
- # plus a docstring with similar-looking text that should not be modified
- original = '''# /// script
-# dependencies = [
-# "polars",
-# "marimo>=0.8.0",
-# ]
-# ///
-import marimo
-
-app = marimo.App()
-
-def __():
- """
- Example of PEP 723 metadata:
-
- # /// script
- # requires-python = ">=3.11"
- # ///
- """
- return ()
-'''
- script_path = tmp_path / "test.py"
- script_path.write_text(original)
-
- _ensure_python_version_in_script_metadata(str(script_path))
-
- content = script_path.read_text()
- major, minor = platform.python_version_tuple()[:2]
- expected = f'''# /// script
-# requires-python = ">={major}.{minor}"
-# dependencies = [
-# "polars",
-# "marimo>=0.8.0",
-# ]
-# ///
-import marimo
-
-app = marimo.App()
-
-def __():
- """
- Example of PEP 723 metadata:
-
- # /// script
- # requires-python = ">=3.11"
- # ///
- """
- return ()
-'''
- assert content == expected
-
-
-def test_ensure_python_version_in_script_metadata_noop_when_present(
- tmp_path: Path,
-) -> None:
- """Test that file is unchanged when requires-python already present."""
- original = """# /// script
-# requires-python = ">=3.10"
-# dependencies = ["marimo", "numpy"]
-# ///
-import marimo
-"""
- script_path = tmp_path / "test.py"
- script_path.write_text(original)
-
- _ensure_python_version_in_script_metadata(str(script_path))
-
- assert script_path.read_text() == original
-
-
-def test_ensure_marimo_in_script_metadata_noop_when_file_missing(
- tmp_path: Path,
-) -> None:
- """Test that file is not created when it doesn't exist."""
- script_path = tmp_path / "nonexistent.py"
-
- _ensure_marimo_in_script_metadata(str(script_path))
-
- # File should still not exist
- assert not script_path.exists()
-
-
def test_get_sandbox_requirements_adds_additional_deps(tmp_path: Path) -> None:
"""Test that additional deps are added when not present."""
from marimo._cli.sandbox import get_sandbox_requirements
diff --git a/tests/_environments/conftest.py b/tests/_environments/conftest.py
new file mode 100644
index 0000000000..bd615ae0d7
--- /dev/null
+++ b/tests/_environments/conftest.py
@@ -0,0 +1,20 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Shared fixtures for tests that invoke a real environment manager."""
+
+from __future__ import annotations
+
+import pytest
+
+# Ambient configuration that changes which versions a manager resolves.
+# These tests assert marimo's own behavior, so a shell or CI job that sets
+# one of these (the minimal-dependency job sets `UV_RESOLUTION`) must not
+# change what they resolve.
+RESOLUTION_VARIABLES = ("UV_RESOLUTION", "UV_PRERELEASE")
+
+
[email protected](autouse=True)
+def ignore_ambient_resolution_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for variable in RESOLUTION_VARIABLES:
+ monkeypatch.delenv(variable, raising=False)
diff --git a/tests/_environments/test_script_metadata.py b/tests/_environments/test_script_metadata.py
new file mode 100644
index 0000000000..0a074053e0
--- /dev/null
+++ b/tests/_environments/test_script_metadata.py
@@ -0,0 +1,351 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import platform
+import subprocess
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._environments import script_metadata
+from marimo._environments.uv import UvNotFoundError, is_uv_available
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+HAS_UV = is_uv_available()
+
+BLOCK_WITH_TOOL_TABLES = """\
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["numpy"]
+#
+# [tool.uv.sources]
+# numpy = { path = "../numpy" }
+#
+# [tool.marimo.export]
+# lock_kind = "resolved"
+# ///
+"""
+
+
+def test_loads_returns_none_without_block() -> None:
+ assert script_metadata.loads("print('hi')\n") is None
+
+
[email protected]("separator", ["", "\n"])
+def test_loads_rejects_multiple_blocks(separator: str) -> None:
+ block = "# /// script\n# dependencies = []\n# ///\n"
+ with pytest.raises(ValueError, match="Multiple"):
+ script_metadata.loads(block + separator + block)
+
+
+def test_loads_ignores_other_block_types() -> None:
+ script = (
+ "# /// script\n# dependencies = []\n# ///\n"
+ '# /// other\n# value = "other metadata"\n# ///\n'
+ )
+ assert script_metadata.loads(script) == {"dependencies": []}
+
+
+def test_dumps_round_trips_tool_tables() -> None:
+ project = script_metadata.loads(BLOCK_WITH_TOOL_TABLES)
+ assert project is not None
+ assert project["tool"]["uv"]["sources"]["numpy"] == {"path": "../numpy"}
+ assert script_metadata.loads(script_metadata.dumps(project)) == project
+
+
+def test_replace_block_keeps_backslashes_literal() -> None:
+ code = BLOCK_WITH_TOOL_TABLES + "\nimport marimo\n"
+ block = (
+ '# /// script\n# dependencies = ["pkg @ file://C:\\\\wheels"]\n# ///'
+ )
+ replaced = script_metadata.replace_block(code, block)
+ assert "C:\\\\wheels" in replaced
+ assert "import marimo" in replaced
+
+
+def test_wrap_block() -> None:
+ assert script_metadata.wrap_block('dependencies = ["numpy"]') == (
+ '# /// script\n# dependencies = ["numpy"]\n# ///'
+ )
+
+
+ "error",
+ [
+ UvNotFoundError(),
+ subprocess.TimeoutExpired(["uv", "add"], timeout=60),
+ FileNotFoundError(
+ 2, "No such file or directory", "/missing/notebooks"
+ ),
+ ],
+)
+def test_edit_normalizes_invocation_failures(
+ monkeypatch: pytest.MonkeyPatch,
+ error: Exception,
+) -> None:
+ def fail(*args: object, **kwargs: object) -> None:
+ del args, kwargs
+ raise error
+
+ monkeypatch.setattr(script_metadata, "uv", fail)
+
+ with pytest.raises(script_metadata.ScriptMetadataError) as exc_info:
+ script_metadata.add_dependencies("notebook.py", ["idna"])
+
+ assert exc_info.value.__cause__ is error
+ assert str(error) in str(exc_info.value)
+
+
+def test_failed_frontmatter_edit_preserves_notebook_and_removes_carrier(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ original = """---
+title: Test
+pyproject: |
+ dependencies = []
+---
+
+# Hello
+"""
+ notebook = tmp_path / "notebook.md"
+ notebook.write_text(original)
+ error = UvNotFoundError("uv disappeared")
+
+ def fail(*args: object, **kwargs: object) -> None:
+ del args, kwargs
+ raise error
+
+ monkeypatch.setattr(script_metadata, "uv", fail)
+
+ with pytest.raises(script_metadata.ScriptMetadataError) as exc_info:
+ script_metadata.add_dependencies(str(notebook), ["idna"])
+
+ assert exc_info.value.__cause__ is error
+ assert str(error) in str(exc_info.value)
+ assert notebook.read_text() == original
+ assert [path.name for path in tmp_path.iterdir()] == ["notebook.md"]
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_ensure_marimo_adds_marimo(tmp_path: Path) -> None:
+ script_path = tmp_path / "test.py"
+ script_path.write_text(
+ """# /// script
+# dependencies = ["numpy"]
+# ///
+import marimo
+"""
+ )
+
+ script_metadata.ensure_marimo(str(script_path))
+
+ content = script_path.read_text()
+ assert "marimo" in content
+ assert "numpy" in content
+
+
+def test_ensure_noop_when_present(tmp_path: Path) -> None:
+ original = """# /// script
+# requires-python = ">=3.10"
+# dependencies = ["marimo", "numpy"]
+# ///
+import marimo
+"""
+ script_path = tmp_path / "test.py"
+ script_path.write_text(original)
+
+ script_metadata.ensure_marimo(str(script_path))
+ script_metadata.ensure_requires_python(str(script_path))
+
+ assert script_path.read_text() == original
+
+
+def test_ensure_marimo_noop_for_missing_or_empty_file(
+ tmp_path: Path,
+) -> None:
+ script_metadata.ensure_marimo(str(tmp_path / "missing.py"))
+ empty = tmp_path / "empty.py"
+ empty.write_text("")
+ script_metadata.ensure_marimo(str(empty))
+ assert empty.read_text() == ""
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_ensure_adds_when_no_metadata(tmp_path: Path) -> None:
+ script_path = tmp_path / "test.py"
+ script_path.write_text("import marimo\napp = marimo.App()\n")
+
+ script_metadata.ensure_marimo(str(script_path))
+ script_metadata.ensure_requires_python(str(script_path))
+
+ content = script_path.read_text()
+ assert "# /// script" in content
+ assert "marimo" in content
+ assert "requires-python" in content
+
+
+def test_ensure_requires_python_only_touches_the_header(
+ tmp_path: Path,
+) -> None:
+ """Regression test for #8054.
+
+ The multi-line deps list must not be reformatted, and similar-looking
+ text elsewhere in the file (e.g. docstrings) must not be modified.
+ """
+ original = '''# /// script
+# dependencies = [
+# "polars",
+# "marimo>=0.8.0",
+# ]
+# ///
+import marimo
+
+app = marimo.App()
+
+def __():
+ """
+ Example of PEP 723 metadata:
+
+ # /// script
+ # requires-python = ">=3.11"
+ # ///
+ """
+ return ()
+'''
+ script_path = tmp_path / "test.py"
+ script_path.write_text(original)
+
+ script_metadata.ensure_requires_python(str(script_path))
+
+ major, minor = platform.python_version_tuple()[:2]
+ expected = original.replace(
+ "# /// script\n",
+ f'# /// script\n# requires-python = ">={major}.{minor}"\n',
+ 1,
+ )
+ assert script_path.read_text() == expected
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_add_and_remove_dependencies(tmp_path: Path) -> None:
+ script_path = tmp_path / "test.py"
+ script_path.write_text(
+ """# /// script
+# dependencies = []
+# ///
+"""
+ )
+
+ script_metadata.add_dependencies(str(script_path), ["idna"])
+ project = script_metadata.loads(script_path.read_text())
+ assert project is not None
+ assert any(dep.startswith("idna") for dep in project["dependencies"])
+
+ script_metadata.remove_dependencies(str(script_path), ["idna"])
+ project = script_metadata.loads(script_path.read_text())
+ assert project is not None
+ assert project["dependencies"] == []
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_frontmatter_edit_resolves_relative_sources(tmp_path: Path) -> None:
+ """Relative `[tool.uv.sources]` paths resolve against the notebook's
+ directory: the carrier lives next to the notebook, so uv anchors them
+ natively and the round-trip leaves them untouched."""
+ lib = tmp_path / "lib"
+ lib.mkdir()
+ (lib / "pyproject.toml").write_text(
+ '[project]\nname = "mylib"\nversion = "0.1.0"\n'
+ )
+ notebook = tmp_path / "notebook.md"
+ notebook.write_text(
+ """---
+pyproject: |
+ requires-python = ">=3.11"
+ dependencies = []
+
+ [tool.uv.sources]
+ mylib = { path = "./lib" }
+---
+
+# Hello
+"""
+ )
+
+ script_metadata.add_dependencies(str(notebook), ["mylib"])
+
+ content = notebook.read_text()
+ assert "mylib" in content
+ assert 'path = "./lib"' in content
+ # The carrier is deleted when the edit finishes.
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["lib", "notebook.md"]
+
+
[email protected](not HAS_UV, reason="uv required")
+ ("suffix", "key", "separator"),
+ [
+ (".md", "pyproject", "\n"),
+ (".md", "header", "\n\n\n"),
+ (".qmd", "pyproject", "\r\n\r\n"),
+ (".qmd", "header", " \n\n"),
+ ],
+)
+def test_frontmatter_edit_preserves_body(
+ tmp_path: Path, suffix: str, key: str, separator: str
+) -> None:
+ from marimo._convert.markdown.to_ir import extract_frontmatter
+ from marimo._utils import yaml
+
+ notebook = tmp_path / f"notebook{suffix}"
+ metadata = 'dependencies = ["numpy"]'
+ if key == "header":
+ metadata = script_metadata.wrap_block(metadata)
+ header = yaml.marimo_compat_dump(
+ {"title": "Test", key: metadata}, sort_keys=False
+ )
+ body = separator + " indented code\r\n\r\n# Hello\n\n"
+ notebook.write_bytes(f"---\n{header}---{body}".encode())
+
+ script_metadata.remove_dependencies(str(notebook), ["numpy"])
+
+ content = notebook.read_bytes().decode()
+ assert content.endswith("---" + body)
+ frontmatter, _ = extract_frontmatter(content)
+ assert frontmatter["title"] == "Test"
+ updated = frontmatter[key]
+ if key == "pyproject":
+ updated = script_metadata.wrap_block(updated)
+ project = script_metadata.loads(updated)
+ assert project is not None
+ assert project["dependencies"] == []
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_edits_accept_relative_notebook_paths(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """uv runs from the notebook's directory, so a relative target with a
+ directory component must not be re-resolved against that directory."""
+ notebooks = tmp_path / "notebooks"
+ notebooks.mkdir()
+ (notebooks / "nb.py").write_text(
+ """# /// script
+# dependencies = ["numpy"]
+# ///
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.chdir(tmp_path)
+
+ script_metadata.remove_dependencies("notebooks/nb.py", ["numpy"])
+
+ project = script_metadata.loads((notebooks / "nb.py").read_text())
+ assert project is not None
+ assert project["dependencies"] == []
diff --git a/tests/_environments/test_uv.py b/tests/_environments/test_uv.py
new file mode 100644
index 0000000000..fa5e7edc7f
--- /dev/null
+++ b/tests/_environments/test_uv.py
@@ -0,0 +1,108 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._environments.uv import (
+ UvCommandError,
+ UvMissingScriptMetadataError,
+ UvNotFoundError,
+ UvResolutionError,
+ find_uv_bin,
+ is_uv_available,
+ require_uv_bin,
+ uv,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+HAS_UV = is_uv_available()
+
+
+def test_find_uv_bin_respects_env_override(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("UV", "/opt/somewhere/uv")
+ assert find_uv_bin() == "/opt/somewhere/uv"
+ monkeypatch.delenv("UV")
+ assert find_uv_bin() == "uv"
+
+
+def test_require_uv_bin_trusts_env_override(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # An explicit UV env var is trusted without a PATH lookup: uv sets it
+ # when it spawns marimo, and it may point outside the PATH.
+ monkeypatch.setenv("UV", "/explicit/path/to/uv")
+ assert is_uv_available()
+ assert require_uv_bin() == "/explicit/path/to/uv"
+
+
+def test_require_uv_bin_raises_when_absent(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("UV", raising=False)
+ monkeypatch.setenv("PATH", "")
+ assert not is_uv_available()
+ with pytest.raises(UvNotFoundError):
+ require_uv_bin()
+
+
+def test_uv_raises_not_found_for_missing_binary(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("UV", str(tmp_path / "uv-does-not-exist"))
+ with pytest.raises(UvNotFoundError):
+ uv(["--version"], cwd=str(tmp_path))
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_uv_preserves_missing_working_directory(tmp_path: Path) -> None:
+ missing = tmp_path / "missing"
+ with pytest.raises(FileNotFoundError) as exc_info:
+ uv(["--version"], cwd=str(missing))
+ assert exc_info.value.filename == str(missing)
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_uv_captures_stdout() -> None:
+ result = uv(["--version"])
+ assert result.returncode == 0
+ assert result.stdout.startswith("uv ")
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_nonzero_exit_raises_with_stderr() -> None:
+ with pytest.raises(UvCommandError) as excinfo:
+ uv(["definitely-not-a-subcommand"])
+ error = excinfo.value
+ assert error.stderr
+ # The stringified error carries the command for logs.
+ assert "definitely-not-a-subcommand" in str(error)
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_missing_script_metadata_is_refined(tmp_path: Path) -> None:
+ script = tmp_path / "plain.py"
+ script.write_text("print('hi')\n", encoding="utf-8")
+ with pytest.raises(UvMissingScriptMetadataError):
+ uv(["export", "--script", str(script)])
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_resolution_failure_is_refined(tmp_path: Path) -> None:
+ script = tmp_path / "unsatisfiable.py"
+ script.write_text(
+ "# /// script\n"
+ '# requires-python = ">=3.11"\n'
+ '# dependencies = ["definitely-not-a-real-pkg-xyz==99.99"]\n'
+ "# ///\n",
+ encoding="utf-8",
+ )
+ # --offline keeps the test hermetic; the resolver still reports
+ # "No solution found when resolving dependencies".
+ with pytest.raises(UvResolutionError):
+ uv(["lock", "--offline", "--script", str(script)])
diff --git a/tests/_runtime/packages/test_package_managers.py b/tests/_runtime/packages/test_package_managers.py
index 08fba278d0..15c56b4bb5 100644
--- a/tests/_runtime/packages/test_package_managers.py
+++ b/tests/_runtime/packages/test_package_managers.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
import sys
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
@@ -7,6 +8,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from marimo._dependencies.dependencies import DependencyManager
+from marimo._environments import script_metadata
+from marimo._environments.uv import UvNotFoundError
from marimo._runtime.packages.package_manager import LogCallback
from marimo._runtime.packages.package_managers import create_package_manager
from marimo._runtime.packages.pypi_package_manager import (
@@ -18,6 +21,9 @@ from marimo._runtime.packages.pypi_package_manager import (
VersionMap,
)
+# Metadata edits absolutize the --script target.
+NB_ABSPATH = os.path.abspath("nb.py")
+
def test_create_package_managers() -> None:
assert isinstance(create_package_manager("pip"), PipPackageManager)
@@ -56,23 +62,26 @@ def test_create_package_manager_without_python_exe() -> None:
assert uv_mgr._python_exe == PY_EXE
-def test_update_script_metadata() -> None:
- runs_calls: list[list[str]] = []
+def uv_calls(monkeypatch: pytest.MonkeyPatch) -> list[list[str]]:
+ """Capture uv invocations made through the script_metadata verbs."""
+ calls: list[list[str]] = []
- class MockUvPackageManager(UvPackageManager):
- @property
- def _uv_bin(self) -> str:
- return "uv"
+ def fake_uv(args: list[str], **kwargs: Any) -> MagicMock:
+ target = args[args.index("--script") + 1]
+ assert os.path.isabs(target)
+ assert kwargs["cwd"] == os.path.dirname(target)
+ calls.append(["uv", *args])
+ return MagicMock()
- def _run_sync(
- self,
- command: list[str],
- log_callback: LogCallback | None = None,
- ) -> bool:
- del log_callback
- runs_calls.append(command)
- return True
+ monkeypatch.setattr(script_metadata, "uv", fake_uv)
+ return calls
+
+def test_update_script_metadata(uv_calls: list[list[str]]) -> None:
+ runs_calls = uv_calls
+
+ class MockUvPackageManager(UvPackageManager):
def _get_version_map(self) -> VersionMap:
return VersionMap({"foo": "1.0", "bar": "2.0"})
@@ -84,30 +93,48 @@ def test_update_script_metadata() -> None:
upgrade=False,
)
assert runs_calls == [
- ["uv", "--quiet", "add", "--script", "nb.py", "foo==1.0"],
- ["uv", "--quiet", "remove", "--script", "nb.py", "bar"],
+ ["uv", "--quiet", "add", "--script", NB_ABSPATH, "foo==1.0"],
+ ["uv", "--quiet", "remove", "--script", NB_ABSPATH, "bar"],
]
runs_calls.clear()
-def test_update_script_metadata_with_version_map() -> None:
- runs_calls: list[list[str]] = []
[email protected]("failures", [{"add"}, {"remove"}, {"add", "remove"}])
+def test_metadata_updates_attempt_both_operations_on_failure(
+ monkeypatch: pytest.MonkeyPatch, failures: set[str]
+) -> None:
+ manager = UvPackageManager()
+ monkeypatch.setattr(
+ manager, "_get_version_map", lambda: VersionMap({"foo": "1.0"})
+ )
+ operations: list[str] = []
- class MockUvPackageManager(UvPackageManager):
- @property
- def _uv_bin(self) -> str:
- return "uv"
+ def run(args: list[str], **kwargs: Any) -> MagicMock:
+ del kwargs
+ operation = args[1]
+ operations.append(operation)
+ if operation in failures:
+ raise UvNotFoundError()
+ return MagicMock()
- def _run_sync(
- self,
- command: list[str],
- log_callback: LogCallback | None = None,
- ) -> bool:
- del log_callback
- runs_calls.append(command)
- return True
+ monkeypatch.setattr(script_metadata, "uv", run)
+ assert not manager.update_notebook_script_metadata(
+ "nb.py",
+ packages_to_add=["foo"],
+ packages_to_remove=["bar"],
+ upgrade=False,
+ )
+ assert operations == ["add", "remove"]
+
+
+def test_update_script_metadata_with_version_map(
+ uv_calls: list[list[str]],
+) -> None:
+ runs_calls = uv_calls
+
+ class MockUvPackageManager(UvPackageManager):
def _get_version_map(self) -> VersionMap:
return VersionMap({"foo": "1.0", "bar": "2.0"})
@@ -124,27 +151,16 @@ def test_update_script_metadata_with_version_map() -> None:
"nb.py", packages_to_remove=["baz"], upgrade=False
)
assert runs_calls == [
- ["uv", "--quiet", "remove", "--script", "nb.py", "baz"],
+ ["uv", "--quiet", "remove", "--script", NB_ABSPATH, "baz"],
]
-def test_update_script_metadata_with_mapping() -> None:
- runs_calls: list[list[str]] = []
+def test_update_script_metadata_with_mapping(
+ uv_calls: list[list[str]],
+) -> None:
+ runs_calls = uv_calls
class MockUvPackageManager(UvPackageManager):
- @property
- def _uv_bin(self) -> str:
- return "uv"
-
- def _run_sync(
- self,
- command: list[str],
- log_callback: LogCallback | None = None,
- ) -> bool:
- del log_callback
- runs_calls.append(command)
- return True
-
def _get_version_map(self) -> VersionMap:
return VersionMap(
{"ibis": "2.0", "ibis-framework": "2.0", "pyyaml": "1.0"}
@@ -156,7 +172,7 @@ def test_update_script_metadata_with_mapping() -> None:
"nb.py", packages_to_add=["ibis"], upgrade=False
)
assert runs_calls == [
- ["uv", "--quiet", "add", "--script", "nb.py", "ibis==2.0"],
+ ["uv", "--quiet", "add", "--script", NB_ABSPATH, "ibis==2.0"],
]
runs_calls.clear()
@@ -166,7 +182,7 @@ def test_update_script_metadata_with_mapping() -> None:
"nb.py", import_namespaces_to_add=["yaml"], upgrade=False
)
assert runs_calls == [
- ["uv", "--quiet", "add", "--script", "nb.py", "pyyaml==1.0"],
+ ["uv", "--quiet", "add", "--script", NB_ABSPATH, "pyyaml==1.0"],
]
runs_calls.clear()
@@ -181,29 +197,18 @@ def test_update_script_metadata_with_mapping() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"ibis-framework[duckdb]==2.0",
],
]
-def test_update_script_metadata_marimo_packages() -> None:
- runs_calls: list[list[str]] = []
+def test_update_script_metadata_marimo_packages(
+ uv_calls: list[list[str]],
+) -> None:
+ runs_calls = uv_calls
class MockUvPackageManager(UvPackageManager):
- @property
- def _uv_bin(self) -> str:
- return "uv"
-
- def _run_sync(
- self,
- command: list[str],
- log_callback: LogCallback | None = None,
- ) -> bool:
- del log_callback
- runs_calls.append(command)
- return True
-
def _get_version_map(self) -> VersionMap:
return VersionMap(
{
@@ -230,7 +235,7 @@ def test_update_script_metadata_marimo_packages() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"marimo-ai==0.2.0",
"pandas==2.0.0",
]
@@ -253,7 +258,7 @@ def test_update_script_metadata_marimo_packages() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"marimo",
"marimo[sql]",
"pandas==2.0.0",
@@ -278,7 +283,7 @@ def test_update_script_metadata_marimo_packages() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"marimo",
"marimo[sql]",
"marimo[recommended]",
@@ -302,7 +307,7 @@ def test_update_script_metadata_marimo_packages() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"marimo",
"pandas==2.0.0",
]
@@ -321,7 +326,7 @@ def test_update_script_metadata_marimo_packages() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"--upgrade",
"pandas==2.0.0",
],
@@ -364,21 +369,6 @@ async def test_uv_pip_install() -> None:
]
-def test_log_callback_type() -> None:
- """Test that LogCallback type works correctly."""
- captured_logs = []
-
- def test_callback(log_line: str) -> None:
- captured_logs.append(log_line)
-
- # Test type annotation works
- callback: LogCallback = test_callback
- callback("test log\n")
-
- assert len(captured_logs) == 1
- assert captured_logs[0] == "test log\n"
-
-
async def test_package_manager_run_without_callback() -> None:
"""Test PackageManager.run without log callback (backward compatibility)."""
pm = PipPackageManager()
@@ -587,24 +577,13 @@ async def test_package_manager_install_method_with_callback() -> None:
assert captured_logs == ["Installing test-package==1.0.0...\n"]
-def test_update_script_metadata_with_git_dependencies() -> None:
+def test_update_script_metadata_with_git_dependencies(
+ uv_calls: list[list[str]],
+) -> None:
"""Test that git dependencies are passed through to uv add --script."""
- runs_calls: list[list[str]] = []
+ runs_calls = uv_calls
class MockUvPackageManager(UvPackageManager):
- @property
- def _uv_bin(self) -> str:
- return "uv"
-
- def _run_sync(
- self,
- command: list[str],
- log_callback: LogCallback | None = None,
- ) -> bool:
- del log_callback
- runs_calls.append(command)
- return True
-
def _get_version_map(self) -> VersionMap:
# Git dependencies won't be in the version map with their git+ prefix
return VersionMap({"python-gcode": "0.1.0"})
@@ -624,7 +603,7 @@ def test_update_script_metadata_with_git_dependencies() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"git+https://github.com/fetlab/python_gcode",
],
]
@@ -642,7 +621,7 @@ def test_update_script_metadata_with_git_dependencies() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"git+ssh://[email protected]/user/repo.git",
],
]
@@ -660,7 +639,7 @@ def test_update_script_metadata_with_git_dependencies() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"package @ https://example.com/package.whl",
],
]
@@ -678,7 +657,7 @@ def test_update_script_metadata_with_git_dependencies() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"mypackage @ file:///path/to/package",
],
]
@@ -699,7 +678,7 @@ def test_update_script_metadata_with_git_dependencies() -> None:
"--quiet",
"add",
"--script",
- "nb.py",
+ NB_ABSPATH,
"python-gcode==0.1.0",
"git+https://github.com/user/repo.git",
],