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
improvement: allow renaming markdown files when enabled (#1341)
Myles Scolnick94a75dcfb2d8
diff --git a/frontend/src/components/editor/header/filename-input.tsx b/frontend/src/components/editor/header/filename-input.tsxindex cfe6c4404c..a0626e76a3 100644--- a/frontend/src/components/editor/header/filename-input.tsx+++ b/frontend/src/components/editor/header/filename-input.tsx@@ -20,6 +20,7 @@ import { PopoverAnchor } from "@radix-ui/react-popover";import { FileInfo } from "@/core/network/types";import "./filename-input.css";+import { getFeatureFlag } from "@/core/config/feature-flag";interface FilenameInputProps {resetOnBlur?: boolean;@@ -205,13 +206,17 @@ function getSuggestion(return;}- if (search.endsWith(".")) {+ // Matches allowed files in marimo/_utils/marimo_path.py+ const extensionsToLeave = getFeatureFlag("markdown")+ ? new Set(["py", "md", "markdown", "qmd"])+ : new Set(["py"]);++ if (extensionsToLeave.has(Paths.extension(search))) {+ // If ends with an allowed extension, leave as is+ } else if (search.endsWith(".")) {search = `${search}py`;} else if (search.endsWith(".p")) {search = `${search}y`;- } else if (search.endsWith(".py")) {- // If ends with .py, leave as is- // noop} else {search = `${search}.py`;}diff --git a/frontend/src/utils/__tests__/path.test.ts b/frontend/src/utils/__tests__/path.test.tsindex 3dd0b65287..ac9d3b68c4 100644--- a/frontend/src/utils/__tests__/path.test.ts+++ b/frontend/src/utils/__tests__/path.test.ts@@ -120,4 +120,12 @@ describe("PathBuilder", () => {expect(pathBuilder.dirname("file" as FilePath)).toBe("");});});++ describe("extension", () => {+ it("should return the extension of a file", () => {+ expect(Paths.extension("file.txt")).toBe("txt");+ expect(Paths.extension("file")).toBe("");+ expect(Paths.extension("file.tar.gz")).toBe("gz");+ });+ });});diff --git a/frontend/src/utils/paths.ts b/frontend/src/utils/paths.tsindex 17cbcf72d7..147d0a14f3 100644--- a/frontend/src/utils/paths.ts+++ b/frontend/src/utils/paths.ts@@ -11,6 +11,13 @@ export const Paths = {basename: (path: string) => {return PathBuilder.guessDeliminator(path).basename(path as FilePath);},+ extension: (filename: string): string => {+ const parts = filename.split(".");+ if (parts.length === 1) {+ return "";+ }+ return parts.at(-1) ?? "";+ },};export class PathBuilder {diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 7c39ae0867..5d20a1d4ec 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -23,6 +23,7 @@ from marimo._cli.upgrade import check_for_updatesfrom marimo._server.file_router import AppFileRouterfrom marimo._server.model import SessionModefrom marimo._server.start import start+from marimo._utils.marimo_path import MarimoPathDEVELOPMENT_MODE = FalseQUIET = False@@ -357,7 +358,7 @@ def run(codegen.get_app(name)start(- file_router=AppFileRouter.from_filename(name),+ file_router=AppFileRouter.from_filename(MarimoPath(name)),development_mode=DEVELOPMENT_MODE,quiet=QUIET,host=host,@@ -485,11 +486,11 @@ def tutorial(source = inspect.getsource(tutorials[name])d = tempfile.TemporaryDirectory()fname = os.path.join(d.name, name + ".py")- with open(fname, "w", encoding="utf-8") as f:- f.write(source)+ path = MarimoPath(fname)+ path.write_text(source)start(- file_router=AppFileRouter.from_filename(fname),+ file_router=AppFileRouter.from_filename(path),development_mode=DEVELOPMENT_MODE,quiet=QUIET,host=host,diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex c0a03afa96..d53c5a85c2 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -2,8 +2,7 @@from __future__ import annotationsimport asyncio-from pathlib import Path-from typing import Callable+from typing import TYPE_CHECKING, Callableimport click@@ -16,8 +15,12 @@ from marimo._server.export import ()from marimo._server.utils import asyncio_runfrom marimo._utils.file_watcher import FileWatcher+from marimo._utils.marimo_path import MarimoPathfrom marimo._utils.paths import maybe_make_dirs+if TYPE_CHECKING:+ from pathlib import Path+@click.group(help="""Export a notebook to various formats.""")def export() -> None:@@ -25,10 +28,10 @@ def export() -> None:def watch_and_export(- name: str,+ marimo_path: MarimoPath,output: str,watch: bool,- export_callback: Callable[[str], str],+ export_callback: Callable[[MarimoPath], str],) -> None:if watch and not output:raise click.UsageError(@@ -49,7 +52,7 @@ def watch_and_export(# No watch, just run onceif not watch:- data = export_callback(name)+ data = export_callback(marimo_path)write_data(data)return@@ -57,13 +60,15 @@ def watch_and_export(click.echo(f"File {str(file_path)} changed. Re-exporting to {green(output)}")- data = export_callback(str(file_path))+ data = export_callback(MarimoPath(file_path))write_data(data)async def start() -> None:# Watch the file for changes- watcher = FileWatcher.create(Path(name), on_file_changed)- click.echo(f"Watching {green(name)} for changes...")+ watcher = FileWatcher.create(marimo_path.path, on_file_changed)+ click.echo(+ f"Watching {green(marimo_path.relative_name)} for changes..."+ )watcher.start()try:# Run forever@@ -132,7 +137,7 @@ def html(cli_args = parse_args(args)- def export_callback(file_path: str) -> str:+ def export_callback(file_path: MarimoPath) -> str:(html, _filename) = asyncio_run(run_app_then_export_as_html(file_path, include_code=include_code, cli_args=cli_args@@ -140,7 +145,7 @@ def html()return html- return watch_and_export(name, output, watch, export_callback)+ return watch_and_export(MarimoPath(name), output, watch, export_callback)@click.command(@@ -189,10 +194,10 @@ def script(Export a marimo notebook as a flat script, in topological order."""- def export_callback(file_path: str) -> str:+ def export_callback(file_path: MarimoPath) -> str:return export_as_script(file_path)[0]- return watch_and_export(name, output, watch, export_callback)+ return watch_and_export(MarimoPath(name), output, watch, export_callback)@click.command(@@ -241,10 +246,10 @@ def md(Export a marimo notebook as a code fenced markdown document."""- def export_callback(file_path: str) -> str:+ def export_callback(file_path: MarimoPath) -> str:return export_as_md(file_path)[0]- return watch_and_export(name, output, watch, export_callback)+ return watch_and_export(MarimoPath(name), output, watch, export_callback)export.add_command(html)diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex 3e6bf45058..4b0611488e 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -13,6 +13,7 @@ from typing import Optionalimport clickfrom marimo._cli.print import green+from marimo._utils.marimo_path import MarimoPathfrom marimo._utils.url import is_urlSTATIC_HTML_CODE_PREFIX = '<marimo-code hidden="">'@@ -89,8 +90,10 @@ def validate_name(f" marimo convert {name} > {prefix}.py\n\n"f" then open with marimo edit {prefix}.py")- elif path.suffix != ".py":- raise click.UsageError("Invalid NAME - %s is not a Python file" % name)+ elif not MarimoPath.is_valid_path(path):+ raise click.UsageError(+ "Invalid NAME - %s is not a Python or Markdown file" % name+ )if is_github_src(name, ext=".py"):temp_dir = TemporaryDirectory()diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 3da19a3ef2..5e7cacc80d 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -1,8 +1,11 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import abcfrom typing import TYPE_CHECKING, List, Tuplefrom marimo._server.file_router import AppFileRouter+from marimo._utils.marimo_path import MarimoPathif TYPE_CHECKING:from starlette.types import ASGIApp@@ -114,7 +117,7 @@ def create_asgi_app(def _build_app(self, path: str, root: str) -> "ASGIAppBuilder":session_manager = SessionManager(- file_router=AppFileRouter.from_filename(root),+ file_router=AppFileRouter.from_filename(MarimoPath(root)),mode=SessionMode.RUN,development_mode=False,quiet=quiet,diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex 9143613167..9fc8ee972d 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -15,12 +15,13 @@ from marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.export import ExportAsHTMLRequestfrom marimo._server.models.models import InstantiateRequestfrom marimo._server.session.session_view import SessionView+from marimo._utils.marimo_path import MarimoPathdef export_as_script(- filename: str,+ path: MarimoPath,) -> tuple[str, str]:- file_router = AppFileRouter.from_filename(filename)+ file_router = AppFileRouter.from_filename(path)file_key = file_router.get_unique_file_key()assert file_key is not Nonefile_manager = file_router.get_file_manager(file_key)@@ -29,9 +30,9 @@ def export_as_script(def export_as_md(- filename: str,+ path: MarimoPath,) -> tuple[str, str]:- file_router = AppFileRouter.from_filename(filename)+ file_router = AppFileRouter.from_filename(path)file_key = file_router.get_unique_file_key()assert file_key is not Nonefile_manager = file_router.get_file_manager(file_key)@@ -40,12 +41,12 @@ def export_as_md(async def run_app_then_export_as_html(- filename: str,+ path: MarimoPath,include_code: bool,cli_args: SerializedCLIArgs,) -> tuple[str, str]:# Create a file router and file manager- file_router = AppFileRouter.from_filename(filename)+ file_router = AppFileRouter.from_filename(path)file_key = file_router.get_unique_file_key()assert file_key is not Nonefile_manager = file_router.get_file_manager(file_key)diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 5e7fee8ef4..78375febef 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -108,7 +108,7 @@ class AppFileManager:self._assert_path_does_not_exist(new_filename)- if self.filename is not None:+ if self._is_named():self._rename_file(new_filename)else:self._create_file(new_filename)@@ -169,7 +169,7 @@ class AppFileManager:configs=configs,)- if self.filename is not None and not self._is_same_path(filename):+ if self._is_named() and not self._is_same_path(filename):raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,detail="Save handler cannot rename files.",@@ -199,7 +199,7 @@ class AppFileManager:header_comments = codegen.get_header_comments(filename)self._create_file(filename, contents, header_comments)- if self.filename is None:+ if self._is_unnamed():self.rename(filename)def to_code(self) -> str:@@ -212,6 +212,12 @@ class AppFileManager:)return contents+ def _is_unnamed(self) -> bool:+ return self.filename is None++ def _is_named(self) -> bool:+ return self.filename is not None+def read_file(self) -> str:"""Read the contents of the file."""if self.filename is None:diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.pyindex 73b62367ef..f75b8230c3 100644--- a/marimo/_server/file_router.py+++ b/marimo/_server/file_router.py@@ -9,6 +9,7 @@ from marimo import _loggersfrom marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.models.home import MarimoFile+from marimo._utils.marimo_path import MarimoPathLOGGER = _loggers.marimo_logger()@@ -27,7 +28,7 @@ class AppFileRouter(abc.ABC):def infer(path: str) -> AppFileRouter:if os.path.isfile(path):LOGGER.debug("Routing to file %s", path)- return AppFileRouter.from_filename(path)+ return AppFileRouter.from_filename(MarimoPath(path))if os.path.isdir(path):LOGGER.debug("Routing to directory %s", path)return AppFileRouter.from_directory(path)@@ -37,12 +38,12 @@ class AppFileRouter(abc.ABC):)@staticmethod- def from_filename(filename: str) -> AppFileRouter:+ def from_filename(file: MarimoPath) -> AppFileRouter:files = [MarimoFile(- name=filename,- path=os.path.abspath(filename),- last_modified=os.path.getmtime(filename),+ name=file.relative_name,+ path=file.absolute_name,+ last_modified=file.last_modified,)]return ListOfFilesAppFileRouter(files)@@ -197,9 +198,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):full_path = os.path.join(root, filename)relative_path = os.path.relpath(full_path, directory)# Python files must contain "marimo.App", or markdown files- if not filename.endswith(".py") or self._is_marimo_app(- full_path- ):+ if self._is_marimo_app(full_path):files.append(MarimoFile(name=filename,@@ -212,8 +211,13 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):def _is_marimo_app(self, full_path: str) -> bool:try:- with open(full_path, "r", encoding="utf-8") as f:- return "marimo.App" in f.read()+ path = MarimoPath(full_path)+ contents = path.read_text()+ if path.is_markdown():+ return "marimo-version:" in contents+ if path.is_python():+ return "marimo.App" in contents+ return Falseexcept Exception as e:LOGGER.debug("Error reading file %s: %s", full_path, e)return Falsediff --git a/marimo/_server/utils.py b/marimo/_server/utils.pyindex fafd6e7af7..f0339f7dd0 100644--- a/marimo/_server/utils.py+++ b/marimo/_server/utils.py@@ -3,11 +3,11 @@ from __future__ import annotationsimport asyncioimport os-import pathlibimport sysfrom typing import TYPE_CHECKING, Any, TypeVarfrom marimo import _loggers+from marimo._utils.marimo_path import MarimoPathif TYPE_CHECKING:from collections.abc import Coroutine@@ -25,7 +25,8 @@ def print_tabbed(string: str, n_tabs: int = 1) -> None:def canonicalize_filename(filename: str) -> str:- if pathlib.Path(filename).suffix != ".py":+ # If its not a valid Python or Markdown file, then add .py+ if not MarimoPath.is_valid_path(filename):filename += ".py"return os.path.expanduser(filename)diff --git a/marimo/_utils/marimo_path.py b/marimo/_utils/marimo_path.pynew file mode 100644index 0000000000..f14b6dfeeb--- /dev/null+++ b/marimo/_utils/marimo_path.py@@ -0,0 +1,106 @@+from __future__ import annotations++from pathlib import Path+++class MarimoPath:+ """+ Wrapper around pathlib.Path to provide additional functionality for Marimo.+ And reduce API surface area of pathlib.Path.+ """++ def __init__(self, path: str | Path, strict: bool = False) -> None:+ self.path: Path = Path(path)+ # Do this on initialization to avoid issues with changing directories+ self.cwd = Path.cwd()+ # strict means can only operate in+ # anything under the current working directory+ self.strict = strict++ self.validate()++ def validate(self) -> None:+ if not self.is_valid():+ raise ValueError(+ f"File {self.path} is not a Python or Markdown file."+ )++ @staticmethod+ def is_valid_path(path: str | Path) -> bool:+ try:+ MarimoPath(path)+ return True+ except ValueError:+ return False++ def is_valid(self) -> bool:+ return self.is_python() or self.is_markdown()++ def is_python(self) -> bool:+ return self.path.suffix == ".py"++ def is_markdown(self) -> bool:+ allowed = {".md", ".markdown", ".qmd"}+ return self.path.suffix in allowed++ def rename(self, new_path: Path) -> None:+ if self.strict:+ if not MarimoPath(new_path).is_relative_to(self.cwd):+ raise ValueError(+ "Cannot rename files outside of "+ "the current working directory"+ )++ # Cannot rename if already exists+ if new_path.exists():+ raise ValueError(+ f"Cannot rename {self.path} to {new_path}"+ " because it already exists"+ )++ self.path.rename(new_path)++ def write_text(self, data: str, encoding: str = "utf-8") -> None:+ # By default, write as utf-8+ self.path.write_text(data, encoding)++ def read_text(self, encoding: str = "utf-8") -> str:+ return self.path.read_text(encoding)++ @property+ def short_name(self) -> str:+ return self.path.name++ @property+ def relative_name(self) -> str:+ if self.strict:+ if not self.is_relative_to(self.cwd):+ raise ValueError(+ "Cannot get relative name for files outside"+ " of the current working directory"+ )+ # If can't return relative path, return absolute path+ if not self.is_relative_to(self.cwd):+ return str(self.path.absolute())+ return str(self.path.relative_to(self.cwd))++ def is_relative_to(self, other: Path) -> bool:+ # In python 3.8, is_relative_to is not available+ if not hasattr(self.path, "is_relative_to"):+ try:+ self.path.relative_to(other)+ return True+ except ValueError:+ return False+ return self.path.is_relative_to(other) # type: ignore++ @property+ def absolute_name(self) -> str:+ return str(self.path.absolute())++ @property+ def last_modified(self) -> float:+ return self.path.stat().st_mtime++ def __str__(self) -> str:+ return str(self.path)diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.pyindex ef42f0852e..2cb9ed5cc2 100644--- a/tests/_cli/test_markdown_conversion.py+++ b/tests/_cli/test_markdown_conversion.py@@ -16,6 +16,7 @@ from marimo._server.export.utils import format_filename_title# Just a handful of scripts to testfrom marimo._tutorials import dataflow, marimo_for_jupyter_users+from marimo._utils.marimo_path import MarimoPathfrom tests.mocks import snapshottermodules = {@@ -45,7 +46,7 @@ def convert_from_py(py: str) -> str:tempfile_name = f.namef.write(py)f.seek(0)- output = export_as_md(tempfile_name)[0]+ output = export_as_md(MarimoPath(tempfile_name))[0]finally:os.remove(tempfile_name)@@ -62,7 +63,7 @@ def convert_from_py(py: str) -> str:)def test_markdown_snapshots() -> None:for name, mod in modules.items():- output = sanitized_version(export_as_md(mod.__file__)[0])+ output = sanitized_version(export_as_md(MarimoPath(mod.__file__))[0])snapshot(f"{name}.md.txt", output)diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pyindex 8cfcc2afe1..0d755dfa6b 100644--- a/tests/_runtime/reload/test_module_watcher.py+++ b/tests/_runtime/reload/test_module_watcher.py@@ -12,7 +12,7 @@ from reload_test_utils import random_modname, update_filefrom marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManager-from marimo._runtime.requests import SetCellConfigRequest, SetUserConfigRequest+from marimo._runtime.requests import SetUserConfigRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProviderdiff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex a24bb4b934..362613b0df 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -8,6 +8,7 @@ from marimo._config.manager import UserConfigManagerfrom marimo._server.file_router import AppFileRouterfrom marimo._server.model import SessionModefrom marimo._server.sessions import NoopLspServer, SessionManager+from marimo._utils.marimo_path import MarimoPathif TYPE_CHECKING:from fastapi.testclient import TestClient@@ -44,7 +45,7 @@ if __name__ == "__main__":lsp_server = NoopLspServer()sm = SessionManager(- file_router=AppFileRouter.from_filename(temp_file.name),+ file_router=AppFileRouter.from_filename(MarimoPath(temp_file.name)),mode=SessionMode.EDIT,development_mode=False,quiet=False,diff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.pyindex eb6697193d..f468a82f8d 100644--- a/tests/_server/test_file_router.py+++ b/tests/_server/test_file_router.py@@ -30,16 +30,22 @@ class TestAppFileRouter(unittest.TestCase):self.test_file2 = tempfile.NamedTemporaryFile(delete=False, dir=self.test_dir, suffix=".py")+ self.test_file_3 = tempfile.NamedTemporaryFile(+ delete=False, dir=self.test_dir, suffix=".md"+ )# Write to the temporary filesself.test_file1.write(file_contents.encode())self.test_file1.close()self.test_file2.write(file_contents.encode())self.test_file2.close()+ self.test_file_3.write("marimo-version: 0.0.0".encode())+ self.test_file_3.close()def tearDown(self):# Clean up temporary files and directoryos.unlink(self.test_file1.name)os.unlink(self.test_file2.name)+ os.unlink(self.test_file_3.name)os.rmdir(self.test_dir)def test_infer_file(self):@@ -100,9 +106,6 @@ class TestAppFileRouter(unittest.TestCase):self.test_dir, include_markdown=True)# Create markdown files- _markdown_file1 = tempfile.NamedTemporaryFile(- dir=self.test_dir, suffix=".md"- )files = router.filesassert len(files) == 3diff --git a/tests/_utils/test_marimo_path.py b/tests/_utils/test_marimo_path.pynew file mode 100644index 0000000000..fedd9002ae--- /dev/null+++ b/tests/_utils/test_marimo_path.py@@ -0,0 +1,94 @@+from __future__ import annotations++import os+from pathlib import Path++import pytest++from marimo._utils.marimo_path import MarimoPath+++def test_init():+ # Test with a valid Python file+ path = Path(__file__)+ mp = MarimoPath(path)+ assert mp.path == path++ # Test with a valid Markdown file+ path = Path("README.md")+ mp = MarimoPath(path)+ assert mp.path == path++ # Test with an invalid file+ path = Path("invalid.txt")+ with pytest.raises(ValueError):+ MarimoPath(path)+++def test_is_valid_path():+ # Test with a valid Python file+ assert MarimoPath.is_valid_path(__file__)++ # Test with a valid Markdown file+ assert MarimoPath.is_valid_path("README.md")++ # Test with an invalid file+ assert not MarimoPath.is_valid_path("invalid.txt")+++def test_is_valid():+ # Test with a Python file+ mp = MarimoPath(__file__)+ assert mp.is_valid()+ assert mp.is_python()+ assert not mp.is_markdown()++ # Test with a Markdown file+ mp = MarimoPath("README.md")+ assert mp.is_valid()+ assert not mp.is_python()+ assert mp.is_markdown()+++def test_rename(tmp_path: Path):+ # Create a temporary file+ tmp_file = tmp_path / "test.py"+ tmp_file.write_text("test")++ # Rename the file+ new_file = tmp_path / "new_test.py"+ mp = MarimoPath(tmp_file)+ mp.rename(new_file)+ assert not tmp_file.exists()+ assert new_file.exists()++ # Try to rename to an existing file+ with pytest.raises(ValueError):+ mp.rename(new_file)+++def test_write_text(tmp_path: Path):+ # Create a temporary file+ tmp_file = tmp_path / "test.py"+ mp = MarimoPath(tmp_file)++ # Write some text to the file+ text = "Hello, world!"+ mp.write_text(text)+ assert tmp_file.read_text() == text+++def test_properties():+ mp = MarimoPath(__file__)++ # Test short_name+ assert mp.short_name == os.path.basename(__file__)++ # Test relative_name+ assert mp.relative_name == os.path.relpath(__file__)++ # Test absolute_name+ assert mp.absolute_name == os.path.abspath(__file__)++ # Test last_modified+ assert mp.last_modified == os.path.getmtime(__file__)