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.

feat: edit --convert to open unknown file types (#5875)

Dylan Madisetti4adf2a6c023b
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 9fa60e4794..b54929ba69 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -56,7 +56,7 @@ def helpful_usage_error(self: Any, file: Any = None) -> None:
click.echo(self.ctx.get_help(), file=file, color=color)
-def check_app_correctness(filename: str) -> None:
+def check_app_correctness(filename: str, noninteractive: bool = True) -> None:
try:
status = get_notebook_status(filename)
except SyntaxError:
@@ -85,7 +85,8 @@ def check_app_correctness(filename: str) -> None:
) from None
# Only show the tip if we're in an interactive terminal
- if status == "invalid" and sys.stdin.isatty():
+ interactive = sys.stdin.isatty() and not noninteractive
+ if status == "invalid" and interactive:
click.echo(
green("tip")
+ ": Use `"
@@ -109,6 +110,26 @@ def check_app_correctness(filename: str) -> None:
)
+def check_app_correctness_or_convert(filename: str) -> None:
+ from marimo._convert.converters import MarimoConvert
+
+ file = Path(filename)
+ code = file.read_text(encoding="utf-8")
+ try:
+ return check_app_correctness(filename, noninteractive=True)
+ except click.ClickException:
+ # A click exception is raised if a python script could not be converted
+ code = MarimoConvert.from_non_marimo_python_script(
+ source=code, aggressive=True
+ ).to_py()
+ except SyntaxError:
+ # The file could not even be read as python
+ code = MarimoConvert.from_plain_text(source=code).to_py()
+ file.write_text(code, encoding="utf-8")
+
+ file.write_text(code, encoding="utf-8")
+
+
click.exceptions.UsageError.show = helpful_usage_error # type: ignore
@@ -398,6 +419,14 @@ edit_help_msg = "\n".join(
hidden=True,
help="Remote URL for runtime configuration.",
)
+ "--convert",
+ is_flag=True,
+ default=False,
+ type=bool,
+ hidden=True,
+ help="When opening a .py file, enable fallback conversion from pypercent, script, or text.",
+)
@click.argument(
"name",
required=False,
@@ -419,6 +448,7 @@ def edit(
watch: bool,
skew_protection: bool,
remote_url: Optional[str],
+ convert: bool,
name: Optional[str],
args: tuple[str, ...],
) -> None:
@@ -474,7 +504,10 @@ def edit(
if os.path.exists(name) and not is_dir:
# module correctness check - don't start the server
# if we can't import the module
- check_app_correctness(name)
+ if convert:
+ check_app_correctness_or_convert(name)
+ else:
+ check_app_correctness(name)
elif not is_dir:
# write empty file
try:
diff --git a/marimo/_convert/converters.py b/marimo/_convert/converters.py
index 1612571132..b72edc356d 100644
--- a/marimo/_convert/converters.py
+++ b/marimo/_convert/converters.py
@@ -52,6 +52,7 @@ class MarimoConvert:
@staticmethod
def from_non_marimo_python_script(
source: str,
+ aggressive: bool = False,
) -> MarimoConverterIntermediate:
"""Convert from a non-marimo Python script to marimo notebook.
@@ -60,13 +61,39 @@ class MarimoConvert:
Args:
source: Unknown Python script source code string
+ aggressive: If True, will attempt to convert aggressively,
+ turning even invalid text into a notebook.
"""
from marimo._convert.non_marimo_python_script import (
convert_non_marimo_python_script_to_notebook_ir,
+ convert_non_marimo_script_to_notebook_ir,
+ )
+
+ if aggressive:
+ notebook_ir = convert_non_marimo_script_to_notebook_ir(source)
+ else:
+ notebook_ir = convert_non_marimo_python_script_to_notebook_ir(
+ source
+ )
+ return MarimoConvert.from_ir(notebook_ir)
+
+ @staticmethod
+ def from_plain_text(
+ source: str,
+ ) -> MarimoConverterIntermediate:
+ """Converts plain text into a single celled marimo notebook.
+
+ Used for cases with syntax errors or unparsable code.
+
+ Args:
+ source: Unknown source code string
+ """
+ from marimo._convert.non_marimo_python_script import (
+ convert_script_block_to_notebook_ir,
)
return MarimoConvert.from_ir(
- convert_non_marimo_python_script_to_notebook_ir(source)
+ convert_script_block_to_notebook_ir(source)
)
@staticmethod
diff --git a/marimo/_convert/non_marimo_python_script.py b/marimo/_convert/non_marimo_python_script.py
index c8559c8f0d..169bf90564 100644
--- a/marimo/_convert/non_marimo_python_script.py
+++ b/marimo/_convert/non_marimo_python_script.py
@@ -6,7 +6,66 @@ from __future__ import annotations
import json
from marimo._convert.ipynb import convert_from_ipynb_to_notebook_ir
-from marimo._schemas.serialization import NotebookSerialization
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ Header,
+ NotebookSerialization,
+ UnparsableCell,
+)
+
+
+def convert_pypercent_script_to_notebook_ir(
+ source: str,
+) -> NotebookSerialization:
+ """Convert a pypercent Python script into marimo notebook IR.
+
+ Converts pypercent to jupyter to marimo notebook IR using jupytext.
+ """
+ try:
+ import jupytext # type: ignore[import-untyped]
+ except ImportError as e:
+ raise ImportError(
+ "Converting py:percent format requires jupytext"
+ ) from e
+ notebook = jupytext.reads(source, fmt="py:percent")
+ notebook_str = json.dumps(notebook)
+
+ ir = convert_from_ipynb_to_notebook_ir(notebook_str)
+ _transform_main_blocks(ir)
+ return ir
+
+
+def convert_python_block_to_notebook_ir(
+ source: str,
+) -> NotebookSerialization:
+ """Convert a Python script block to marimo notebook IR.
+
+ This is used when the script is not in the notebook format.
+ """
+ notebook = {"cells": [{"source": source, "cell_type": "code"}]}
+ notebook_str = json.dumps(notebook)
+
+ ir = convert_from_ipynb_to_notebook_ir(notebook_str)
+ _transform_main_blocks(ir)
+ return ir
+
+
+def convert_script_block_to_notebook_ir(
+ source: str,
+) -> NotebookSerialization:
+ """Converts unknown script block to marimo notebook IR.
+
+ Puts all content into a single cell. Generally used for unparsable scripts.
+ """
+ return NotebookSerialization(
+ app=AppInstantiation(),
+ header=Header(value=""),
+ cells=[
+ UnparsableCell(
+ code=source,
+ )
+ ],
+ )
def convert_non_marimo_python_script_to_notebook_ir(
@@ -20,22 +79,31 @@ def convert_non_marimo_python_script_to_notebook_ir(
2. Otherwise, puts all content into a single cell
3. Preserves PEP 723 inline script metadata if present
"""
+
if "# %%" in source:
- try:
- import jupytext # type: ignore[import-untyped]
- except ImportError as e:
- raise ImportError(
- "Converting py:percent format requires jupytext"
- ) from e
- notebook = jupytext.reads(source, fmt="py:percent")
- else:
- notebook = {"cells": [{"source": source, "cell_type": "code"}]}
+ return convert_pypercent_script_to_notebook_ir(source)
+ return convert_python_block_to_notebook_ir(source)
- notebook_str = json.dumps(notebook)
- ir = convert_from_ipynb_to_notebook_ir(notebook_str)
- _transform_main_blocks(ir)
- return ir
+def convert_non_marimo_script_to_notebook_ir(
+ source: str,
+) -> NotebookSerialization:
+ """Convert a non-marimo script to marimo notebook IR.
+
+ This is a convenience function that turns any string into a
+ marimo notebook.
+ """
+ try:
+ return convert_non_marimo_python_script_to_notebook_ir(source)
+ except ImportError:
+ pass
+ try:
+ import ast
+
+ ast.parse(source) # Validate if it's valid Python code
+ return convert_python_block_to_notebook_ir(source)
+ except SyntaxError:
+ return convert_script_block_to_notebook_ir(source)
def _transform_main_blocks(ir: NotebookSerialization) -> None:
diff --git a/tests/_convert/test_convert_non_marimo_python_script.py b/tests/_convert/test_convert_non_marimo_python_script.py
index cae93d3939..18680196b4 100644
--- a/tests/_convert/test_convert_non_marimo_python_script.py
+++ b/tests/_convert/test_convert_non_marimo_python_script.py
@@ -3,6 +3,8 @@ import pytest
from marimo._convert.converters import MarimoConvert
from marimo._convert.non_marimo_python_script import (
convert_non_marimo_python_script_to_notebook_ir,
+ convert_non_marimo_script_to_notebook_ir,
+ convert_python_block_to_notebook_ir,
)
from marimo._dependencies.dependencies import DependencyManager
from tests.mocks import snapshotter
@@ -12,6 +14,140 @@ HAS_JUPYTEXT = DependencyManager.has("jupytext")
snapshot_test = snapshotter(__file__)
+class TestConvertNonMarimoScriptToNotebookIr:
+ """Test the convert_non_marimo_script_to_notebook_ir function."""
+
+ def test_python_script_success(self) -> None:
+ """Test successful Python script conversion."""
+ source = '''"""A simple Python script."""
+
+x = 5
+y = 10
+print(x + y)
+'''
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # CellDef objects don't have cell_type attribute
+ assert "print(x + y)" in ir.cells[0].code
+
+ @pytest.mark.skipif(not HAS_JUPYTEXT, reason="jupytext not installed")
+ def test_pypercent_script_success(self) -> None:
+ """Test successful pypercent script conversion."""
+ source = '''"""Pypercent format notebook."""
+
+# %%
+x = 1
+print(x)
+'''
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) > 0
+
+ @pytest.mark.skipif(
+ HAS_JUPYTEXT,
+ reason="Check failure occurs when jupytext is not available",
+ )
+ def test_pypercent_script_without_jupytext(self) -> None:
+ """Test pypercent script when jupytext is not available."""
+ source = '''"""Pypercent format notebook."""
+
+# %%
+x = 1
+print(x)
+'''
+ # Should fall back to Python block conversion
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # CellDef objects don't have cell_type attribute
+ assert "print(x)" in ir.cells[0].code
+
+ def test_invalid_python_syntax(self) -> None:
+ """Test script with invalid Python syntax."""
+ source = """This is not valid Python code
+def incomplete_function(
+ # Missing closing parenthesis
+"""
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # Should be an UnparsableCell
+ assert hasattr(ir.cells[0], "code")
+ # Strip trailing newlines for comparison
+ assert ir.cells[0].code.rstrip() == source.rstrip()
+
+ def test_bash_script(self) -> None:
+ """Test non-Python script (bash)."""
+ source = """#!/bin/bash
+echo "Hello World"
+for i in {1..5}; do
+ echo "Count: $i"
+done
+"""
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # Should be an UnparsableCell
+ assert hasattr(ir.cells[0], "code")
+ # Strip trailing newlines for comparison
+ assert ir.cells[0].code.rstrip() == source.rstrip()
+
+ def test_markdown_text(self) -> None:
+ """Test markdown text as script."""
+ source = """# My Document
+
+This is a markdown document with some content.
+
+## Section 1
+
+- Item 1
+- Item 2
+- Item 3
+
+## Section 2
+
+Some more content here.
+"""
+ ir = convert_non_marimo_script_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # Should be an UnparsableCell
+ assert hasattr(ir.cells[0], "code")
+ # Strip trailing newlines for comparison
+ assert ir.cells[0].code.rstrip() == source.rstrip()
+
+ def test_empty_python_block(self) -> None:
+ """Test empty Python block conversion."""
+ source = ""
+ ir = convert_python_block_to_notebook_ir(source)
+ assert ir.app is not None
+ assert len(ir.cells) == 1
+ # CellDef objects don't have cell_type attribute
+ assert ir.cells[0].code.strip() == ""
+
+ def test_basic_script_block(self) -> None:
+ """Test basic script block conversion."""
+ source = "This is some arbitrary text that is not Python code"
+ ir = MarimoConvert.from_plain_text(source).to_ir()
+ assert ir.app is not None
+ assert ir.header.value == ""
+ assert len(ir.cells) == 1
+ assert ir.cells[0].code == source
+
+ def test_script_block_with_special_characters(self) -> None:
+ """Test script block with special characters."""
+ source = """#!/bin/bash
+echo "Hello World"
+# This is a bash script, not Python
+"""
+ ir = MarimoConvert.from_non_marimo_python_script(
+ source, aggressive=True
+ ).to_ir()
+ assert len(ir.cells) == 1
+ assert ir.cells[0].code.strip() == source.strip()
+
+
class TestConvertNonMarimoPython:
"""Test conversion of non-marimo Python files to marimo notebooks."""