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
fix: prompt user to open invalid files (#5677)
Dylan Madisettiaee551e7c3a2
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.pyindex d8c54fc595..ab49e4c10a 100644--- a/marimo/_ast/load.py+++ b/marimo/_ast/load.py@@ -9,7 +9,7 @@ from typing import Literal, Optional, Unionfrom marimo import _loggersfrom marimo._ast.app import App, InternalAppfrom marimo._ast.parse import MarimoFileError, parse_notebook-from marimo._schemas.serialization import UnparsableCell+from marimo._schemas.serialization import NotebookSerialization, UnparsableCellLOGGER = _loggers.marimo_logger()@@ -23,6 +23,8 @@ LOGGER = _loggers.marimo_logger()# However for "managed" marimo (i.e. run/ edit), the expectation is to not fail# on startup and defer errors to the runtime.+NotebookStatus = Literal["empty", "has_errors", "invalid", "valid"]+def _maybe_contents(filename: Optional[Union[str, Path]]) -> Optional[str]:if filename is None:@@ -74,7 +76,7 @@ def _static_load(filepath: Path) -> Optional[App]:return app-def notebook_is_openable(filename: str) -> Literal[True]:+def get_notebook_status(filename: str) -> NotebookStatus:"""Attempts to parse an app- should raise SyntaxError on failure.Args:@@ -90,22 +92,32 @@ def notebook_is_openable(filename: str) -> Literal[True]:contents = _maybe_contents(filename)if not contents:- return True+ return "empty"+ notebook: Optional[NotebookSerialization] = Noneif path.suffix in (".md", ".qmd"):from marimo._convert.markdown.markdown import (convert_from_md_to_marimo_ir,)- _ = convert_from_md_to_marimo_ir(contents)- 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.")+ notebook = convert_from_md_to_marimo_ir(contents)+ elif path.suffix == ".py":+ notebook = parse_notebook(contents)+ else:+ raise MarimoFileError("File must end with .py, .md, or .qmd.")++ # NB. A invalid notebook can still be opened.+ if notebook is None:+ return "empty"+ if not notebook.valid:+ return "invalid"+ if len(notebook.violations) > 0:+ LOGGER.debug(+ "Notebook has violations: \n%s",+ "\n".join(map(repr, notebook.violations)),+ )+ return "has_errors"+ return "valid"def load_app(filename: Optional[str]) -> Optional[App]:diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.pyindex 163242ba84..09f779626b 100644--- a/marimo/_ast/parse.py+++ b/marimo/_ast/parse.py@@ -656,6 +656,39 @@ def extract_offsets_post_colon(return start_line, col_offset+def is_equal_ast(+ basis: Optional[Union[ast.AST, list[ast.AST]]],+ other: Optional[Union[ast.AST, list[ast.AST]]],+) -> bool:+ """Compare two AST nodes for equality."""+ if type(basis) is not type(other):+ return False+ elif basis is None or other is None:+ return basis == other+ elif isinstance(basis, list):+ assert isinstance(other, list)+ if len(basis) != len(other):+ return False+ return all(is_equal_ast(a, b) for a, b in zip(basis, other))++ for key, value in vars(basis).items():+ # Scrub positional data not relevant for comparison.+ if key in {+ "lineno",+ "end_lineno",+ "col_offset",+ "end_col_offset",+ "ctx",+ }:+ continue+ other_value = getattr(other, key, None)+ if isinstance(value, (ast.AST, list, type(None))):+ return is_equal_ast(value, other_value)+ elif value != other_value:+ return False+ return True++def get_valid_decorator(node: CellNode,) -> Optional[Union[ast.Attribute, ast.Call]]:@@ -780,10 +813,8 @@ def is_cell(node: Optional[Node]) -> bool:def is_run_guard(node: Optional[Node]) -> bool:- return bool(- node- and (node == ast.parse('if __name__ == "__main__": app.run()').body[0])- )+ basis = ast.parse('if __name__ == "__main__": app.run()').body[0]+ return bool(node and is_equal_ast(basis, node))def parse_notebook(contents: str) -> Optional[NotebookSerialization]:diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 48c318a310..80910fe3ee 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -14,7 +14,7 @@ import clickimport marimo._cli.cli_validators as validatorsfrom marimo import __version__, _loggersfrom marimo._ast import codegen-from marimo._ast.load import notebook_is_openable+from marimo._ast.load import get_notebook_statusfrom marimo._cli.config.commands import configfrom marimo._cli.convert.commands import convertfrom marimo._cli.development.commands import development@@ -22,7 +22,7 @@ from marimo._cli.envinfo import get_system_infofrom marimo._cli.export.commands import exportfrom marimo._cli.file_path import validate_namefrom marimo._cli.parse_args import parse_args-from marimo._cli.print import red+from marimo._cli.print import bold, green, redfrom marimo._cli.run_docker import (prompt_run_in_docker_container,)@@ -57,7 +57,7 @@ def helpful_usage_error(self: Any, file: Any = None) -> None:def check_app_correctness(filename: str) -> None:try:- notebook_is_openable(filename)+ status = get_notebook_status(filename)except SyntaxError:import traceback@@ -70,6 +70,28 @@ def check_app_correctness(filename: str) -> None:click.echo(f"Failed to parse notebook: {filename}\n", err=True)raise click.ClickException(traceback.format_exc(limit=0)) from None+ if status == "invalid":+ click.echo(+ green("tip")+ + ": Use `"+ + bold("marimo convert")+ + "` to convert existing scripts.",+ err=True,+ )+ click.confirm(+ (+ "The file is not detected as a marimo notebook, opening it may "+ "overwrite its contents.\nDo you want to open it anyway?"+ ),+ default=False,+ abort=True,+ )+ if status == "has_errors":+ # Provide a warning, but allow the user to open the notebook+ _loggers.marimo_logger().warning(+ "This notebook has errors, saving may lose data. Continuing anyway."+ )+click.exceptions.UsageError.show = helpful_usage_error # type: ignorediff --git a/tests/_ast/codegen_data/test_empty.py b/tests/_ast/codegen_data/test_empty.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py b/tests/_ast/codegen_data/test_get_codes_messy_toplevel.pyindex c7b6f8581a..18f2e5f207 100644--- a/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py+++ b/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py@@ -1,9 +1,7 @@import marimo-__generated_with = '0.1.0'app = marimo.App()-# We want a wrapper as a proof of concept. Note, that this will not serialize# in this form.def wrapper(func):@@ -28,7 +26,3 @@ def fn(a,@app.celldef wrapped():return---if __name__ == "__main__":- app.run()diff --git a/tests/_ast/codegen_data/test_invalid.py b/tests/_ast/codegen_data/test_invalid.pynew file mode 100644index 0000000000..f913379c7a--- /dev/null+++ b/tests/_ast/codegen_data/test_invalid.py@@ -0,0 +1 @@+print("Not a notebook")diff --git a/tests/_ast/codegen_data/test_main.py b/tests/_ast/codegen_data/test_main.pyindex f3c34f92c5..5ca8d27428 100644--- a/tests/_ast/codegen_data/test_main.py+++ b/tests/_ast/codegen_data/test_main.py@@ -1,29 +1,27 @@-from typing import Any, Tuple-import marimo-__generated_with = "0.1.0"+__generated_with = "0.14.11"app = marimo.App()@app.cell-def one() -> Tuple[Any]:- x = 0+def one():+ x: int = 0return (x,)@app.cell-def two(x: Any) -> Tuple[Any, Any]:- y = x + 1- z = y + 1+def two(x: int):+ y: int = x + 1+ z: int = y + 1"z"- return y, z+ return (y,)@app.cell-def three(x: Any, y: Any) -> Tuple[Any]:- a = x + y- return (a,)+def three(x: int, y: int):+ a: int = x + y+ returnif __name__ == "__main__":diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.pyindex 4267a6476c..3730efa58f 100644--- a/tests/_ast/test_load.py+++ b/tests/_ast/test_load.py@@ -285,3 +285,28 @@ class TestGetCodes:from codegen_data.test_with_bad_decorator import hundredassert hundred == 100+++class TestGetStatus:+ @staticmethod+ def test_get_status_valid() -> None:+ assert load.get_notebook_status(get_filepath("test_main")) == "valid"++ @staticmethod+ def test_get_status_empty() -> None:+ assert load.get_notebook_status(get_filepath("test_empty")) == "empty"++ @staticmethod+ def test_get_status_invalid() -> None:+ assert (+ load.get_notebook_status(get_filepath("test_invalid")) == "invalid"+ )++ @staticmethod+ def test_get_status_warn() -> None:+ assert (+ load.get_notebook_status(+ get_filepath("test_get_codes_messy_toplevel")+ )+ == "has_errors"+ )diff --git a/tests/_ast/test_parse.py b/tests/_ast/test_parse.pyindex 9222058e13..38901565b5 100644--- a/tests/_ast/test_parse.py+++ b/tests/_ast/test_parse.py@@ -15,6 +15,12 @@ def get_filepath(name: str) -> Path:# NB. Some barebones testing at the areas that seemed to be most sensitive.# Note that loader should cover these cases and more by proxy.class TestParser:+ @staticmethod+ def test_main() -> None:+ notebook = parse_notebook(get_filepath("test_main").read_text())+ # Should just work without any violations.+ assert len(notebook.violations) == 0+@staticmethoddef test_parse_codes() -> None:parser = Parser.from_file(get_filepath("test_generate_filecontents"))@@ -99,6 +105,6 @@ class TestParser:assert notebook# unexpected statements and a missing run guardassert len(notebook.violations) == 3- assert "statement" in notebook.violations[0].description+ assert "generated" in notebook.violations[0].descriptionassert "statement" in notebook.violations[1].descriptionassert "run guard" in notebook.violations[2].description