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.

improvement: marimo converters to/from various formats (#5146)

Myles Scolnick3036aa219c0a
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index e0404877c0..c6658ac7a8 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -16,36 +16,42 @@ import { downloadBlob } from "@/utils/download";
import { useEvent } from "@/hooks/useEvent";
import { getNotebook } from "@/core/cells/cells";
import { notebookCells } from "@/core/cells/utils";
-import { useFilename } from "@/core/saving/filename";
+import type { Notebook } from "@marimo-team/marimo-api";
+import { getMarimoVersion } from "@/core/meta/globals";
+import { Paths } from "@/utils/paths";
const RecoveryModal = (props: {
proposedName: string;
closeModal: () => void;
}): JSX.Element => {
- const filename = useFilename();
-
const downloadRecoveryFile = () => {
downloadBlob(
- new Blob([getCellsAsJSON()], { type: "text/plain" }),
+ new Blob([getNotebookJSON()], { type: "text/plain" }),
`${props.proposedName}.json`,
);
};
- const getCellsAsJSON = useEvent(() => {
+ const getNotebookJSON = useEvent(() => {
const notebook = getNotebook();
const cells = notebookCells(notebook);
- return JSON.stringify(
- {
- filename: filename,
- cells: cells.map((cell) => {
- return { name: cell.name, code: cell.code };
- }),
+ const notbook: Notebook["NotebookV1"] = {
+ version: "1",
+ metadata: {
+ marimo_version: getMarimoVersion(),
},
- // no replacer
- null,
- // whitespace for indentation
- 2,
- );
+ cells: cells.map((cell) => {
+ return {
+ id: cell.id,
+ name: cell.name,
+ code: cell.code,
+ config: {
+ column: 0,
+ ...cell.config,
+ },
+ };
+ }),
+ };
+ return JSON.stringify(notbook, null, 2);
});
// NB: we use markdown class to have sane styling for list, paragraph
@@ -123,7 +129,8 @@ export const RecoveryButton = (props: {
const { filename, needsSave } = props;
const { openModal, closeModal } = useImperativeModal();
- const proposedName = filename === null ? "app" : filename.slice(0, -3);
+ const proposedName =
+ filename === null ? "app" : Paths.basename(filename).split(".")[0];
const openRecoveryModal = () => {
if (needsSave) {
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index baf03979e4..862d2967a8 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -25,6 +25,11 @@ from uuid import uuid4
from marimo._ast.app_config import _AppConfig
from marimo._ast.variables import BUILTINS
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ NotebookSerializationV1,
+)
from marimo._types.ids import CellId_t
if sys.version_info < (3, 10):
@@ -806,3 +811,18 @@ class InternalApp:
self, request: FunctionCallRequest
) -> tuple[HumanReadableStatus, JSONType, bool]:
return await self._app._function_call(request)
+
+ def to_ir(self) -> NotebookSerializationV1:
+ return NotebookSerializationV1(
+ cells=[
+ CellDef(
+ code=cell_data.code,
+ name=cell_data.name,
+ options=cell_data.config.asdict(),
+ )
+ for cell_data in self._app._cell_manager._cell_data.values()
+ ],
+ app=AppInstantiation(
+ options=self._app._config.asdict(),
+ ),
+ )
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index d32663fbf7..819032b22b 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -28,6 +28,11 @@ if TYPE_CHECKING:
@dataclasses.dataclass
class CellConfig:
+ """
+ Internal representation of a cell's configuration.
+ This is not part of the public API.
+ """
+
column: Optional[int] = None
# If True, the cell and its descendants cannot be executed,
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 7068b11df2..bc1b9d4094 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -2,12 +2,11 @@
from __future__ import annotations
import ast
-import json
import os
import re
import sys
import textwrap
-from typing import TYPE_CHECKING, Any, Literal, Optional, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional
from marimo import __version__
from marimo._ast.app_config import _AppConfig
@@ -17,6 +16,8 @@ from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAME
from marimo._ast.toplevel import TopLevelExtraction, TopLevelStatus
from marimo._ast.variables import BUILTINS
from marimo._ast.visitor import Name, VariableData
+from marimo._convert.converters import MarimoConvert
+from marimo._schemas.serialization import NotebookSerializationV1
from marimo._types.ids import CellId_t
if TYPE_CHECKING:
@@ -349,6 +350,16 @@ def generate_app_constructor(config: Optional[_AppConfig]) -> str:
return format_tuple_elements("app = marimo.App(...)", kwargs)
+def generate_filecontents_from_ir(ir: NotebookSerializationV1) -> str:
+ return generate_filecontents(
+ codes=[cell.code for cell in ir.cells],
+ names=[cell.name for cell in ir.cells],
+ cell_configs=[CellConfig.from_dict(cell.options) for cell in ir.cells],
+ config=_AppConfig.from_untrusted_dict(ir.app.options),
+ header_comments=ir.header.value if ir.header else None,
+ )
+
+
def generate_filecontents(
codes: list[str],
names: list[str],
@@ -357,6 +368,7 @@ def generate_filecontents(
header_comments: Optional[str] = None,
) -> str:
"""Translates a sequences of codes (cells) to a Python file"""
+
# Update old internal cell names to the new ones
for idx, name in enumerate(names):
if name == "__":
@@ -391,28 +403,12 @@ def generate_filecontents(
return "\n".join(filecontents).lstrip()
-def recover(filename: str) -> str:
+def recover(filepath: Path) -> str:
"""Generate a module for code recovered from a disconnected frontend"""
- with open(filename, encoding="utf-8") as f:
- contents = f.read()
- cells = json.loads(contents)["cells"]
- codes, names, configs = tuple(
- zip(
- *[
- (
- cell["code"],
- cell["name"],
- cell["config"] if "config" in cell else CellConfig(),
- )
- for cell in cells
- ]
- )
- )
- return generate_filecontents(
- cast(list[str], list(codes)),
- cast(list[str], list(names)),
- cast(list[CellConfig], list(configs)),
- )
+ import json
+
+ contents = filepath.read_text(encoding="utf-8")
+ return MarimoConvert.from_notebook_v1(json.loads(contents)).to_py()
def is_multiline_comment(node: ast.stmt) -> bool:
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.py
index a1220de1d0..d8c54fc595 100644
--- a/marimo/_ast/load.py
+++ b/marimo/_ast/load.py
@@ -3,7 +3,8 @@ from __future__ import annotations
import importlib.util
import sys
-from typing import Literal, Optional
+from pathlib import Path
+from typing import Literal, Optional, Union
from marimo import _loggers
from marimo._ast.app import App, InternalApp
@@ -23,14 +24,11 @@ LOGGER = _loggers.marimo_logger()
# on startup and defer errors to the runtime.
-def _maybe_contents(filename: Optional[str]) -> Optional[str]:
+def _maybe_contents(filename: Optional[Union[str, Path]]) -> Optional[str]:
if filename is None:
return None
- with open(filename, encoding="utf-8") as f:
- contents = f.read().strip()
-
- return contents
+ return Path(filename).read_text(encoding="utf-8").strip()
# Used in tests and current fallback
@@ -60,11 +58,14 @@ def _dynamic_load(filename: str) -> Optional[App]:
return app
-def _static_load(filename: str) -> Optional[App]:
- notebook = parse_notebook(filename)
+def _static_load(filepath: Path) -> Optional[App]:
+ contents = _maybe_contents(filepath)
+ if not contents:
+ return None
+ notebook = parse_notebook(contents)
if notebook is None or not notebook.valid:
return None
- app = App(**notebook.app.options, _filename=filename)
+ app = App(**notebook.app.options, _filename=str(filepath))
for cell in notebook.cells:
if isinstance(cell, UnparsableCell):
app._unparsable_cell(cell.code, **cell.options)
@@ -85,19 +86,26 @@ def notebook_is_openable(filename: str) -> Literal[True]:
Raises:
SyntaxError: If the file contains a syntax error
"""
+ path = Path(filename)
- if filename.endswith(".md") or filename.endswith(".qmd"):
- contents = _maybe_contents(filename)
- if not contents:
- # We can still "open" it
- return True
- from marimo._cli.convert.markdown import convert_from_md
+ contents = _maybe_contents(filename)
+ if not contents:
+ return True
+
+ if path.suffix in (".md", ".qmd"):
+ from marimo._convert.markdown.markdown import (
+ convert_from_md_to_marimo_ir,
+ )
- _ = convert_from_md(contents)
+ _ = convert_from_md_to_marimo_ir(contents)
return True
- _ = parse_notebook(filename)
- # NB. A invalid notebook can still be opened.
- return True
+
+ if path.suffix == ".py":
+ _ = parse_notebook(contents)
+ # NB. A invalid notebook can still be opened.
+ return True
+
+ raise MarimoFileError("File must end with .py, .md, or .qmd.")
def load_app(filename: Optional[str]) -> Optional[App]:
@@ -120,19 +128,21 @@ def load_app(filename: Optional[str]) -> Optional[App]:
if filename is None:
return None
- if filename.endswith(".md") or filename.endswith(".qmd"):
+ path = Path(filename)
+
+ if path.suffix in (".md", ".qmd"):
contents = _maybe_contents(filename)
if not contents:
return None
- from marimo._cli.convert.markdown import convert_from_md_to_app
+ from marimo._convert.markdown.markdown import convert_from_md_to_app
return convert_from_md_to_app(contents) if contents else None
- if not filename.endswith(".py"):
+ if not path.suffix == ".py":
raise MarimoFileError("File must end with .py or .md")
try:
- return _static_load(filename)
+ return _static_load(path)
except MarimoFileError:
# Security advantages of static load are lost here, but reasonable
# fallback for now.
diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.py
index b6e70b0bd2..163242ba84 100644
--- a/marimo/_ast/parse.py
+++ b/marimo/_ast/parse.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import ast
import io
import token as token_types
+from pathlib import Path
from textwrap import dedent
from tokenize import TokenInfo, tokenize
from typing import (
@@ -51,19 +52,12 @@ class MarimoFileError(Exception):
class Extractor:
"""Helper to extract AST nodes to schema/serialization ir."""
- def __init__(
- self, filename: Optional[str] = None, contents: Optional[str] = None
- ):
- self.contents = None
- if filename is not None:
- assert contents is None, (
- "Cannot provide both filename and contents"
- )
- with open(filename, encoding="utf-8") as f:
- self.contents = f.read().strip()
- elif contents is not None:
- self.contents = contents
+ @staticmethod
+ def from_file(filename: Union[str, Path]) -> Extractor:
+ return Extractor(contents=Path(filename).read_text(encoding="utf-8"))
+ def __init__(self, contents: str):
+ self.contents = contents.strip()
self.lines = self.contents.splitlines() if self.contents else []
def extract_from_offsets(
@@ -340,8 +334,12 @@ class Parser:
the notebook.
"""
- def __init__(self, *args: Any, **kwargs: Any):
- self.extractor = Extractor(*args, **kwargs)
+ @staticmethod
+ def from_file(filename: Union[str, Path]) -> Parser:
+ return Parser(contents=Path(filename).read_text(encoding="utf-8"))
+
+ def __init__(self, contents: str):
+ self.extractor = Extractor(contents=contents)
def node_stack(self) -> PeekStack[Node]:
return PeekStack(iter(ast.parse(self.extractor.contents or "").body))
@@ -788,8 +786,8 @@ def is_run_guard(node: Optional[Node]) -> bool:
)
-def parse_notebook(filename: str) -> Optional[NotebookSerialization]:
- parser = Parser(filename)
+def parse_notebook(contents: str) -> Optional[NotebookSerialization]:
+ parser = Parser(contents)
if not parser.extractor.contents:
return None
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 6b47787e5a..276936b5f2 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -826,9 +826,11 @@ def run(
@click.argument(
"name",
required=True,
- type=click.Path(exists=True, file_okay=True, dir_okay=False),
+ type=click.Path(
+ exists=True, file_okay=True, dir_okay=False, path_type=Path
+ ),
)
-def recover(name: str) -> None:
+def recover(name: Path) -> None:
click.echo(codegen.recover(name))
diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.py
index a81a667e2b..b136e85965 100644
--- a/marimo/_cli/convert/commands.py
+++ b/marimo/_cli/convert/commands.py
@@ -2,14 +2,14 @@
from __future__ import annotations
from pathlib import Path
+from typing import Optional
import click
-from marimo._cli.convert.markdown import convert_from_md
from marimo._cli.convert.utils import load_external_file
from marimo._cli.print import echo
from marimo._cli.utils import prompt_to_overwrite
-from marimo._convert.ipynb import convert_from_ipynb
+from marimo._convert.converters import MarimoConvert
from marimo._utils.paths import maybe_make_dirs
@@ -26,7 +26,7 @@ from marimo._utils.paths import maybe_make_dirs
)
def convert(
filename: str,
- output: Path,
+ output: Optional[Path],
) -> None:
r"""Convert a Jupyter notebook or Markdown file to a marimo notebook.
@@ -58,10 +58,10 @@ def convert(
text = load_external_file(filename, ext)
if ext == ".ipynb":
- notebook = convert_from_ipynb(text)
+ notebook = MarimoConvert.from_ipynb(text).to_py()
else:
assert ext in (".md", ".qmd")
- notebook = convert_from_md(text)
+ notebook = MarimoConvert.from_md(text).to_py()
if output:
output_path = Path(output)
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 942212e00b..8940a0a684 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any
import click
from marimo._cli.print import orange
+from marimo._convert.converters import MarimoConvert
if TYPE_CHECKING:
import psutil
@@ -481,7 +482,152 @@ def print_routes() -> None:
return
[email protected](help="Preview a marimo file as static HTML")
+ "file_path",
+ required=True,
+ type=click.Path(
+ path_type=Path, exists=True, file_okay=True, dir_okay=False
+ ),
+)
+ "--port",
+ default=8080,
+ help="Port to serve the preview on",
+ type=int,
+)
+ "--host",
+ default="localhost",
+ help="Host to serve the preview on",
+ type=str,
+)
+ "--headless",
+ is_flag=True,
+ default=False,
+ help="Don't automatically open the browser",
+)
+def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
+ """
+ Preview a marimo file as static HTML.
+
+ Creates a static HTML export of the marimo file and serves it
+ on a simple HTTP server for preview purposes.
+
+ Example usage:
+ marimo development preview my_notebook.py
+ marimo development preview my_notebook.py --port 8000
+ """
+ import threading
+ import webbrowser
+
+ import uvicorn
+ from starlette.applications import Starlette
+ from starlette.responses import HTMLResponse
+ from starlette.routing import Route
+ from starlette.staticfiles import StaticFiles
+
+ from marimo import __version__
+ from marimo._ast.app_config import _AppConfig
+ from marimo._config.config import DEFAULT_CONFIG
+ from marimo._schemas.session import (
+ NotebookSessionMetadata,
+ NotebookSessionV1,
+ )
+ from marimo._server.export.exporter import hash_code
+ from marimo._server.templates.templates import static_notebook_template
+ from marimo._server.tokens import SkewProtectionToken
+ from marimo._utils.paths import marimo_package_path
+
+ if TYPE_CHECKING:
+ from starlette.requests import Request
+
+ try:
+ # Convert to notebook format
+ notebook_snapshot = MarimoConvert.from_py(
+ file_path.read_text(encoding="utf-8")
+ ).to_notebook_v1()
+
+ # Create empty session snapshot since we're not running the code
+ session_snapshot = NotebookSessionV1(
+ version="1",
+ metadata=NotebookSessionMetadata(marimo_version=__version__),
+ cells=[],
+ )
+
+ # Get the static assets directory
+ static_root = marimo_package_path() / "_static"
+
+ # Get base HTML template
+ template_path = static_root / "index.html"
+
+ html_template = template_path.read_text(encoding="utf-8")
+
+ # Use local assets instead of CDN
+ asset_url = f"http://{host}:{port}"
+ code = file_path.read_text(encoding="utf-8")
+
+ # Generate static HTML
+ html_content = static_notebook_template(
+ html=html_template,
+ user_config=DEFAULT_CONFIG,
+ config_overrides={},
+ server_token=SkewProtectionToken("preview"),
+ app_config=_AppConfig(),
+ filepath=str(file_path),
+ code=code,
+ code_hash=hash_code(code),
+ session_snapshot=session_snapshot,
+ notebook_snapshot=notebook_snapshot,
+ files={},
+ asset_url=asset_url,
+ )
+
+ click.echo(f"Creating preview for {file_path.name}")
+
+ async def serve_html(request: Request) -> HTMLResponse:
+ del request
+ return HTMLResponse(html_content)
+
+ # Create Starlette app
+ app = Starlette(
+ routes=[
+ Route("/", serve_html),
+ Route("/index.html", serve_html),
+ ]
+ )
+
+ # Mount static files for assets
+ app.mount(
+ "/assets",
+ StaticFiles(directory=static_root / "assets"),
+ name="assets",
+ )
+
+ url = f"http://{host}:{port}"
+ click.echo(f"Serving preview at {url}")
+ click.echo("Press Ctrl+C to stop the server")
+
+ # Open browser if requested
+ if not headless:
+
+ def open_browser() -> None:
+ webbrowser.open(url)
+
+ timer = threading.Timer(1.0, open_browser)
+ timer.start()
+
+ # Run the server
+ uvicorn.run(app, host=host, port=port, log_level="error")
+
+ except Exception as e:
+ click.echo(f"Error creating preview: {e}", err=True)
+ raise click.Abort() from e
+
+
development.add_command(inline_packages)
development.add_command(openapi)
development.add_command(ps)
development.add_command(print_routes)
+development.add_command(preview)
diff --git a/marimo/_convert/converters.py b/marimo/_convert/converters.py
new file mode 100644
index 0000000000..8fbc467e69
--- /dev/null
+++ b/marimo/_convert/converters.py
@@ -0,0 +1,98 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._schemas.notebook import NotebookV1
+from marimo._schemas.serialization import (
+ EMPTY_NOTEBOOK_SERIALIZATION,
+ NotebookSerialization,
+)
+
+
+class MarimoConverterIntermediate:
+ """Intermediate representation that allows chaining conversions."""
+
+ def __init__(self, ir: NotebookSerialization):
+ self.ir = ir
+
+ def to_notebook_v1(self) -> NotebookV1:
+ """Convert to NotebookV1 format."""
+ from marimo._convert.notebook import convert_from_ir_to_notebook_v1
+
+ return convert_from_ir_to_notebook_v1(self.ir)
+
+ def to_markdown(self) -> str:
+ raise NotImplementedError("Not implemented")
+
+ def to_py(self) -> str:
+ """Convert to python format."""
+ from marimo._ast.codegen import generate_filecontents_from_ir
+
+ return generate_filecontents_from_ir(self.ir)
+
+ def to_ir(self) -> NotebookSerialization:
+ """Convert to notebook IR."""
+ return self.ir
+
+
+class MarimoConvert:
+ """Converter utility for marimo notebooks."""
+
+ @staticmethod
+ def from_py(source: str) -> MarimoConverterIntermediate:
+ """Convert from marimo Python source code.
+
+ Args:
+ source: Python source code string
+ """
+ from marimo._ast.parse import parse_notebook
+
+ ir = parse_notebook(source) or EMPTY_NOTEBOOK_SERIALIZATION
+ return MarimoConverterIntermediate(ir)
+
+ @staticmethod
+ def from_md(source: str) -> MarimoConverterIntermediate:
+ """Convert from markdown source code.
+
+ Args:
+ source: Markdown source code string
+ """
+ from marimo._convert.markdown.markdown import (
+ convert_from_md_to_marimo_ir,
+ )
+
+ return MarimoConvert.from_ir(convert_from_md_to_marimo_ir(source))
+
+ @staticmethod
+ def from_ipynb(source: str) -> MarimoConverterIntermediate:
+ """Convert from Jupyter notebook JSON.
+
+ Args:
+ source: Jupyter notebook JSON string
+ """
+ from marimo._convert.ipynb import convert_from_ipynb_to_notebook_ir
+
+ return MarimoConvert.from_ir(convert_from_ipynb_to_notebook_ir(source))
+
+ @staticmethod
+ def from_notebook_v1(
+ notebook_v1: NotebookV1,
+ ) -> MarimoConverterIntermediate:
+ """Convert from notebook v1.
+
+ Args:
+ notebook_v1: Notebook v1
+ """
+ from marimo._convert.notebook import convert_from_notebook_v1_to_ir
+
+ return MarimoConverterIntermediate(
+ convert_from_notebook_v1_to_ir(notebook_v1)
+ )
+
+ @staticmethod
+ def from_ir(ir: NotebookSerialization) -> MarimoConverterIntermediate:
+ """Convert from notebook IR.
+
+ Args:
+ ir: Notebook IR
+ """
+ return MarimoConverterIntermediate(ir)
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.py
index 247f862368..012f36cce9 100644
--- a/marimo/_convert/ipynb.py
+++ b/marimo/_convert/ipynb.py
@@ -13,8 +13,14 @@ from marimo._ast.compiler import compile_cell
from marimo._ast.transformers import NameTransformer
from marimo._ast.variables import is_local
from marimo._ast.visitor import Block, NamedNode, ScopedVisitor
-from marimo._convert.utils import generate_from_sources, markdown_to_marimo
+from marimo._convert.utils import markdown_to_marimo
from marimo._runtime.dataflow import DirectedGraph
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ Header,
+ NotebookSerializationV1,
+)
from marimo._types.ids import CellId_t
# Define a type for our transform functions
@@ -698,7 +704,12 @@ def _transform_sources(
return sources
-def convert_from_ipynb(raw_notebook: str) -> str:
+def convert_from_ipynb_to_notebook_ir(
+ raw_notebook: str,
+) -> NotebookSerializationV1:
+ """
+ Convert a raw notebook to a NotebookSerializationV1 object.
+ """
notebook = json.loads(raw_notebook)
sources: list[str] = []
metadata: list[dict[str, Any]] = []
@@ -732,8 +743,14 @@ def convert_from_ipynb(raw_notebook: str) -> str:
for source in transformed_sources
]
- return generate_from_sources(
- sources=transformed_sources,
- header_comments=inline_meta,
- cell_configs=cell_configs,
+ return NotebookSerializationV1(
+ app=AppInstantiation(),
+ header=Header(value=inline_meta or ""),
+ cells=[
+ CellDef(
+ code=source,
+ options={"hide_code": config.hide_code},
+ )
+ for source, config in zip(transformed_sources, cell_configs)
+ ],
)
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_convert/markdown/markdown.py
similarity index 88%
rename from marimo/_cli/convert/markdown.py
rename to marimo/_convert/markdown/markdown.py
index a0e8817119..d53e7ed371 100644
--- a/marimo/_cli/convert/markdown.py
+++ b/marimo/_convert/markdown/markdown.py
@@ -3,7 +3,16 @@ from __future__ import annotations
import re
from dataclasses import dataclass
-from typing import Any, Callable, Literal, Optional, Union, cast
+from typing import (
+ Any,
+ Callable,
+ Generic,
+ Literal,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
# Native to python
from xml.etree.ElementTree import Element, SubElement
@@ -23,21 +32,25 @@ from pymdownx.superfences import ( # type: ignore
)
from marimo import _loggers
-from marimo._ast import codegen
from marimo._ast.app import App, InternalApp
-from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._ast.names import DEFAULT_CELL_NAME
from marimo._convert.utils import markdown_to_marimo, sql_to_marimo
from marimo._dependencies.dependencies import DependencyManager
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ Header,
+ NotebookSerializationV1,
+)
LOGGER = _loggers.marimo_logger()
MARIMO_MD = "marimo-md"
MARIMO_CODE = "marimo-code"
-ConvertKeys = Union[Literal["marimo"], Literal["marimo-app"]]
+ConvertKeys = Union[Literal["marimo-ir"], Literal["marimo-app"]]
def backwards_compatible_sanitization(line: str) -> str:
@@ -107,7 +120,13 @@ def formatted_code_block(
)
-def app_config_from_root(root: Element) -> _AppConfig:
+def app_config_from_root(root: Element) -> dict[str, Any]:
+ """
+ Extract app config from the root element.
+
+ This may contains unknown keys.
+ """
+
# Extract meta data from root attributes.
config_keys = {
"title": "app_title",
@@ -122,7 +141,7 @@ def app_config_from_root(root: Element) -> _AppConfig:
# Remove values particular to markdown saves.
config.pop("marimo-version", None)
- return _AppConfig.from_untrusted_dict(config, silent=True)
+ return config
def get_source_from_tag(tag: Element) -> str:
@@ -161,20 +180,23 @@ def get_cell_config_from_tag(tag: Element, **defaults: bool) -> CellConfig:
return CellConfig.from_dict(extracted_attrs)
+T = TypeVar("T")
+
+
# TODO: Consider upstreaming some logic such that this isn't such a terrible
# hack. At some point rewriting / overriding the markdown parser would be a
# better idea than all these little work arounds.
@dataclass
-class SafeWrap:
- app: App
+class SafeWrap(Generic[T]):
+ inner: T
- def strip(self) -> App:
- return self.app
+ def strip(self) -> T:
+ return self.inner
-def _tree_to_app_obj(root: Element) -> SafeWrap:
+def _tree_to_app_obj(root: Element) -> SafeWrap[App]:
app_config = app_config_from_root(root)
- app = InternalApp(App(**app_config.asdict()))
+ app = InternalApp(App(**app_config))
for child in root:
name = child.get("name", DEFAULT_CELL_NAME)
@@ -208,7 +230,7 @@ def _tree_to_app_obj(root: Element) -> SafeWrap:
return SafeWrap(app._app)
-def _tree_to_app(root: Element) -> str:
+def _tree_to_ir(root: Element) -> SafeWrap[NotebookSerializationV1]:
app_config = app_config_from_root(root)
sources: list[str] = []
@@ -226,13 +248,19 @@ def _tree_to_app(root: Element) -> str:
pyproject = root.get("pyproject", None)
if pyproject and not header:
header = "\n# ".join(["# ///script", *pyproject.splitlines(), "///"])
- return codegen.generate_filecontents(
- sources,
- names,
- cell_config,
- config=app_config,
- header_comments=header,
+ notebook = NotebookSerializationV1(
+ app=AppInstantiation(options=app_config),
+ cells=[
+ CellDef(
+ name=name,
+ code=source,
+ options=config.asdict(),
+ )
+ for name, source, config in zip(names, sources, cell_config)
+ ],
+ header=Header(value=header) if header else None,
)
+ return SafeWrap(notebook)
class IdentityParser(Markdown):
@@ -272,18 +300,25 @@ class IdentityParser(Markdown):
return super().convert(text)
-class MarimoParser(IdentityParser):
+class MarimoMdParser(IdentityParser):
"""Parses Markdown to marimo notebook string."""
meta: dict[str, Any]
- output_formats: dict[ConvertKeys, Callable[[Element], Union[str, App]]] = { # type: ignore[assignment, misc]
- "marimo": _tree_to_app,
+ output_formats: dict[ConvertKeys, Callable[[Element], SafeWrap[Any]]] = { # type: ignore[assignment, misc]
+ "marimo-ir": _tree_to_ir,
"marimo-app": _tree_to_app_obj,
}
- def __init__(self, *args: Any, **kwargs: Any) -> None:
- super().__init__(*args, **kwargs)
+ def __init__(
+ self,
+ *args: Any,
+ output_format: ConvertKeys,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(
+ *args, output_format=cast(Any, output_format), **kwargs
+ )
self.meta = {}
# Build here opposed to the parent class since there is intermediate
# logic after the parser is built, and it is more clear here what is
@@ -343,9 +378,9 @@ class FrontMatterPreprocessor(Preprocessor):
(BSD-3) or python-frontmatter (MIT) for similar implementations.
"""
- def __init__(self, md: MarimoParser):
+ def __init__(self, md: MarimoMdParser):
super().__init__(md)
- self.md: MarimoParser = md
+ self.md: MarimoMdParser = md
def run(self, lines: list[str]) -> list[str]:
if not lines:
@@ -419,7 +454,7 @@ class ExpandAndClassifyProcessor(BlockProcessor):
def run(self, parent: Element, blocks: list[str]) -> None:
# Copy app metadata to the parent element.
- assert isinstance(self.parser.md, MarimoParser)
+ assert isinstance(self.parser.md, MarimoMdParser)
for key, value in self.parser.md.meta.items():
if isinstance(value, str):
parent.set(key, value)
@@ -482,14 +517,18 @@ def convert_from_md_to_app(text: str) -> App:
if not text.strip():
app = App()
else:
- app = cast(App, MarimoParser(output_format="marimo-app").convert(text))
+ app = cast(
+ App, MarimoMdParser(output_format="marimo-app").convert(text)
+ )
app._cell_manager.ensure_one_cell()
return app
-def convert_from_md(text: str) -> str:
- return MarimoParser(output_format="marimo").convert(text)
+def convert_from_md_to_marimo_ir(text: str) -> NotebookSerializationV1:
+ notebook = MarimoMdParser(output_format="marimo-ir").convert(text)
+ assert isinstance(notebook, NotebookSerializationV1)
+ return notebook
def extract_frontmatter(text: str) -> tuple[dict[str, str], str]:
diff --git a/marimo/_convert/notebook.py b/marimo/_convert/notebook.py
new file mode 100644
index 0000000000..4e1cc03cf2
--- /dev/null
+++ b/marimo/_convert/notebook.py
@@ -0,0 +1,80 @@
+from marimo import __version__
+from marimo._schemas.notebook import (
+ NotebookCell,
+ NotebookCellConfig,
+ NotebookMetadata,
+ NotebookV1,
+)
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ NotebookSerialization,
+ NotebookSerializationV1,
+)
+
+
+def convert_from_ir_to_notebook_v1(
+ notebook_ir: NotebookSerialization,
+) -> NotebookV1:
+ """Convert the notebook IR to the NotebookV1.
+
+ Args:
+ notebook_ir: The notebook IR.
+
+ Returns:
+ NotebookV1: The notebook v1.
+ """
+ cells: list[NotebookCell] = []
+ for data in notebook_ir.cells:
+ cells.append(
+ NotebookCell(
+ id=None,
+ code=data.code,
+ name=data.name,
+ config=NotebookCellConfig(
+ column=data.options.get("column", None),
+ disabled=data.options.get("disabled", False),
+ hide_code=data.options.get("hide_code", False),
+ ),
+ )
+ )
+ return NotebookV1(
+ version="1",
+ cells=cells,
+ metadata=NotebookMetadata(marimo_version=__version__),
+ )
+
+
+def convert_from_notebook_v1_to_ir(
+ notebook_v1: NotebookV1,
+) -> NotebookSerialization:
+ """Convert the notebook v1 to the python source code.
+
+ Args:
+ notebook_v1: The notebook v1.
+
+ Returns:
+ str: The python source code.
+ """
+
+ return NotebookSerializationV1(
+ app=AppInstantiation(options={}),
+ header=None,
+ version=None,
+ cells=[
+ CellDef(
+ code=cell.get("code", "") or "",
+ name=cell.get("name", "") or "",
+ options={
+ "column": cell.get("config", {}).get("column", None),
+ "disabled": cell.get("config", {}).get("disabled", False),
+ "hide_code": cell.get("config", {}).get(
+ "hide_code", False
+ ),
+ },
+ )
+ for cell in notebook_v1.get("cells", [])
+ ],
+ violations=[],
+ valid=True,
+ )
diff --git a/marimo/_convert/utils.py b/marimo/_convert/utils.py
index a561be5dac..3033af6987 100644
--- a/marimo/_convert/utils.py
+++ b/marimo/_convert/utils.py
@@ -1,12 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Optional
-
from marimo._ast import codegen
-from marimo._ast.app_config import _AppConfig
-from marimo._ast.cell import CellConfig
-from marimo._ast.names import DEFAULT_CELL_NAME
def markdown_to_marimo(source: str) -> str:
@@ -45,30 +40,3 @@ def sql_to_marimo(
")",
]
)
-
-
-def generate_from_sources(
- *,
- sources: list[str],
- config: Optional[_AppConfig] = None,
- header_comments: Optional[str] = None,
- cell_configs: Optional[list[CellConfig]] = None,
-) -> str:
- """
- Given a list of Python source code,
- generate the marimo file contents.
- """
- if cell_configs is None:
- cell_configs = [CellConfig() for _ in range(len(sources))]
- else:
- assert len(cell_configs) == len(sources), (
- "cell_configs must be the same length as sources"
- )
-
- return codegen.generate_filecontents(
- sources,
- [DEFAULT_CELL_NAME for _ in sources],
- cell_configs,
- config=config,
- header_comments=header_comments,
- )
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 4aaa83a8de..aac3a6362b 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -338,7 +338,8 @@ class PyodideBridge:
def export_markdown(self, request: str) -> str:
del request
md, _filename = Exporter().export_as_md(
- file_manager=self.session.app_manager,
+ notebook=self.session.app_manager.app.to_ir(),
+ filename=self.session.app_manager.filename,
)
return json.dumps(md)
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 2f3c36b36a..0e3315a08f 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -228,7 +228,7 @@ class UvPackageManager(PypiPackageManager):
packages_to_remove: list[str],
upgrade: bool,
) -> None:
- from marimo._cli.convert.markdown import extract_frontmatter
+ from marimo._convert.markdown.markdown import extract_frontmatter
from marimo._utils import yaml
from marimo._utils.inline_script_metadata import (
get_headers_from_frontmatter,
diff --git a/marimo/_schemas/generated/notebook.yaml b/marimo/_schemas/generated/notebook.yaml
index 905dc2a2d0..1451e5042d 100644
--- a/marimo/_schemas/generated/notebook.yaml
+++ b/marimo/_schemas/generated/notebook.yaml
@@ -17,12 +17,9 @@ components:
hide_code:
nullable: true
type: boolean
- required:
- - column
- - disabled
- - hide_code
type: object
id:
+ nullable: true
type: string
name:
nullable: true
@@ -44,18 +41,12 @@ components:
hide_code:
nullable: true
type: boolean
- required:
- - column
- - disabled
- - hide_code
type: object
NotebookMetadata:
properties:
marimo_version:
nullable: true
type: string
- required:
- - marimo_version
type: object
NotebookV1:
properties:
@@ -66,6 +57,8 @@ components:
metadata:
$ref: '#/components/schemas/NotebookMetadata'
version:
+ enum:
+ - '1'
type: string
required:
- version
diff --git a/marimo/_schemas/notebook.py b/marimo/_schemas/notebook.py
index f3603b014e..d6e5390efc 100644
--- a/marimo/_schemas/notebook.py
+++ b/marimo/_schemas/notebook.py
@@ -1,9 +1,7 @@
# Copyright 2025 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Optional
-
-from marimo._schemas.common import BaseDict
+from typing import Literal, Optional, TypedDict
# This file contains the schema for the notebook.
# It may be externally used and must be kept backwards compatible.
@@ -13,7 +11,7 @@ from marimo._schemas.common import BaseDict
# We check for backwards compatibility using a GitHub action: `.github/workflows/test_schemas.yaml`
-class NotebookCellConfig(BaseDict):
+class NotebookCellConfig(TypedDict, total=False):
"""Configuration for a notebook cell"""
column: Optional[int]
@@ -21,28 +19,28 @@ class NotebookCellConfig(BaseDict):
hide_code: Optional[bool]
-class NotebookCell(BaseDict):
+class NotebookCell(TypedDict):
"""Code cell specific structure"""
- id: str
+ id: Optional[str]
code: Optional[str]
name: Optional[str]
config: NotebookCellConfig
# Notebook metadata
-class NotebookMetadata(BaseDict):
+class NotebookMetadata(TypedDict, total=False):
"""Metadata about the notebook"""
marimo_version: Optional[str]
# Main notebook structure
-class NotebookV1(BaseDict):
+class NotebookV1(TypedDict):
"""Main notebook structure"""
# The notebook format version
- version: str
+ version: Literal["1"]
# Metadata about the notebook
metadata: NotebookMetadata
# The cells in the notebook
diff --git a/marimo/_schemas/serialization.py b/marimo/_schemas/serialization.py
index 7a0631d548..8fd03a94d4 100644
--- a/marimo/_schemas/serialization.py
+++ b/marimo/_schemas/serialization.py
@@ -126,5 +126,12 @@ class NotebookSerializationV1:
NotebookSerialization: TypeAlias = NotebookSerializationV1
+EMPTY_NOTEBOOK_SERIALIZATION = NotebookSerializationV1(
+ app=AppInstantiation(options={}),
+ cells=[],
+ violations=[],
+ valid=True,
+)
+
VERSION = "1"
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index 06e54c3c69..dd71910f54 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -221,7 +221,8 @@ async def export_as_markdown(
)
markdown, filename = Exporter().export_as_md(
- file_manager=app_file_manager,
+ notebook=app_file_manager.app.to_ir(),
+ filename=app_file_manager.filename,
)
if body.download:
@@ -277,7 +278,8 @@ async def auto_export_as_markdown(
session.app_file_manager.reload()
markdown, _filename = Exporter().export_as_md(
- file_manager=session.app_file_manager,
+ notebook=session.app_file_manager.app.to_ir(),
+ filename=session.app_file_manager.filename,
)
# Save the Markdown file to disk, at `.marimo/<filename>.md`
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index c83b8fdac9..1571a27a12 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -71,7 +71,11 @@ def export_as_md(
# py -> md
if new_filename:
file_manager.filename = str(new_filename)
- result = Exporter().export_as_md(file_manager, previous=path.path)
+ result = Exporter().export_as_md(
+ notebook=file_manager.app.to_ir(),
+ filename=file_manager.filename,
+ previous=path.path,
+ )
return ExportResult(
contents=result[0],
download_filename=result[1],
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 1de6b83b76..83fd4610c7 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -16,6 +16,7 @@ from typing import (
from marimo import __version__, _loggers
from marimo._ast.cell import Cell, CellImpl
from marimo._ast.names import DEFAULT_CELL_NAME, is_internal_cell_name
+from marimo._ast.visitor import Language
from marimo._config.config import (
DEFAULT_CONFIG,
DisplayConfig,
@@ -28,8 +29,9 @@ from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
+from marimo._schemas.serialization import NotebookSerializationV1
from marimo._server.export.utils import (
- get_app_title,
+ format_filename_title,
get_download_filename,
get_filename,
get_markdown_from_cell,
@@ -47,6 +49,7 @@ from marimo._server.templates.templates import (
wasm_notebook_template,
)
from marimo._server.tokens import SkewProtectionToken
+from marimo._types.ids import CellId_t
from marimo._utils.data_uri import build_data_url
from marimo._utils.marimo_path import MarimoPath
from marimo._utils.paths import marimo_package_path
@@ -71,7 +74,7 @@ class Exporter:
) -> tuple[str, str]:
index_html = get_html_contents()
- filename = get_filename(file_manager)
+ filename = get_filename(file_manager.filename)
files: dict[str, str] = {}
for filename_and_length in request.files:
@@ -133,7 +136,9 @@ class Exporter:
asset_url=request.asset_url,
)
- download_filename = get_download_filename(file_manager, "html")
+ download_filename = get_download_filename(
+ file_manager.filename, "html"
+ )
return html, download_filename
def export_as_script(
@@ -158,7 +163,9 @@ class Exporter:
]
code = f'\n__generated_with = "{__version__}"\n\n' + "\n\n".join(codes)
- download_filename = get_download_filename(file_manager, "script.py")
+ download_filename = get_download_filename(
+ file_manager.filename, "script.py"
+ )
return code, download_filename
def export_as_ipynb(
@@ -221,28 +228,36 @@ class Exporter:
stream = io.StringIO()
nbformat.write(notebook, stream) # type: ignore[no-untyped-call]
stream.seek(0)
- download_filename = get_download_filename(file_manager, "ipynb")
+ download_filename = get_download_filename(
+ file_manager.filename, "ipynb"
+ )
return stream.read(), download_filename
def export_as_md(
- self, file_manager: AppFileManager, previous: Path | None = None
+ self,
+ notebook: NotebookSerializationV1,
+ filename: Optional[str],
+ previous: Path | None = None,
) -> tuple[str, str]:
from marimo._ast import codegen
from marimo._ast.app_config import _AppConfig
- from marimo._ast.cell import Cell
from marimo._ast.compiler import compile_cell
- from marimo._cli.convert.markdown import (
+ from marimo._convert.markdown.markdown import (
extract_frontmatter,
formatted_code_block,
is_sanitized_markdown,
)
from marimo._utils import yaml
- filename = get_filename(file_manager)
+ filename = get_filename(filename)
+ app_title = notebook.app.options.get("app_title", None)
+ if not app_title:
+ app_title = format_filename_title(filename)
+
metadata: dict[str, str | list[str]] = {}
metadata.update(
{
- "title": get_app_title(file_manager),
+ "title": app_title,
"marimo-version": __version__,
}
)
@@ -256,7 +271,7 @@ class Exporter:
metadata.update(
{
k: v
- for k, v in file_manager.app.config.asdict().items()
+ for k, v in notebook.app.options.items()
if k not in ignored_keys and v != default_config.get(k)
}
)
@@ -267,7 +282,7 @@ class Exporter:
if header:
metadata["header"] = header.strip()
else:
- header_file = previous if previous else file_manager.filename
+ header_file = previous if previous else filename
if header_file:
with open(header_file, encoding="utf-8") as f:
_metadata, _ = extract_frontmatter(f.read())
@@ -298,42 +313,37 @@ class Exporter:
)
document = ["---", header.strip(), "---", ""]
previous_was_markdown = False
- for cell_data in file_manager.app.cell_manager.cell_data():
- cell = cell_data.cell
- code = cell_data.code
+
+ for cell in notebook.cells:
+ code = cell.code
# Config values are opt in, so only include if they are set.
- attributes = cell_data.config.asdict()
+ attributes = cell.options
# Allow for attributes like column index.
attributes = {
k: repr(v).lower() for k, v in attributes.items() if v
}
- if not is_internal_cell_name(cell_data.name):
- attributes["name"] = cell_data.name
+ if not is_internal_cell_name(cell.name):
+ attributes["name"] = cell.name
+
# No "cell" typically means not parseable. However newly added
# cells require compilation before cell is set.
# TODO: Refactor so it doesn't occur in export (codegen
# does this too)
# NB. Also need to recompile in the sql case since sql parsing is
# cached.
- if not cell or cell._cell.language == "sql":
- try:
- cell_impl = compile_cell(
- code, cell_id=cell_data.cell_id
- ).configure(cell_data.config)
- cell = Cell(
- _cell=cell_impl,
- _name=cell_data.name,
- _app=file_manager.app,
- )
- cell_data.cell = cell
- except SyntaxError:
- pass
+ language: Language = "python"
+ cell_impl: CellImpl | None = None
+ try:
+ cell_impl = compile_cell(code, cell_id=CellId_t("dummy"))
+ language = cell_impl.language
+ except SyntaxError:
+ pass
- if cell:
+ if cell_impl:
# Markdown that starts a column is forced to code.
column = attributes.get("column", None)
if not column or column == "0":
- markdown = get_markdown_from_cell(cell, code)
+ markdown = get_markdown_from_cell(cell_impl, code)
# Unsanitized markdown is forced to code.
if markdown and is_sanitized_markdown(markdown):
# Use blank HTML comment to separate markdown codeblocks
@@ -342,11 +352,13 @@ class Exporter:
previous_was_markdown = True
document.append(markdown)
continue
- attributes["language"] = cell._cell.language
+ attributes["language"] = language
# Definitely a code cell, but need to determine if it can be
# formatted as non-python.
if attributes["language"] == "sql":
- sql_options = get_sql_options_from_cell(code)
+ sql_options: dict[str, str] | None = (
+ get_sql_options_from_cell(code)
+ )
if not sql_options:
# means not sql.
attributes.pop("language")
@@ -355,7 +367,7 @@ class Exporter:
if sql_options.get("query") == "_df":
sql_options.pop("query")
attributes.update(sql_options)
- code = "\n".join(cell._cell.raw_sqls).strip()
+ code = "\n".join(cell_impl.raw_sqls).strip()
# Definitely no "cell"; as such, treat as code, as everything in
# marimo is code.
@@ -367,7 +379,7 @@ class Exporter:
previous_was_markdown = False
document.append(formatted_code_block(code, attributes))
- download_filename = get_download_filename(file_manager, "md")
+ download_filename = get_download_filename(filename, "md")
return "\n".join(document).strip(), download_filename
def export_as_wasm(
@@ -382,7 +394,7 @@ class Exporter:
) -> tuple[str, str]:
"""Export notebook as a WASM-powered standalone HTML file."""
index_html = get_html_contents()
- filename = get_filename(file_manager)
+ filename = get_filename(file_manager.filename)
# We only want to pass the display config in the static notebook
config: MarimoConfig = deep_copy(DEFAULT_CONFIG)
@@ -403,7 +415,9 @@ class Exporter:
show_code=show_code,
)
- download_filename = get_download_filename(file_manager, "wasm.html")
+ download_filename = get_download_filename(
+ file_manager.filename, "wasm.html"
+ )
return html, download_filename
@@ -464,8 +478,8 @@ class AutoExporter:
def save_html(self, file_manager: AppFileManager, html: str) -> None:
# get filename
- directory = Path(get_filename(file_manager)).parent
- filename = get_download_filename(file_manager, "html")
+ directory = Path(get_filename(file_manager.filename)).parent
+ filename = get_download_filename(file_manager.filename, "html")
# make directory if it doesn't exist
self._make_export_dir(directory)
@@ -476,8 +490,8 @@ class AutoExporter:
def save_md(self, file_manager: AppFileManager, markdown: str) -> None:
# get filename
- directory = Path(get_filename(file_manager)).parent
- filename = get_download_filename(file_manager, "md")
+ directory = Path(get_filename(file_manager.filename)).parent
+ filename = get_download_filename(file_manager.filename, "md")
# make directory if it doesn't exist
self._make_export_dir(directory)
@@ -488,8 +502,8 @@ class AutoExporter:
def save_ipynb(self, file_manager: AppFileManager, ipynb: str) -> None:
# get filename
- directory = Path(get_filename(file_manager)).parent
- filename = get_download_filename(file_manager, "ipynb")
+ directory = Path(get_filename(file_manager.filename)).parent
+ filename = get_download_filename(file_manager.filename, "ipynb")
# make directory if it doesn't exist
self._make_export_dir(directory)
diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.py
index 058ca8b842..e9bdace03c 100644
--- a/marimo/_server/export/utils.py
+++ b/marimo/_server/export/utils.py
@@ -5,10 +5,9 @@ import ast
import os
import re
from textwrap import dedent
-from typing import Optional
+from typing import Optional, Union
-from marimo._ast.cell import Cell
-from marimo._server.file_manager import AppFileManager
+from marimo._ast.cell import Cell, CellImpl
def format_filename_title(filename: str) -> str:
@@ -18,24 +17,14 @@ def format_filename_title(filename: str) -> str:
return title.title()
-def get_filename(
- file_manager: AppFileManager, default: str = "notebook.py"
-) -> str:
- filename = file_manager.filename
+def get_filename(filename: Optional[str], default: str = "notebook.py") -> str:
if not filename:
filename = default
return filename
-def get_app_title(file_manager: AppFileManager) -> str:
- if file_manager.app.config.app_title:
- return f"{file_manager.app.config.app_title}"
- filename = get_filename(file_manager)
- return format_filename_title(filename)
-
-
-def get_download_filename(file_manager: AppFileManager, extension: str) -> str:
- filename = get_filename(file_manager, f"notebook.{extension}")
+def get_download_filename(filename: Optional[str], extension: str) -> str:
+ filename = filename or f"notebook.{extension}"
basename = os.path.basename(filename)
if basename.endswith(f".{extension}"):
return basename
@@ -55,7 +44,9 @@ def _const_or_id(args: ast.stmt) -> str:
return f"{args.id}" # type: ignore[attr-defined]
-def get_markdown_from_cell(cell: Cell, code: str) -> Optional[str]:
+def get_markdown_from_cell(
+ cell: Union[CellImpl, Cell], code: str
+) -> Optional[str]:
"""Attempt to extract markdown from a cell, or return None"""
if not (cell.refs == {"mo"} and not cell.defs):
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index bccf40ffc1..9742d93b36 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -10,14 +10,15 @@ from typing import Any, Optional, Union
from marimo import _loggers
from marimo._ast import codegen, load
from marimo._ast.app import App, InternalApp
-from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._config.config import SqlOutputType, WidthType
+from marimo._convert.converters import MarimoConvert
from marimo._runtime.layout.layout import (
LayoutConfig,
read_layout_config,
save_layout_config,
)
+from marimo._schemas.serialization import Header, NotebookSerializationV1
from marimo._server.api.status import HTTPException, HTTPStatus
from marimo._server.models.models import (
CopyNotebookRequest,
@@ -126,10 +127,7 @@ class AppFileManager:
def _save_file(
self,
filename: str,
- codes: list[str],
- names: list[str],
- configs: list[CellConfig],
- app_config: _AppConfig,
+ notebook: NotebookSerializationV1,
# Whether or not to persist the app to the file system
persist: bool,
# Whether save was triggered by a rename
@@ -148,7 +146,11 @@ class AppFileManager:
previous = None
if previous_filename:
previous = Path(previous_filename)
- contents, _ = Exporter().export_as_md(self, previous)
+ contents, _ = Exporter().export_as_md(
+ self.app.to_ir(),
+ self.filename,
+ previous,
+ )
else:
# Header might be better kept on the AppConfig side, opposed to
# reparsing it. Also would allow for md equivalent in a field like
@@ -166,14 +168,14 @@ class AppFileManager:
)
else:
header_comments = codegen.get_header_comments(filename)
- # try to save the app under the name `filename`
- contents = codegen.generate_filecontents(
- codes,
- names,
- cell_configs=configs,
- config=app_config,
- header_comments=header_comments,
- )
+
+ contents = MarimoConvert.from_ir(
+ NotebookSerializationV1(
+ app=notebook.app,
+ cells=notebook.cells,
+ header=Header(value=header_comments or ""),
+ )
+ ).to_py()
if persist:
self._create_file(filename, contents)
@@ -231,10 +233,7 @@ class AppFileManager:
if needs_save:
self._save_file(
self.filename,
- list(self.app.cell_manager.codes()),
- list(self.app.cell_manager.names()),
- list(self.app.cell_manager.configs()),
- self.app.config,
+ self.app.to_ir(),
persist=True,
previous_filename=previous_filename,
)
@@ -275,14 +274,11 @@ class AppFileManager:
# Update the file with the latest app config
# TODO(akshayka): Only change the `app = marimo.App` line (at top level
# of file), instead of overwriting the whole file.
- new_config = self.app.update_config(config)
+ self.app.update_config(config)
if self.filename is not None:
return self._save_file(
self.filename,
- list(self.app.cell_manager.codes()),
- list(self.app.cell_manager.names()),
- list(self.app.cell_manager.configs()),
- new_config,
+ self.app.to_ir(),
persist=True,
)
return ""
@@ -326,10 +322,7 @@ class AppFileManager:
self.app.update_config({"layout_file": None})
return self._save_file(
filename,
- codes,
- names,
- configs,
- self.app.config,
+ self.app.to_ir(),
persist=request.persist,
)
@@ -340,13 +333,7 @@ class AppFileManager:
def to_code(self) -> str:
"""Read the contents of the unsaved file."""
- contents = codegen.generate_filecontents(
- codes=list(self.app.cell_manager.codes()),
- names=list(self.app.cell_manager.names()),
- cell_configs=list(self.app.cell_manager.configs()),
- config=self.app.config,
- )
- return contents
+ return MarimoConvert.from_ir(self.app.to_ir()).to_py()
def _is_unnamed(self) -> bool:
return self.filename is None
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 8ec7d981ae..598929a75b 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -229,7 +229,7 @@ def serialize_notebook(
)
return NotebookV1(
- version=VERSION,
+ version="1",
metadata=NotebookMetadata(marimo_version=__version__),
cells=cells,
)
diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.py
index 99e9a3e3c6..fbc24a78e5 100644
--- a/marimo/_utils/inline_script_metadata.py
+++ b/marimo/_utils/inline_script_metadata.py
@@ -208,7 +208,7 @@ def is_marimo_dependency(dependency: str) -> bool:
def get_headers_from_markdown(contents: str) -> dict[str, str]:
- from marimo._cli.convert.markdown import extract_frontmatter
+ from marimo._convert.markdown.markdown import extract_frontmatter
frontmatter, _ = extract_frontmatter(contents)
return get_headers_from_frontmatter(frontmatter)
diff --git a/openapi/src/notebook.ts b/openapi/src/notebook.ts
index 3af874562a..835d6045a9 100644
--- a/openapi/src/notebook.ts
+++ b/openapi/src/notebook.ts
@@ -10,25 +10,26 @@ export interface components {
NotebookCell: {
code: string | null;
config: {
- column: number | null;
- disabled: boolean | null;
- hide_code: boolean | null;
+ column?: number | null;
+ disabled?: boolean | null;
+ hide_code?: boolean | null;
};
- id: string;
+ id: string | null;
name: string | null;
};
NotebookCellConfig: {
- column: number | null;
- disabled: boolean | null;
- hide_code: boolean | null;
+ column?: number | null;
+ disabled?: boolean | null;
+ hide_code?: boolean | null;
};
NotebookMetadata: {
- marimo_version: string | null;
+ marimo_version?: string | null;
};
NotebookV1: {
cells: components["schemas"]["NotebookCell"][];
metadata: components["schemas"]["NotebookMetadata"];
- version: string;
+ /** @enum {string} */
+ version: "1";
};
};
responses: never;
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index ca2672274e..0342558cce 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -3,11 +3,10 @@ from __future__ import annotations
import json
import os
-import tempfile
from functools import partial
from inspect import cleandoc
from textwrap import dedent
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional
import codegen_data.test_main as mod
import pytest
@@ -18,6 +17,10 @@ from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
from marimo._ast.names import is_internal_cell_name
+from marimo._schemas.notebook import NotebookV1
+
+if TYPE_CHECKING:
+ from pathlib import Path
compile_cell = partial(compiler.compile_cell, cell_id="0")
@@ -77,11 +80,11 @@ def get_idempotent_marimo_source(name: str) -> str:
app = load.load_app(path)
header_comments = codegen.get_header_comments(path)
generated_contents = codegen.generate_filecontents(
- list(app._cell_manager.codes()),
- list(app._cell_manager.names()),
- list(app._cell_manager.configs()),
- app._config,
- header_comments,
+ codes=list(app._cell_manager.codes()),
+ names=list(app._cell_manager.names()),
+ cell_configs=list(app._cell_manager.configs()),
+ config=app._config,
+ header_comments=header_comments,
)
generated_contents = sanitized_version(generated_contents)
@@ -593,27 +596,21 @@ class TestToFunctionDef:
assert fndef == expected
-def test_recover() -> None:
- cells = {
+def test_recover(tmp_path: Path) -> None:
+ cells: NotebookV1 = {
+ "version": "1",
+ "metadata": {"marimo_version": __version__},
"cells": [
{"name": "a", "code": '"santa"\n\n"clause"\n\n\n'},
{"name": "b", "code": ""},
{"name": "c", "code": "\n123"},
- ]
+ ],
}
filecontents = json.dumps(cells)
# keep open for windows compat
- tempfile_name = ""
- with tempfile.NamedTemporaryFile(
- mode="w", suffix=".py", delete=False
- ) as f:
- f.write(filecontents)
- f.seek(0)
- tempfile_name = f.name
- try:
- recovered = codegen.recover(tempfile_name)
- finally:
- os.remove(tempfile_name)
+ tempfile_name = tmp_path / "test.py"
+ tempfile_name.write_text(filecontents)
+ recovered = codegen.recover(tempfile_name)
codes = [
"\n".join(['"santa"', "", '"clause"', "", "", ""]),
diff --git a/tests/_ast/test_parse.py b/tests/_ast/test_parse.py
index d61acfb27f..9222058e13 100644
--- a/tests/_ast/test_parse.py
+++ b/tests/_ast/test_parse.py
@@ -1,15 +1,15 @@
# Copyright 2025 Marimo. All rights reserved.
from __future__ import annotations
-import os
+from pathlib import Path
from marimo._ast.parse import Parser, parse_notebook
-DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+DIR_PATH = Path(__file__).parent
-def get_filepath(name: str) -> str:
- return os.path.join(DIR_PATH, f"codegen_data/{name}.py")
+def get_filepath(name: str) -> Path:
+ return DIR_PATH / f"codegen_data/{name}.py"
# NB. Some barebones testing at the areas that seemed to be most sensitive.
@@ -17,7 +17,7 @@ def get_filepath(name: str) -> str:
class TestParser:
@staticmethod
def test_parse_codes() -> None:
- parser = Parser(get_filepath("test_generate_filecontents"))
+ parser = Parser.from_file(get_filepath("test_generate_filecontents"))
body = parser.node_stack()
body_result = parser.parse_body(body)
assert body_result
@@ -33,7 +33,7 @@ class TestParser:
@staticmethod
def test_parse_setup_blank() -> None:
- parser = Parser(get_filepath("test_get_setup_blank"))
+ parser = Parser.from_file(get_filepath("test_get_setup_blank"))
body = parser.node_stack()
_ = parser.parse_header(body)
setup_result = parser.parse_setup(body)
@@ -45,7 +45,7 @@ class TestParser:
@staticmethod
def test_parse_codes_toplevel() -> None:
notebook = parse_notebook(
- get_filepath("test_generate_filecontents_toplevel")
+ get_filepath("test_generate_filecontents_toplevel").read_text()
)
assert notebook
assert notebook.header.value.startswith(
@@ -73,7 +73,7 @@ class TestParser:
@staticmethod
def test_parse_app_with_only_comments() -> None:
- parser = Parser(get_filepath("test_app_with_only_comments"))
+ parser = Parser.from_file(get_filepath("test_app_with_only_comments"))
body = parser.node_stack()
header_result = parser.parse_header(body)
assert header_result
@@ -83,7 +83,9 @@ class TestParser:
@staticmethod
def test_just_app() -> None:
- notebook = parse_notebook(get_filepath("test_get_app_kwargs"))
+ notebook = parse_notebook(
+ get_filepath("test_get_app_kwargs").read_text()
+ )
# No generated with, or run guard
assert len(notebook.violations) == 2
assert "generated_with" in notebook.violations[0].description
@@ -92,7 +94,7 @@ class TestParser:
@staticmethod
def test_parse_messy_toplevel() -> None:
notebook = parse_notebook(
- get_filepath("test_get_codes_messy_toplevel")
+ get_filepath("test_get_codes_messy_toplevel").read_text()
)
assert notebook
# unexpected statements and a missing run guard
diff --git a/tests/_cli/snapshots/markdown_to_marimo.txt b/tests/_cli/snapshots/markdown_to_marimo.txt
index 5d452464f1..7f7a29a050 100644
--- a/tests/_cli/snapshots/markdown_to_marimo.txt
+++ b/tests/_cli/snapshots/markdown_to_marimo.txt
@@ -18,3 +18,4 @@ def _(mo):
if __name__ == "__main__":
app.run()
+
diff --git a/tests/_cli/snapshots/remote_markdown_to_marimo.txt b/tests/_cli/snapshots/remote_markdown_to_marimo.txt
index 4eaa998e14..74d88bff82 100644
--- a/tests/_cli/snapshots/remote_markdown_to_marimo.txt
+++ b/tests/_cli/snapshots/remote_markdown_to_marimo.txt
@@ -20,3 +20,4 @@ def _(mo):
if __name__ == "__main__":
app.run()
+
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index fa4e09afa1..8cb12308e3 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -115,7 +115,9 @@ def _check_started(port: int, host: str = "localhost") -> Optional[bytes]:
def _temp_run_file(directory: tempfile.TemporaryDirectory[str]) -> str:
filecontents = codegen.generate_filecontents(
- ["import marimo as mo"], ["one"], cell_configs=[CellConfig()]
+ codes=["import marimo as mo"],
+ names=["one"],
+ cell_configs=[CellConfig()],
)
path = Path(directory.name) / "run.py"
path.write_text(filecontents, encoding="utf-8")
diff --git a/tests/_cli/test_cli_convert.py b/tests/_cli/test_cli_convert.py
index ef6402622f..20282d42d4 100644
--- a/tests/_cli/test_cli_convert.py
+++ b/tests/_cli/test_cli_convert.py
@@ -21,7 +21,7 @@ snapshot = snapshotter(__file__)
# HTTP server for testing remote file conversion
-class TestHTTPServer:
+class MockHTTPServer:
def __init__(self, directory: Path, port: int):
self.directory = directory
self.port = port
@@ -60,7 +60,7 @@ class TestHTTPServer:
def http_server():
tmp_path = tempfile.mkdtemp()
port = find_free_port(1234)
- server = TestHTTPServer(Path(tmp_path), port=port)
+ server = MockHTTPServer(Path(tmp_path), port=port)
server.start()
yield server
server.stop()
@@ -170,7 +170,7 @@ print('Hello from Markdown!')
assert "File must be an .ipynb or .md file" in p.stderr
@staticmethod
- def test_convert_remote_ipynb(http_server: TestHTTPServer) -> None:
+ def test_convert_remote_ipynb(http_server: MockHTTPServer) -> None:
# Create a notebook file
notebook_path = http_server.directory / "remote_notebook.ipynb"
notebook_content = """
@@ -213,7 +213,7 @@ print('Hello from Markdown!')
is_windows(),
reason="Markdown conversion adds extra new line on Windows",
)
- def test_convert_remote_markdown(http_server: TestHTTPServer) -> None:
+ def test_convert_remote_markdown(http_server: MockHTTPServer) -> None:
# Create a markdown file
md_path = http_server.directory / "remote_markdown.md"
md_content = """
@@ -241,7 +241,7 @@ print('Hello from Remote Markdown!')
snapshot("remote_markdown_to_marimo.txt", output)
@staticmethod
- def test_convert_remote_invalid_file(http_server: TestHTTPServer) -> None:
+ def test_convert_remote_invalid_file(http_server: MockHTTPServer) -> None:
# Create an invalid file
invalid_file = http_server.directory / "invalid.txt"
invalid_file.write_text(
@@ -259,7 +259,7 @@ print('Hello from Remote Markdown!')
@staticmethod
def test_convert_nonexistent_remote_file(
- http_server: TestHTTPServer,
+ http_server: MockHTTPServer,
) -> None:
# Try to convert non-existent remote file
p = subprocess.run(
diff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_convert/snapshots/dataflow.md.txt
similarity index 100%
rename from tests/_cli/snapshots/dataflow.md.txt
rename to tests/_convert/snapshots/dataflow.md.txt
diff --git a/tests/_cli/snapshots/frontmatter-only.py.txt b/tests/_convert/snapshots/frontmatter-only.py.txt
similarity index 88%
rename from tests/_cli/snapshots/frontmatter-only.py.txt
rename to tests/_convert/snapshots/frontmatter-only.py.txt
index 59bff4f87b..9282a614bd 100644
--- a/tests/_cli/snapshots/frontmatter-only.py.txt
+++ b/tests/_convert/snapshots/frontmatter-only.py.txt
@@ -8,4 +8,4 @@ app = marimo.App(app_title="My Title")
if __name__ == "__main__":
- app.run()
\ No newline at end of file
+ app.run()
diff --git a/tests/_cli/snapshots/frontmatter-test.py.txt b/tests/_convert/snapshots/frontmatter-test.py.txt
similarity index 95%
rename from tests/_cli/snapshots/frontmatter-test.py.txt
rename to tests/_convert/snapshots/frontmatter-test.py.txt
index 201e5bc2a1..6f93ed8d66 100644
--- a/tests/_cli/snapshots/frontmatter-test.py.txt
+++ b/tests/_convert/snapshots/frontmatter-test.py.txt
@@ -24,4 +24,4 @@ def _():
if __name__ == "__main__":
- app.run()
\ No newline at end of file
+ app.run()
diff --git a/tests/_cli/snapshots/has-header.md.txt b/tests/_convert/snapshots/has-header.md.txt
similarity index 100%
rename from tests/_cli/snapshots/has-header.md.txt
rename to tests/_convert/snapshots/has-header.md.txt
diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_convert/snapshots/marimo_for_jupyter_users.md.txt
similarity index 100%
rename from tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
rename to tests/_convert/snapshots/marimo_for_jupyter_users.md.txt
diff --git a/tests/_cli/snapshots/no-frontmatter.py.txt b/tests/_convert/snapshots/no-frontmatter.py.txt
similarity index 96%
rename from tests/_cli/snapshots/no-frontmatter.py.txt
rename to tests/_convert/snapshots/no-frontmatter.py.txt
index d33114d915..00297ae7c9 100644
--- a/tests/_cli/snapshots/no-frontmatter.py.txt
+++ b/tests/_convert/snapshots/no-frontmatter.py.txt
@@ -32,4 +32,4 @@ def _(mo):
if __name__ == "__main__":
- app.run()
\ No newline at end of file
+ app.run()
diff --git a/tests/_cli/snapshots/sql-notebook.py.txt b/tests/_convert/snapshots/sql-notebook.py.txt
similarity index 97%
rename from tests/_cli/snapshots/sql-notebook.py.txt
rename to tests/_convert/snapshots/sql-notebook.py.txt
index db02b584ed..3c9acf931b 100644
--- a/tests/_cli/snapshots/sql-notebook.py.txt
+++ b/tests/_convert/snapshots/sql-notebook.py.txt
@@ -39,4 +39,4 @@ def _(export, mo):
if __name__ == "__main__":
- app.run()
\ No newline at end of file
+ app.run()
diff --git a/tests/_cli/snapshots/sql.md.txt b/tests/_convert/snapshots/sql.md.txt
similarity index 100%
rename from tests/_cli/snapshots/sql.md.txt
rename to tests/_convert/snapshots/sql.md.txt
diff --git a/tests/_cli/snapshots/unsafe-app.md.txt b/tests/_convert/snapshots/unsafe-app.md.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-app.md.txt
rename to tests/_convert/snapshots/unsafe-app.md.txt
diff --git a/tests/_cli/snapshots/unsafe-app.py.txt b/tests/_convert/snapshots/unsafe-app.py.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-app.py.txt
rename to tests/_convert/snapshots/unsafe-app.py.txt
diff --git a/tests/_cli/snapshots/unsafe-doc-old.md.txt b/tests/_convert/snapshots/unsafe-doc-old.md.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-doc-old.md.txt
rename to tests/_convert/snapshots/unsafe-doc-old.md.txt
diff --git a/tests/_cli/snapshots/unsafe-doc-old.py.txt b/tests/_convert/snapshots/unsafe-doc-old.py.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-doc-old.py.txt
rename to tests/_convert/snapshots/unsafe-doc-old.py.txt
diff --git a/tests/_cli/snapshots/unsafe-doc.md.txt b/tests/_convert/snapshots/unsafe-doc.md.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-doc.md.txt
rename to tests/_convert/snapshots/unsafe-doc.md.txt
diff --git a/tests/_cli/snapshots/unsafe-doc.py.txt b/tests/_convert/snapshots/unsafe-doc.py.txt
similarity index 100%
rename from tests/_cli/snapshots/unsafe-doc.py.txt
rename to tests/_convert/snapshots/unsafe-doc.py.txt
diff --git a/tests/_convert/test_convert_utils.py b/tests/_convert/test_convert_utils.py
index 93906800a9..83278072f8 100644
--- a/tests/_convert/test_convert_utils.py
+++ b/tests/_convert/test_convert_utils.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
from textwrap import dedent
+from marimo._ast import codegen
from marimo._ast.cell import CellConfig
from marimo._convert import utils
@@ -26,7 +27,11 @@ def test_markdown_to_marimo():
def test_generate_from_sources():
# Test with basic sources
sources = ["print('Hello')", "x = 5"]
- result = utils.generate_from_sources(sources=sources)
+ result = codegen.generate_filecontents(
+ codes=sources,
+ names=["_", "_"],
+ cell_configs=[CellConfig(), CellConfig()],
+ )
result = re.sub(r"__generated_with = .*", "", result)
assert result == dedent(
@@ -58,8 +63,10 @@ if __name__ == "__main__":
def test_generate_from_sources_with_cell_configs():
sources = ["print('Hello')", "x = 5"]
cell_configs = [CellConfig(hide_code=True), CellConfig(hide_code=False)]
- result = utils.generate_from_sources(
- sources=sources, cell_configs=cell_configs
+ result = codegen.generate_filecontents(
+ codes=sources,
+ names=["_", "_"],
+ cell_configs=cell_configs,
)
result = re.sub(r"__generated_with = .*", "", result)
assert result == dedent(
diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_convert/test_ipynb_to_marimo.py
similarity index 74%
rename from tests/_cli/test_ipynb_to_marimo.py
rename to tests/_convert/test_ipynb_to_marimo.py
index 41c2603f27..394c2feab4 100644
--- a/tests/_cli/test_ipynb_to_marimo.py
+++ b/tests/_convert/test_ipynb_to_marimo.py
@@ -6,7 +6,8 @@ from pathlib import Path
import pytest
-from marimo._convert.ipynb import convert_from_ipynb
+from marimo._convert.converters import MarimoConvert
+from marimo._convert.ipynb import convert_from_ipynb_to_notebook_ir
from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
@@ -17,7 +18,9 @@ DIR_PATH = Path(__file__).parent / "ipynb_data"
@pytest.mark.parametrize("ipynb_path", DIR_PATH.glob("*.ipynb.txt"))
def test_ipynb_to_marimo_snapshots(ipynb_path: Path) -> None:
contents = ipynb_path.read_text()
- converted = convert_from_ipynb(contents)
+ ir = convert_from_ipynb_to_notebook_ir(contents)
+ converted = MarimoConvert.from_ir(ir).to_py()
+
converted = re.sub(r"__generated_with = .*\n", "", converted)
converted = re.sub(r"# requires-python = .*\n", "", converted)
snapshot(
diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_convert/test_markdown_conversion.py
similarity index 93%
rename from tests/_cli/test_markdown_conversion.py
rename to tests/_convert/test_markdown_conversion.py
index 0d3cf2163f..56f954ab91 100644
--- a/tests/_cli/test_markdown_conversion.py
+++ b/tests/_convert/test_markdown_conversion.py
@@ -11,10 +11,8 @@ import pytest
from marimo import __version__
from marimo._ast.app import InternalApp
-from marimo._cli.convert.markdown import (
- convert_from_md,
- convert_from_md_to_app,
-)
+from marimo._convert.converters import MarimoConvert
+from marimo._convert.markdown.markdown import convert_from_md_to_app
from marimo._server.export import export_as_md
from marimo._server.export.utils import format_filename_title
@@ -34,6 +32,12 @@ DIR_PATH = os.path.dirname(os.path.realpath(__file__))
snapshot = snapshotter(__file__)
+def md_to_py(md: str) -> str:
+ if not md:
+ return ""
+ return MarimoConvert.from_md(md).to_py()
+
+
def sanitized_version(output: str) -> str:
return output.replace(__version__, "0.0.0")
@@ -80,7 +84,7 @@ def test_idempotent_markdown_to_marimo() -> None:
for script in modules.keys():
with open(DIR_PATH + f"/snapshots/{script}.md.txt") as f:
md = f.read()
- python_source = sanitized_version(convert_from_md(md))
+ python_source = sanitized_version(md_to_py(md))
assert convert_from_py(python_source) == md.strip()
@@ -110,7 +114,7 @@ def test_markdown_frontmatter() -> None:
)
# As python file
- output = sanitized_version(convert_from_md(script))
+ output = sanitized_version(md_to_py(script))
assert 'app_title="My Title"' in output
assert output.startswith("#!/usr/bin/env python")
snapshot("frontmatter-test.py.txt", output)
@@ -143,7 +147,7 @@ def test_no_frontmatter() -> None:
"""
)
)
- output = sanitized_version(convert_from_md(script))
+ output = sanitized_version(md_to_py(script))
snapshot("no-frontmatter.py.txt", output)
# As python object
@@ -170,7 +174,7 @@ def test_markdown_just_frontmatter() -> None:
"""
)
)
- output = sanitized_version(convert_from_md(script))
+ output = sanitized_version(md_to_py(script))
assert 'app_title="My Title"' in output
snapshot("frontmatter-only.py.txt", output)
@@ -211,7 +215,7 @@ def test_markdown_with_sql() -> None:
"""
)
)
- output = sanitized_version(convert_from_md(script))
+ output = sanitized_version(md_to_py(script))
snapshot("sql-notebook.py.txt", output)
# As python object
@@ -233,7 +237,7 @@ def test_markdown_with_sql() -> None:
def test_markdown_empty() -> None:
- assert convert_from_md("") == ""
+ assert md_to_py("") == ""
# As python object
app = InternalApp(convert_from_md_to_app(""))
@@ -345,7 +349,7 @@ def test_python_to_md_code_injection() -> None:
)
)
maybe_unsafe_md = convert_from_py(unsafe_app).strip()
- maybe_unsafe_py = convert_from_md(maybe_unsafe_md).strip()
+ maybe_unsafe_py = md_to_py(maybe_unsafe_md).strip()
snapshot("unsafe-app.py.txt", maybe_unsafe_py)
snapshot("unsafe-app.md.txt", maybe_unsafe_md)
@@ -435,12 +439,15 @@ def test_old_md_to_python_code_injection() -> None:
)
)
- maybe_unsafe_py = sanitized_version(convert_from_md(script).strip())
+ maybe_unsafe_py = sanitized_version(md_to_py(script).strip())
+ assert "Casually malicious md" in maybe_unsafe_py
+
maybe_unsafe_md = convert_from_py(maybe_unsafe_py)
+ assert "Casually malicious md" in maybe_unsafe_md
# Idempotent even under strange conditions.
assert maybe_unsafe_py == sanitized_version(
- convert_from_md(maybe_unsafe_md).strip()
+ md_to_py(maybe_unsafe_md).strip()
)
snapshot("unsafe-doc-old.py.txt", maybe_unsafe_py)
@@ -522,12 +529,12 @@ def test_md_to_python_code_injection() -> None:
)
)
- maybe_unsafe_py = sanitized_version(convert_from_md(script).strip())
+ maybe_unsafe_py = sanitized_version(md_to_py(script).strip())
maybe_unsafe_md = convert_from_py(maybe_unsafe_py)
# Idempotent even under strange conditions.
assert maybe_unsafe_py == sanitized_version(
- convert_from_md(maybe_unsafe_md).strip()
+ md_to_py(maybe_unsafe_md).strip()
)
snapshot("unsafe-doc.py.txt", maybe_unsafe_py)
diff --git a/tests/mocks.py b/tests/mocks.py
index 87e261162c..340b99c736 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -1,10 +1,11 @@
from __future__ import annotations
import difflib
-import os
from pathlib import Path
from typing import Callable
+import pytest
+
from marimo import __version__
from marimo._utils.paths import maybe_make_dirs
@@ -37,21 +38,19 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:
result = normalize(result)
# If doesn't exist, create snapshot
- if not os.path.exists(filepath):
- with open(filepath, "w") as f:
- f.write(result)
+ if not filepath.exists():
+ filepath.write_text(result)
print("Snapshot updated")
+ return
# Read snapshot
- with open(filepath) as f:
- expected = normalize(f.read())
+ expected = normalize(filepath.read_text())
assert result, "Result is empty"
assert expected, "Expected is empty"
def write_result() -> None:
- with open(filepath, "w") as f:
- f.write(result)
+ filepath.write_text(result)
is_json = filename.endswith(".json")
if is_json:
@@ -76,11 +75,16 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:
)
)
- if text_diff != "":
+ if result != expected:
write_result()
print("Snapshot updated")
- assert result == expected, f"Snapshot differs:\n{text_diff}"
+ # If the snapshot only differs by whitespace,
+ # provide a more helpful error message.
+ if result.strip() == expected.strip():
+ print("Snapshot only differs by whitespace (.strip())")
+
+ pytest.fail(f"Snapshot differs: '{text_diff}'")
return snapshot