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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add r2 support for 'marimo edit' (#8278)
Myles Scolnicke5a8ee6ff59d
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 540689d2eb..1b9c5b765d 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -22,7 +22,7 @@ from marimo._cli.convert.commands import convertfrom marimo._cli.development.commands import developmentfrom marimo._cli.envinfo import get_system_infofrom marimo._cli.export.commands import export-from marimo._cli.file_path import validate_name+from marimo._cli.files.file_path import validate_namefrom marimo._cli.help_formatter import ColoredGroupfrom marimo._cli.parse_args import parse_argsfrom marimo._cli.print import bright_green, light_blue, reddiff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.pyindex b8cde4e53a..f4510ad991 100644--- a/marimo/_cli/convert/utils.py+++ b/marimo/_cli/convert/utils.py@@ -6,7 +6,7 @@ from pathlib import Pathimport clickimport marimo._utils.requests as requests-from marimo._cli.file_path import get_github_src_url, is_github_src+from marimo._cli.files.file_path import get_github_src_url, is_github_srcfrom marimo._utils.url import is_urldiff --git a/marimo/_cli/files/__init__.py b/marimo/_cli/files/__init__.pynew file mode 100644index 0000000000..fe2d2e388e--- /dev/null+++ b/marimo/_cli/files/__init__.py@@ -0,0 +1 @@+# Copyright 2026 Marimo. All rights reserved.diff --git a/marimo/_cli/files/cloudflare.py b/marimo/_cli/files/cloudflare.pynew file mode 100644index 0000000000..6536d81ab2--- /dev/null+++ b/marimo/_cli/files/cloudflare.py@@ -0,0 +1,94 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import os+import shutil+import subprocess+from pathlib import Path+from typing import TYPE_CHECKING, Optional++import click++from marimo._cli.files.file_path import FileHandler++if TYPE_CHECKING:+ from tempfile import TemporaryDirectory+++def is_r2_path(name: str) -> bool:+ return name.startswith("r2://")+++def parse_r2_path(url: str) -> tuple[str, str]:+ """Parse an r2://bucket/key URL into (bucket, key).++ Raises ValueError if the URL is not a valid r2:// path.+ """+ if not is_r2_path(url):+ raise ValueError(f"Not an r2:// URL: {url}")++ path = url[len("r2://") :]+ if "/" not in path:+ raise ValueError(+ f"Invalid r2:// URL: {url}. Expected format: r2://bucket/key"+ )++ bucket, key = path.split("/", 1)+ if not key:+ raise ValueError(+ f"Invalid r2:// URL: {url}. Missing object key after bucket name"+ )++ return bucket, key+++def _check_npx_available() -> None:+ if shutil.which("npx") is None:+ raise click.ClickException(+ "npx is not available on PATH. "+ "Install Node.js (https://nodejs.org) to use r2:// paths."+ )+++def _download_r2_object(bucket: str, key: str, local_path: str) -> None:+ _check_npx_available()++ try:+ subprocess.run(+ [+ "npx",+ "wrangler",+ "r2",+ "object",+ "get",+ f"{bucket}/{key}",+ "--file",+ local_path,+ "--remote",+ ],+ check=True,+ capture_output=True,+ text=True,+ )+ except subprocess.CalledProcessError as e:+ msg = (+ f"Failed to download r2://{bucket}/{key}.\n\n"+ f" wrangler stderr: {e.stderr.strip()}\n\n"+ " Tip: run `npx wrangler login` to authenticate, "+ "or check that the bucket and key are correct."+ )+ raise click.ClickException(msg) from e+++class R2FileHandler(FileHandler):+ def can_handle(self, name: str) -> bool:+ return is_r2_path(name)++ def handle(+ self, name: str, temp_dir: TemporaryDirectory[str]+ ) -> tuple[str, Optional[TemporaryDirectory[str]]]:+ bucket, key = parse_r2_path(name)+ filename = os.path.basename(key)+ local_path = str(Path(temp_dir.name) / filename)+ _download_r2_object(bucket, key, local_path)+ return local_path, temp_dirdiff --git a/marimo/_cli/file_path.py b/marimo/_cli/files/file_path.pysimilarity index 99%rename from marimo/_cli/file_path.pyrename to marimo/_cli/files/file_path.pyindex db0622a92a..cc6da19103 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/files/file_path.py@@ -429,7 +429,10 @@ def validate_name(Returns:Path to the file and temporary directory"""+ from marimo._cli.files.cloudflare import R2FileHandler+handlers = [+ R2FileHandler(),LocalFileHandler(allow_new_file, allow_directory),RemoteFileHandler(),]diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.pyindex b4fa513cd1..78bf3d8b51 100644--- a/marimo/_utils/inline_script_metadata.py+++ b/marimo/_utils/inline_script_metadata.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import Any, castfrom marimo import _loggers-from marimo._cli.file_path import FileContentReader+from marimo._cli.files.file_path import FileContentReaderfrom marimo._utils.paths import normalize_pathfrom marimo._utils.scripts import read_pyproject_from_scriptdiff --git a/tests/_cli/test_cloudflare.py b/tests/_cli/test_cloudflare.pynew file mode 100644index 0000000000..050f042d42--- /dev/null+++ b/tests/_cli/test_cloudflare.py@@ -0,0 +1,138 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import subprocess+import tempfile+from unittest.mock import patch++import click+import pytest++from marimo._cli.files.cloudflare import (+ R2FileHandler,+ _download_r2_object,+ parse_r2_path,+)+from marimo._cli.files.file_path import validate_name+++ ("url", "expected"),+ [+ ("r2://bucket/file.py", ("bucket", "file.py")),+ ("r2://bucket/path/to/file.py", ("bucket", "path/to/file.py")),+ ],+)+def test_parse_r2_path(url: str, expected: tuple[str, str]) -> None:+ assert parse_r2_path(url) == expected+++ ("url", "match"),+ [+ ("r2://bucket/", "Missing object key"),+ ("r2://bucket", "Expected format"),+ ("https://example.com", "Not an r2:// URL"),+ ],+)+def test_parse_r2_path_errors(url: str, match: str) -> None:+ with pytest.raises(ValueError, match=match):+ parse_r2_path(url)+++class TestR2FileHandler:+ def test_can_handle(self) -> None:+ handler = R2FileHandler()+ assert handler.can_handle("r2://bucket/file.py") is True+ assert handler.can_handle("https://example.com") is False+ assert handler.can_handle("file.py") is False++ @patch("marimo._cli.files.cloudflare._download_r2_object")+ def test_handle(self, mock_download, tmp_path) -> None:+ handler = R2FileHandler()+ temp_dir = tempfile.TemporaryDirectory(dir=tmp_path)++ mock_download.side_effect = lambda _bucket, _key, local_path: open(+ local_path, "w"+ ).close()++ path, returned_temp_dir = handler.handle(+ "r2://my-bucket/notebooks/test.py", temp_dir+ )++ assert path.endswith("test.py")+ assert returned_temp_dir is temp_dir+ mock_download.assert_called_once_with(+ "my-bucket", "notebooks/test.py", path+ )+++@patch(+ "marimo._cli.files.cloudflare.shutil.which",+ return_value="/usr/bin/npx",+)+@patch("marimo._cli.files.cloudflare.subprocess.run")+def test_download_calls_wrangler(mock_run, mock_which) -> None:+ del mock_which+ mock_run.return_value = subprocess.CompletedProcess(args=[], returncode=0)++ _download_r2_object("my-bucket", "path/to/file.py", "/tmp/file.py")++ mock_run.assert_called_once_with(+ [+ "npx",+ "wrangler",+ "r2",+ "object",+ "get",+ "my-bucket/path/to/file.py",+ "--file",+ "/tmp/file.py",+ "--remote",+ ],+ check=True,+ capture_output=True,+ text=True,+ )+++@patch(+ "marimo._cli.files.cloudflare.shutil.which",+ return_value="/usr/bin/npx",+)+@patch("marimo._cli.files.cloudflare.subprocess.run")+def test_download_wrangler_failure(mock_run, mock_which) -> None:+ del mock_which+ mock_run.side_effect = subprocess.CalledProcessError(+ returncode=1,+ cmd=["npx", "wrangler"],+ stderr="authentication required",+ )++ with pytest.raises(click.ClickException, match="Failed to download r2://"):+ _download_r2_object("bucket", "key.py", "/tmp/key.py")+++@patch("marimo._cli.files.cloudflare.shutil.which", return_value=None)+def test_download_npx_not_found(mock_which) -> None:+ del mock_which+ with pytest.raises(click.ClickException, match="npx is not available"):+ _download_r2_object("bucket", "key.py", "/tmp/key.py")+++@patch("marimo._cli.files.cloudflare._download_r2_object")+def test_validate_name_routes_to_r2(mock_download) -> None:+ mock_download.side_effect = lambda _bucket, _key, local_path: open(+ local_path, "w"+ ).close()++ path, temp_dir = validate_name(+ "r2://my-bucket/notebook.py",+ allow_new_file=False,+ allow_directory=False,+ )++ assert path.endswith("notebook.py")+ assert temp_dir is not None+ mock_download.assert_called_once_with("my-bucket", "notebook.py", path)+ temp_dir.cleanup()diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.pyindex 1859ecffa1..66834a843f 100644--- a/tests/_cli/test_file_path.py+++ b/tests/_cli/test_file_path.py@@ -10,7 +10,7 @@ from unittest.mock import Mock, patchimport clickimport pytest-from marimo._cli.file_path import (+from marimo._cli.files.file_path import (FileContentReader,GenericURLReader,GistSourceReader,@@ -574,7 +574,7 @@ class TestStaticNotebooks:PYTHON_CODE = "import marimo as mo"@patch("marimo._utils.requests.get")- @patch("marimo._cli.file_path.Path.read_text")+ @patch("marimo._cli.files.file_path.Path.read_text")def test_static_notebook_reader(self, mock_read_text, mock_get):reader = StaticNotebookReader()default_filename = reader.DEFAULT_FILENAME@@ -615,7 +615,9 @@ class TestStaticNotebooks:assert filename == default_filenamedef test_validate_local_static_notebook(self, tmp_path):- with patch("marimo._cli.file_path.Path.read_text") as mock_read_text:+ with patch(+ "marimo._cli.files.file_path.Path.read_text"+ ) as mock_read_text:mock_read_text.return_value = self.VALID_HTML_CONTENT_WITH_FILENAMEhtml_file = tmp_path / "notebook.html"html_file.touch()@@ -629,7 +631,7 @@ class TestStaticNotebooks:assert Path(path).read_text() == self.PYTHON_CODEtemp_dir_obj.cleanup()- @patch("marimo._cli.file_path.Path.read_text")+ @patch("marimo._cli.files.file_path.Path.read_text")def test_validate_local_html_not_notebook(self, mock_read_text, tmp_path):mock_read_text.return_value = self.INVALID_HTML_CONTENThtml_file = tmp_path / "notebook.html"