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: Update cli.py run/edit from github or external files (#343)
Myles Scolnick206226d70f93
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex e902430f03..3104e76d0e 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -4,11 +4,9 @@ from __future__ import annotationsimport asyncioimport inspectimport json-import loggingimport osimport pathlibimport tempfile-import urllib.requestfrom typing import Any, Literal, Optionalimport click@@ -17,8 +15,8 @@ from marimo import __version__, _loggersfrom marimo._ast import codegenfrom marimo._cli import ipynb_to_marimofrom marimo._cli.envinfo import get_system_info+from marimo._cli.file_path import validate_namefrom marimo._server.server import start_server-from marimo._utils.url import is_urlDEVELOPMENT_MODE = FalseQUIET = False@@ -186,17 +184,12 @@ def edit(name: Optional[str] = None,) -> None:if name is not None:- path = pathlib.Path(name)- if path.suffix != ".py":- raise click.UsageError(- "Invalid NAME - %s is not a Python file" % name- )-+ # Validate name, or download from URL+ # The second return value is an optional temporary directory. It is+ # unused, but must be kept around because its lifetime on disk is bound+ # to the life of the Python object+ name, _ = validate_name(name, allow_new_file=True)if os.path.exists(name):- if not path.is_file():- raise click.UsageError(- "Invalid NAME - %s is not a file" % name- )# module correctness check - don't start the server# if we can't import the modulecodegen.get_app(name)@@ -249,22 +242,11 @@ Example:)@click.argument("name", required=True)def run(port: Optional[int], headless: bool, name: str) -> None:- path = pathlib.Path(name)- if path.suffix != ".py":- raise click.UsageError("Invalid NAME - %s is not a Python file" % name)-- if is_url(name):- d = tempfile.TemporaryDirectory()- logging.info("Downloading %s", name)- path_to_app = os.path.join(d.name, os.path.basename(name))- urllib.request.urlretrieve(url=name, filename=path_to_app)- logging.info("App saved to %s", path_to_app)- # overwrite name to point to the temporary file- name = path_to_app- elif not os.path.exists(name):- raise click.UsageError("Invalid NAME - %s does not exist" % name)- elif not path.is_file():- raise click.UsageError("Invalid NAME - %s is not a file" % name)+ # Validate name, or download from URL+ # The second return value is an optional temporary directory. It is unused,+ # but must be kept around because its lifetime on disk is bound to the life+ # of the Python object+ name, _ = validate_name(name, allow_new_file=False)# correctness check - don't start the server if we can't import the modulecodegen.get_app(name)diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pynew file mode 100644index 0000000000..595c9a9c46--- /dev/null+++ b/marimo/_cli/file_path.py@@ -0,0 +1,134 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import json+import logging+import os+import pathlib+import urllib.parse+import urllib.request+from tempfile import TemporaryDirectory+from typing import Optional++import click++from marimo._utils.url import is_url+++def validate_name(+ name: str, allow_new_file: bool+) -> tuple[str, Optional[TemporaryDirectory[str]]]:+ """+ Validate the name of the file to be edited/run.++ If its an existing path, check that it is a valid Python file.+ If its a URL, we download it to a temporary file and return+ the path to that file.++ Args:+ name: The name of the file to be edited/run.++ Returns:+ The name of file to to be edited/run+ Optional TemporaryDirectory, returned to prevent it from being+ cleaned up+ """++ if _is_github_issue_url(name):+ temp_dir = TemporaryDirectory()+ return _handle_github_issue(name, temp_dir), temp_dir++ path = pathlib.Path(name)+ if path.suffix != ".py":+ raise click.UsageError("Invalid NAME - %s is not a Python file" % name)++ if _is_github_py(name):+ temp_dir = TemporaryDirectory()+ return _handle_github_py(name, temp_dir), temp_dir++ if is_url(name):+ return _create_tmp_file_from_url(name, temp_dir), temp_dir++ if not allow_new_file:+ if not os.path.exists(name):+ raise click.UsageError("Invalid NAME - %s does not exist" % name)+ if not path.is_file():+ raise click.UsageError("Invalid NAME - %s is not a file" % name)++ return name, None+++def _is_github_issue_url(url: str) -> bool:+ return is_url(url) and url.startswith(+ "https://github.com/marimo-team/marimo/issues/"+ )+++def _handle_github_issue(url: str, temp_dir: TemporaryDirectory[str]) -> str:+ issue_number = url.split("/")[-1]+ api_url = f"https://api.github.com/repos/marimo-team/marimo/issues/{issue_number}"+ issue_response = urllib.request.urlopen(api_url).read().decode("utf-8")+ issue_json = json.loads(issue_response)+ body = issue_json["body"]++ # Find the content between first ```python and last ```+ try:+ code = _find_python_code_in_github_issue(body)+ except IndexError:+ raise click.UsageError(+ "Invalid Issue - %s does not include a marimo app" % url+ ) from None++ # Create a temporary file with the content+ path_to_app = _create_tmp_file_from_content(+ code, f"issue_{issue_number}.py", temp_dir+ )+ return path_to_app+++def _find_python_code_in_github_issue(body: str) -> str:+ # Find the content between first ```python and last ```+ return body.split("```python")[1].rsplit("```", 1)[0]+++def _is_github_py(url: str) -> bool:+ if not is_url(url):+ return False++ hostname = urllib.parse.urlparse(url).hostname+ if hostname != "github.com" and hostname != "raw.githubusercontent.com":+ return False+ path: str = urllib.parse.urlparse(url).path+ if not path.endswith(".py"):+ return False+ return True+++def _handle_github_py(url: str, temp_dir: TemporaryDirectory[str]) -> str:+ # Change hostname to raw.githubusercontent.com+ path = urllib.parse.urlparse(url).path+ path = path.replace("/blob/", "/", 1)+ url = f"https://raw.githubusercontent.com{path}"+ path_to_app = _create_tmp_file_from_url(url, temp_dir)+ return path_to_app+++def _create_tmp_file_from_url(+ url: str, temp_dir: TemporaryDirectory[str]+) -> str:+ logging.info("Downloading %s", url)+ path_to_app = os.path.join(temp_dir.name, os.path.basename(url))+ urllib.request.urlretrieve(url=url, filename=path_to_app)+ logging.info("App saved to %s", path_to_app)+ return path_to_app+++def _create_tmp_file_from_content(+ content: str, name: str, temp_dir: TemporaryDirectory[str]+) -> str:+ logging.info("Creating temporary file")+ path_to_app = os.path.join(temp_dir.name, name)+ with open(path_to_app, "w") as f:+ f.write(content)+ logging.info("App saved to %s", path_to_app)+ return path_to_appdiff --git a/marimo/_cli/test_file_path.py b/marimo/_cli/test_file_path.pynew file mode 100644index 0000000000..eb621e4787--- /dev/null+++ b/marimo/_cli/test_file_path.py@@ -0,0 +1,137 @@+# Copyright 2023 Marimo. All rights reserved.+import tempfile+from typing import Any+from unittest.mock import mock_open, patch++import click+import pytest++from marimo._cli.file_path import (+ _create_tmp_file_from_content,+ _create_tmp_file_from_url,+ _find_python_code_in_github_issue,+ _handle_github_issue,+ _is_github_issue_url,+ _is_github_py,+ validate_name,+)++temp_dir = tempfile.TemporaryDirectory()+++def test_validate_name_with_python_file() -> None:+ full_path = __file__+ assert validate_name(full_path, allow_new_file=False)[0].endswith(+ "test_file_path.py"+ )+++def test_validate_name_with_non_python_file() -> None:+ with pytest.raises(click.UsageError):+ validate_name("example.txt", allow_new_file=False)+ with pytest.raises(click.UsageError):+ validate_name("example.txt", allow_new_file=True)+++def test_validate_name_with_nonexistent_file() -> None:+ with pytest.raises(click.UsageError):+ validate_name("nonexistent.py", allow_new_file=False)+ assert (+ "nonexistent.py"+ == validate_name("nonexistent.py", allow_new_file=True)[0]+ )+++def test_validate_name_with_directory() -> None:+ with pytest.raises(click.UsageError):+ validate_name(".", allow_new_file=False)+ with pytest.raises(click.UsageError):+ validate_name(".", allow_new_file=True)+++def test_is_github_issue_url_with_valid_url() -> None:+ valid_url = "https://github.com/marimo-team/marimo/issues/1"+ assert _is_github_issue_url(valid_url) is True++ invalid_url = "https://github.com/marimo-team/marimo/pull/1"+ assert _is_github_issue_url(invalid_url) is False+++def test_is_github_py_with_valid_url() -> None:+ valid_url = "https://github.com/marimo-team/marimo/blob/main/example.py"+ assert _is_github_py(valid_url) is True++ invalid_url = "https://github.com/marimo-team/marimo/blob/main/example.txt"+ assert _is_github_py(invalid_url) is False+++@patch("urllib.request.urlopen")+def test_handle_github_issue(mock_urlopen: Any) -> None:+ # Mock the response from GitHub API+ mock_response = mock_open(+ read_data="""{+ "body": "Some content.```python\\nprint(\'Hello, world!\')\\n```"}+ """.encode()+ )+ mock_urlopen.return_value = mock_response()++ # Call the function with a mock URL+ issue_url = "https://github.com/marimo-team/marimo/issues/1"+ result = _handle_github_issue(issue_url, temp_dir)++ # Check if the result is a path to a temporary file+ assert result.endswith(".py")+ assert open(result).read().strip() == "print('Hello, world!')"+++def test_create_tmp_file_from_url() -> None:+ url = "https://raw.githubusercontent.com/marimo-team/marimo/main/examples/optimization/regularization_and_sparsity.py"+ result = _create_tmp_file_from_url(url, temp_dir)++ # Check if the result is a path to a temporary file+ assert result.endswith(".py")+++def test_create_tmp_file_from_content() -> None:+ content = 'print("Hello, world!")'+ name = "test_script.py"+ result = _create_tmp_file_from_content(content, name, temp_dir)++ assert result.endswith(name)+ assert open(result).read() == content+++def test_find_python_code_in_github_issue_multiple_codes() -> None:+ body = """+ some text.+ ```python+ print("First block of Python code")+ ```+ some more text.+ ```python+ print("Second block of Python code")+ ```+ """+ expected = '\n print("First block of Python code")\n '+ actual = _find_python_code_in_github_issue(body)+ assert actual == expected++ body = """+ some text without any code blocks.+ """+ try:+ _find_python_code_in_github_issue(body)+ raise AssertionError("Expected an IndexError")+ except IndexError:+ # IndexError if there are no code blocks+ pass++ body = """+ some text.+ ```python+ print("Only one block of Python code")+ ```+ """+ expected = '\n print("Only one block of Python code")\n '+ actual = _find_python_code_in_github_issue(body)+ assert actual == expected