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
Ruff config discovery for notebook cell formatting (#8609)
Frank65108be71315
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex f9b08a39f3..cd701f50dd 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -134,13 +134,18 @@ async def format_cell(request: Request) -> FormatResponse:schema:$ref: "#/components/schemas/FormatResponse""""+ app_state = AppState(request)body = await parse_request(request, cls=FormatCellsRequest)formatter = DefaultFormatter(line_length=body.line_length)try:- return FormatResponse(codes=await formatter.format(body.codes))+ return FormatResponse(+ codes=await formatter.format(+ body.codes,+ stdin_filename=app_state.require_current_session().app_file_manager.path,+ )+ )except ModuleNotFoundError:- app_state = AppState(request)# Installation occurs in the kernel which is not useful for multi mode.if app_state.session_manager.sandbox_mode is SandboxMode.MULTI:# Re-raise without name so error handler won't send install notificationdiff --git a/marimo/_utils/formatter.py b/marimo/_utils/formatter.pyindex 2a75f59fc3..2c9a5b83a0 100644--- a/marimo/_utils/formatter.py+++ b/marimo/_utils/formatter.py@@ -59,7 +59,9 @@ async def _run_subprocess_safe(return await asyncio.to_thread(run_sync)-async def ruff(codes: CellCodes, *cmd: str) -> CellCodes:+async def ruff(+ codes: CellCodes, *cmd: str, stdin_filename: str | None = None+) -> CellCodes:# Try with sys.executable firstruff_cmd = [sys.executable, "-m", "ruff"]stdout, _stderr, returncode = await _run_subprocess_safe(@@ -80,8 +82,13 @@ async def ruff(codes: CellCodes, *cmd: str) -> CellCodes:formatted_codes: CellCodes = {}for key, code in codes.items():try:+ command = [*ruff_cmd, *cmd]+ if stdin_filename:+ command.extend(["--stdin-filename", stdin_filename])+ command.append("-")+stdout, _stderr, returncode = await _run_subprocess_safe(- *ruff_cmd, *cmd, "-", input_data=code.encode()+ *command, input_data=code.encode())if returncode != 0:@@ -101,7 +108,10 @@ class Formatter:def __init__(self, line_length: int) -> None:self.line_length = line_length- async def format(self, codes: CellCodes) -> CellCodes:+ async def format(+ self, codes: CellCodes, stdin_filename: str | None = None+ ) -> CellCodes:+ del stdin_filenamereturn codes@@ -110,10 +120,14 @@ class DefaultFormatter(Formatter):Tries ruff, then black, then no formatting."""- async def format(self, codes: CellCodes) -> CellCodes:+ async def format(+ self, codes: CellCodes, stdin_filename: str | None = None+ ) -> CellCodes:# Ruff may be installed in venv or globallyif DependencyManager.ruff.has() or DependencyManager.which("ruff"):- return await RuffFormatter(self.line_length).format(codes)+ return await RuffFormatter(self.line_length).format(+ codes, stdin_filename=stdin_filename+ )# Black must be installed in venvelif DependencyManager.black.has():return await BlackFormatter(self.line_length).format(codes)@@ -125,14 +139,23 @@ class DefaultFormatter(Formatter):class RuffFormatter(Formatter):- async def format(self, codes: CellCodes) -> CellCodes:+ async def format(+ self, codes: CellCodes, stdin_filename: str | None = None+ ) -> CellCodes:return await ruff(- codes, "format", "--line-length", str(self.line_length)+ codes,+ "format",+ "--line-length",+ str(self.line_length),+ stdin_filename=stdin_filename,)class BlackFormatter(Formatter):- async def format(self, codes: CellCodes) -> CellCodes:+ async def format(+ self, codes: CellCodes, stdin_filename: str | None = None+ ) -> CellCodes:+ del stdin_filenameDependencyManager.black.require("to enable code formatting")import blackdiff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.pyindex 9a18e36d8e..678601b296 100644--- a/tests/_server/api/endpoints/test_editing.py+++ b/tests/_server/api/endpoints/test_editing.py@@ -2,6 +2,7 @@from __future__ import annotationsfrom typing import TYPE_CHECKING+from unittest.mock import AsyncMock, patchimport pytest@@ -70,6 +71,33 @@ def test_format_cell(client: TestClient) -> None:assert formatted_codes["cell-123"] == "def foo():\n return 1"+@with_session(SESSION_ID)+def test_format_cell_passes_notebook_path_to_formatter(+ client: TestClient,+) -> None:+ with patch(+ "marimo._server.api.endpoints.editing.DefaultFormatter.format",+ new=AsyncMock(return_value={"cell-123": "x = 1"}),+ ) as mock_format:+ response = client.post(+ "/api/kernel/format",+ headers=HEADERS,+ json={+ "codes": {"cell-123": "x=1"},+ "lineLength": 80,+ },+ )++ assert response.status_code == 200, response.text+ assert response.json() == {"codes": {"cell-123": "x = 1"}}+ assert mock_format.await_count == 1++ args, kwargs = mock_format.await_args+ assert {"cell-123": "x=1"} in args+ assert isinstance(kwargs["stdin_filename"], str)+ assert kwargs["stdin_filename"].endswith(".py")++@with_session(SESSION_ID)def test_install_missing_packages(client: TestClient) -> None:response = client.post(diff --git a/tests/_utils/test_formatter.py b/tests/_utils/test_formatter.pyindex 974d704103..66ebde6db6 100644--- a/tests/_utils/test_formatter.py+++ b/tests/_utils/test_formatter.py@@ -59,7 +59,9 @@ class TestDefaultFormatter:result = await formatter.format(codes)mock_ruff_formatter.assert_called_once_with(88)- mock_instance.format.assert_called_once_with(codes)+ mock_instance.format.assert_called_once_with(+ codes, stdin_filename=None+ )assert result == {"cell1": "formatted_code"}@patch("marimo._utils.formatter.BlackFormatter")@@ -134,7 +136,34 @@ class TestRuffFormatter:result = await formatter.format(codes)mock_ruff.assert_called_once_with(- codes, "format", "--line-length", "100"+ codes,+ "format",+ "--line-length",+ "100",+ stdin_filename=None,+ )+ assert result == {"cell1": "formatted_code"}++ @patch("marimo._utils.formatter.ruff")+ async def test_ruff_formatter_passes_stdin_filename(+ self, mock_ruff: MagicMock+ ) -> None:+ """Test RuffFormatter forwards notebook filename for config discovery."""+ mock_ruff.return_value = {"cell1": "formatted_code"}++ formatter = RuffFormatter(line_length=100)+ codes: CellCodes = {"cell1": "x=1"}++ result = await formatter.format(+ codes, stdin_filename="/tmp/notebook.py"+ )++ mock_ruff.assert_called_once_with(+ codes,+ "format",+ "--line-length",+ "100",+ stdin_filename="/tmp/notebook.py",)assert result == {"cell1": "formatted_code"}@@ -271,6 +300,41 @@ class TestRuffFunction:)assert format_call[1]["input_data"] == b"x=1"+ @patch("marimo._utils.formatter._run_subprocess_safe")+ async def test_ruff_function_passes_stdin_filename(+ self, mock_subprocess_safe: MagicMock+ ):+ """Test ruff includes --stdin-filename when provided."""+ mock_subprocess_safe.side_effect = [+ (b"", b"", 0), # help command success+ (b"formatted_code\n", b"", 0), # format command success+ ]++ codes: CellCodes = {"cell1": "x=1"}+ result = await ruff(+ codes,+ "format",+ "--line-length",+ "88",+ stdin_filename="/tmp/notebook.py",+ )++ assert result == {"cell1": "formatted_code"}++ format_call = mock_subprocess_safe.call_args_list[1]+ assert format_call[0] == (+ sys.executable,+ "-m",+ "ruff",+ "format",+ "--line-length",+ "88",+ "--stdin-filename",+ "/tmp/notebook.py",+ "-",+ )+ assert format_call[1]["input_data"] == b"x=1"+@patch("marimo._utils.formatter._run_subprocess_safe")async def test_ruff_function_falls_back_to_global_ruff(self, mock_subprocess_safe: MagicMock