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
Persist comment headers while resaving notebooks (#728)
Mohamad Fakhouri4ef347eb4bd8
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex cefc217a92..ab05687794 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -1,9 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import astimport builtinsimport importlib.utilimport json+import osfrom collections.abc import Sequencefrom typing import Any, List, Optional, Union, cast@@ -245,3 +247,40 @@ def recover(filename: str) -> str:cast(List[str], names),cast(List[CellConfig], configs),)+++def get_header_comments(filename: str) -> Optional[str]:+ """Gets the header comments from a file. Returns+ None if the file does not exist or the header is+ invalid, which is determined by:+ 1. If the file is does not contain the marimo+ import statement+ 2. If the section before the marimo import+ statement contains any non-comment code+ """++ def is_multiline_comment(node: ast.stmt) -> bool:+ """Checks if a node is a docstring or a multiline comment."""+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):+ return True+ return False++ if not os.path.exists(filename):+ return None++ with open(filename, "r", encoding="utf-8") as f:+ contents = f.read()++ if "import marimo" not in contents:+ return None++ header, _ = contents.split("import marimo", 1)++ # Ensure the header only contains non-executable code+ # ast parses out single line comments, so we only+ # need to check that every node is not a multiline comment+ module = ast.parse(header)+ if any(not is_multiline_comment(node) for node in module.body):+ return None++ return headerdiff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex 11f79d23ae..937e11ee6f 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -238,7 +238,10 @@ async def save()LOGGER.debug("Saving app to %s", filename)try:+ header_comments = codegen.get_header_comments(filename)with open(filename, "w", encoding="utf-8") as f:+ if header_comments:+ f.write(header_comments.rstrip() + "\n\n")f.write(contents)except Exception as e:raise HTTPException(diff --git a/tests/_ast/codegen_data/test_get_header_comments.py b/tests/_ast/codegen_data/test_get_header_comments.pynew file mode 100644index 0000000000..0b39da39f2--- /dev/null+++ b/tests/_ast/codegen_data/test_get_header_comments.py@@ -0,0 +1,27 @@+"""Docstring"""++"""multi+ line+"""++# A copyright license++# A linter/formatter directive++import marimo++__generated_with = "0.1.0"+app = marimo.App()+++def one(): return+++def two():+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_ast/codegen_data/test_get_header_comments_invalid.py b/tests/_ast/codegen_data/test_get_header_comments_invalid.pynew file mode 100644index 0000000000..6f4830c39a--- /dev/null+++ b/tests/_ast/codegen_data/test_get_header_comments_invalid.py@@ -0,0 +1,30 @@+"""Docstring"""++"""+This is an invalid header since there is+ a statement before the import marmio command+"""++print("Hello World")++# A copyright license++# A linter/formatter directive++import marimo++__generated_with = "0.1.0"+app = marimo.App()+++def one(): return+++def two():+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 1b3745361c..57e1b62ce1 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -428,3 +428,21 @@ def test_recover() -> None:# TODO(akshayka): more tests for attributes, classdefs, and closures# TODO(akshayka): test builtin functions# TODO(akshayka): test delete cell+++def test_get_header_comments() -> None:+ filepath = get_filepath("test_get_header_comments")+ comments = codegen.get_header_comments(filepath)++ assert comments, "No comments found"+ assert '"""Docstring"""' in comments, "Docstring not found"+ assert '"""multi\n line\n"""' in comments, "Multiline string not found"+ assert "# A copyright" in comments, "Comment not found"+ assert "# A linter" in comments, "Comment not found"+++def test_get_header_comments_invalid() -> None:+ filepath = get_filepath("test_get_header_comments_invalid")+ comments = codegen.get_header_comments(filepath)++ assert comments is None, "Comments found when there should be none"diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 83dae8f08d..3c9665b7b2 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -106,6 +106,88 @@ def test_save_file(client: TestClient) -> None:)+@with_session(SESSION_ID)+def test_save_with_header(client: TestClient) -> None:+ filename = get_session_manager(client).filename+ assert filename+ assert os.path.exists(filename)++ header = (+ '"""This is a docstring"""\n\n' + "# Copyright 2024\n# Linter ignore\n"+ )+ # Prepend a header to the file+ contents = open(filename).read()+ contents = header + contents+ open(filename, "w", encoding="UTF-8").write(contents)++ response = client.post(+ "/api/kernel/save",+ headers=HEADERS,+ json={+ "cell_ids": ["1"],+ "filename": filename,+ "codes": ["import marimo as mo"],+ "names": ["my_cell"],+ "configs": [+ {+ "hideCode": True,+ "disabled": False,+ }+ ],+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["success"] is True+ file_contents = open(filename).read()+ assert "import marimo as mo" in file_contents+ assert file_contents.startswith(header.rstrip()), "Header was removed"+ assert "@app.cell(hide_code=True)" in file_contents+ assert "my_cell" in file_contents+++@with_session(SESSION_ID)+def test_save_with_invalid_file(client: TestClient) -> None:+ filename = get_session_manager(client).filename+ assert filename+ assert os.path.exists(filename)++ header = (+ '"""This is a docstring"""\n\n'+ + 'print("dont do this!")\n'+ + "# Linter ignore\n"+ )++ # Prepend a header to the file+ contents = open(filename).read()+ contents = header + contents+ open(filename, "w", encoding="UTF-8").write(contents)++ response = client.post(+ "/api/kernel/save",+ headers=HEADERS,+ json={+ "cell_ids": ["1"],+ "filename": filename,+ "codes": ["import marimo as mo"],+ "names": ["my_cell"],+ "configs": [+ {+ "hideCode": True,+ "disabled": False,+ }+ ],+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["success"] is True+ file_contents = open(filename).read()+ assert file_contents.startswith("import marimo"), "Header was not removed"+ assert "@app.cell(hide_code=True)" in file_contents+ assert "my_cell" in file_contents++@with_session(SESSION_ID)def test_save_file_cannot_rename(client: TestClient) -> None:response = client.post(