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: `marimo edit` local static notebooks (#7474)
crivaronicolini61c90766c81c
diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex 5fabdca5a3..e6a89654bd 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -143,10 +143,13 @@ class GitHubIssueReader(FileReader):class StaticNotebookReader(FileReader):CODE_TAG = r"marimo-code"- CODE_REGEX = re.compile(r"<marimo-code\s+hidden(?:=['\"]{2})?\s*>(.*?)<")+ CODE_REGEX = re.compile(+ r"<marimo-code\s+hidden(?:=['\"]{2})?\s*>\s*(.*?)\s*<"+ )FILENAME_REGEX = re.compile(- r"<marimo-filename\s+hidden(?:=['\"]{2})?\s*>(.*?)<"+ r"<marimo-filename\s+hidden(?:=['\"]{2})?\s*>\s*(.*?)\s*<")+ DEFAULT_FILENAME = "notebook.py"def can_read(self, name: str) -> bool:return self._is_static_marimo_notebook_url(name)[0]@@ -171,6 +174,14 @@ class StaticNotebookReader(FileReader):# Not a URLif not is_url(url):+ # Read a local Static Notebook+ if url.endswith(".html"):+ file_contents = Path(url).read_text(encoding="utf-8")+ return (+ StaticNotebookReader.CODE_TAG in file_contents,+ file_contents,+ )+return False, ""# Ends with .html, try to download it@@ -209,7 +220,7 @@ class StaticNotebookReader(FileReader):StaticNotebookReader.FILENAME_REGEX, file_contents):return urllib.parse.unquote(search.group(1))- return "notebook.py"+ return StaticNotebookReader.DEFAULT_FILENAMEclass GitHubSourceReader(FileReader):@@ -254,9 +265,9 @@ class FileContentReader:self.readers = [LocalFileReader(),GitHubIssueReader(),- StaticNotebookReader(),GitHubSourceReader(),GistSourceReader(),+ StaticNotebookReader(),GenericURLReader(),]@@ -302,7 +313,6 @@ class LocalFileHandler(FileHandler):def handle(self, name: str, temp_dir: TemporaryDirectory[str]) -> tuple[str, Optional[TemporaryDirectory[str]]]:- del temp_dirimport clickpath = Path(name)@@ -320,6 +330,19 @@ class LocalFileHandler(FileHandler):f" then open with marimo edit {prefix}.py")+ if path.suffix == ".html":+ reader = StaticNotebookReader()+ if reader.can_read(name):+ content, filename = reader.read(name)+ path_to_app = self._create_tmp_file_from_content(+ content, filename, temp_dir+ )+ return path_to_app, temp_dir+ else:+ raise click.ClickException(+ f"Invalid HTML file - {name} does not contain Python code. Make sure the file was downloaded from marimo."+ )+if not MarimoPath.is_valid_path(path):raise click.ClickException(f"Invalid NAME - {name} is not a Python or Markdown file"@@ -337,6 +360,16 @@ class LocalFileHandler(FileHandler):return name, None+ @staticmethod+ def _create_tmp_file_from_content(+ content: str, name: str, temp_dir: TemporaryDirectory[str]+ ) -> str:+ LOGGER.info("Creating temporary file")+ path_to_app = Path(temp_dir.name) / name+ path_to_app.write_text(content, encoding="utf-8")+ LOGGER.info("App saved to %s", path_to_app)+ return str(path_to_app)+class RemoteFileHandler(FileHandler):def __init__(self) -> None:diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.pyindex 43dce90d84..b6ffe27667 100644--- a/tests/_cli/test_file_path.py+++ b/tests/_cli/test_file_path.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport tempfileimport urllib.errorfrom pathlib import Path+from textwrap import dedentfrom unittest.mock import Mock, patchimport click@@ -137,27 +138,6 @@ def test_local_file_reader(tmp_path: Path) -> None:assert filename == "local_file.py"-def test_static_notebook_reader() -> None:- reader = StaticNotebookReader()- valid_url = "https://static.marimo.app/static/example"- invalid_url = "https://example.com/file.py"-- with patch.object(- StaticNotebookReader, "_is_static_marimo_notebook_url"- ) as mock_is_static:- mock_is_static.return_value = (- True,- "<marimo-code hidden=''>print('Hello')</marimo-code><marimo-filename hidden=''>test.py</marimo-filename>", # noqa: E501- )- assert reader.can_read(valid_url) is True- content, filename = reader.read(valid_url)- assert content == "print('Hello')"- assert filename == "test.py"-- mock_is_static.return_value = (False, "")- assert reader.can_read(invalid_url) is False--def test_generic_url_reader() -> None:reader = GenericURLReader()assert reader.can_read("https://example.com/file.py") is True@@ -181,19 +161,12 @@ def test_file_content_reader() -> None:with (patch.object(LocalFileReader, "read") as mock_local_read,patch.object(GitHubIssueReader, "read") as mock_github_issue_read,- patch.object(- StaticNotebookReader, "read"- ) as mock_static_notebook_read,patch.object(GitHubSourceReader, "read") as mock_github_source_read,patch.object(GistSourceReader, "read") as mock_gist_source_read,patch.object(GenericURLReader, "read") as mock_generic_url_read,):mock_local_read.return_value = ("local content", "local.py")mock_github_issue_read.return_value = ("issue content", "issue.py")- mock_static_notebook_read.return_value = (- "notebook content",- "notebook.py",- )mock_github_source_read.return_value = ("github content", "github.py")mock_gist_source_read.return_value = ("gist content", "gist.py")mock_generic_url_read.return_value = ("url content", "url.py")@@ -579,3 +552,125 @@ def test_gist_source_reader() -> None:assert "https://api.github.com/gists/12345" in api_call_args[0]content_call_args, _ = mock_get.call_args_list[1]assert content_call_args[0] == expected_raw_url+++class TestStaticNotebooks:+ VALID_HTML_CONTENT = dedent("""\+ <html>+ <marimo-code hidden=''>+ import marimo as mo+ </marimo-code>+ </html>""")+ VALID_HTML_CONTENT_WITH_FILENAME = dedent("""\+ <html>+ <marimo-code hidden=''>+ import marimo as mo+ </marimo-code>+ <marimo-filename hidden=''>+ custom.py+ </marimo-filename>+ </html>""")+ INVALID_HTML_CONTENT = """<html><body>no code</body></html>"""+ PYTHON_CODE = "import marimo as mo"++ @patch("marimo._utils.requests.get")+ @patch("marimo._cli.file_path.Path.read_text")+ def test_static_notebook_reader(self, mock_read_text, mock_get):+ reader = StaticNotebookReader()+ default_filename = reader.DEFAULT_FILENAME++ # Test local file+ mock_read_text.return_value = self.VALID_HTML_CONTENT_WITH_FILENAME+ assert reader.can_read("test.html") is True+ content, filename = reader.read("test.html")+ assert content == self.PYTHON_CODE+ assert filename == "custom.py"++ # Test local file, invalid content+ mock_read_text.return_value = self.INVALID_HTML_CONTENT+ assert reader.can_read("test.html") is False++ # Test remote file+ mock_get.return_value = Response(+ 200, self.VALID_HTML_CONTENT.encode("utf-8"), {}+ )+ assert reader.can_read("http://example.com/notebook.html") is True+ content, filename = reader.read("http://example.com/notebook.html")+ assert content == self.PYTHON_CODE+ assert filename == default_filename++ # Test remote file, invalid content+ mock_get.return_value = Response(+ 200, self.INVALID_HTML_CONTENT.encode("utf-8"), {}+ )+ assert reader.can_read("http://example.com/notebook.html") is False++ # Test non-html URL that is a static notebook+ mock_get.return_value = Response(+ 200, self.VALID_HTML_CONTENT.encode("utf-8"), {}+ )+ assert reader.can_read("https://static.marimo.app/static/foo") is True+ content, filename = reader.read("https://static.marimo.app/static/foo")+ assert content == self.PYTHON_CODE+ assert filename == default_filename++ def test_validate_local_static_notebook(self, tmp_path):+ with patch("marimo._cli.file_path.Path.read_text") as mock_read_text:+ mock_read_text.return_value = self.VALID_HTML_CONTENT_WITH_FILENAME+ html_file = tmp_path / "notebook.html"+ html_file.touch()++ path, temp_dir_obj = validate_name(+ str(html_file), allow_new_file=False, allow_directory=False+ )++ assert temp_dir_obj is not None+ assert Path(path).name == "custom.py"+ assert Path(path).read_text() == self.PYTHON_CODE+ temp_dir_obj.cleanup()++ @patch("marimo._cli.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_CONTENT+ html_file = tmp_path / "notebook.html"+ html_file.touch()++ with pytest.raises(click.ClickException) as excinfo:+ validate_name(+ str(html_file), allow_new_file=False, allow_directory=False+ )+ assert "Invalid HTML file" in str(excinfo.value)++ @patch("marimo._utils.requests.get")+ def test_validate_remote_static_notebook(self, mock_get):+ mock_response = Response(+ 200, self.VALID_HTML_CONTENT.encode("utf-8"), {}+ )+ mock_get.return_value = mock_response++ path, temp_dir_obj = validate_name(+ "https://example.com/notebook.html",+ allow_new_file=False,+ allow_directory=False,+ )+ assert temp_dir_obj is not None+ assert Path(path).name == StaticNotebookReader().DEFAULT_FILENAME+ assert Path(path).read_text() == self.PYTHON_CODE+ temp_dir_obj.cleanup()++ @patch("marimo._utils.requests.get")+ def test_validate_remote_static_marimo_url(self, mock_get):+ mock_response = Response(+ 200, self.VALID_HTML_CONTENT.encode("utf-8"), {}+ )+ mock_get.return_value = mock_response++ path, temp_dir_obj = validate_name(+ "https://static.marimo.app/static/123",+ allow_new_file=False,+ allow_directory=False,+ )+ assert temp_dir_obj is not None+ assert Path(path).name == StaticNotebookReader().DEFAULT_FILENAME+ assert Path(path).read_text() == self.PYTHON_CODE+ temp_dir_obj.cleanup()