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
feat: format with ruff if provided, black is not (#1118)
Myles Scolnicka420087732b5
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex f35179ce41..55c2f19d70 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -58,7 +58,7 @@ from marimo._server.models.models import (SaveRequest,)from marimo._snippets.snippets import read_snippets-from marimo._utils.formatter import BlackFormatter+from marimo._utils.formatter import DefaultFormatterfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -230,7 +230,7 @@ class PyodideBridge:def format(self, request: str) -> str:parsed = parse_raw(json.loads(request), FormatRequest)- formatter = BlackFormatter(line_length=parsed.line_length)+ formatter = DefaultFormatter(line_length=parsed.line_length)response = FormatResponse(codes=formatter.format(parsed.codes))return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex d31a269ae7..5322ea7fb8 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -21,7 +21,7 @@ from marimo._server.models.models import (SuccessResponse,)from marimo._server.router import APIRouter-from marimo._utils.formatter import BlackFormatter+from marimo._utils.formatter import DefaultFormatterif TYPE_CHECKING:from starlette.requests import Request@@ -57,7 +57,7 @@ async def delete_cell(request: Request) -> BaseResponse:async def format_cell(request: Request) -> FormatResponse:"""Complete a code fragment."""body = await parse_request(request, cls=FormatRequest)- formatter = BlackFormatter(line_length=body.line_length)+ formatter = DefaultFormatter(line_length=body.line_length)return FormatResponse(codes=formatter.format(body.codes))diff --git a/marimo/_utils/formatter.py b/marimo/_utils/formatter.pyindex 77b35cf111..39e9a536b7 100644--- a/marimo/_utils/formatter.py+++ b/marimo/_utils/formatter.py@@ -1,8 +1,10 @@# Copyright 2024 Marimo. All rights reserved.+import subprocessfrom typing import Dictfrom marimo import _loggersfrom marimo._ast.cell import CellId_t+from marimo._dependencies.dependencies import DependencyManagerLOGGER = _loggers.marimo_logger()@@ -18,6 +20,54 @@ class Formatter:return codes+class DefaultFormatter(Formatter):+ """+ Tries black, then ruff, then no formatting.+ """++ def format(self, codes: CellCodes) -> CellCodes:+ if DependencyManager.has("black"):+ return BlackFormatter(self.line_length).format(codes)+ elif DependencyManager.has("ruff"):+ return RuffFormatter(self.line_length).format(codes)+ else:+ LOGGER.warning(+ "To enable code formatting, install black (pip install black) "+ "or ruff (pip install ruff)"+ )+ return {}+++class RuffFormatter(Formatter):+ def format(self, codes: CellCodes) -> CellCodes:+ formatted_codes: CellCodes = {}+ for key, code in codes.items():+ try:+ process = subprocess.run(+ [+ "ruff",+ "format",+ "--line-length",+ str(self.line_length),+ "-",+ ],+ input=code.encode(),+ capture_output=True,+ check=True,+ )+ if process.returncode != 0:+ raise FormatError("Failed to format code with ruff")++ formatted = process.stdout.decode()+ formatted_codes[key] = formatted.strip()+ except Exception as e:+ LOGGER.error("Failed to format code with ruff")+ LOGGER.debug(e)+ continue++ return formatted_codes++class BlackFormatter(Formatter):def format(self, codes: CellCodes) -> CellCodes:try:@@ -38,3 +88,7 @@ class BlackFormatter(Formatter):formatted_codes[key] = codereturn formatted_codes+++class FormatError(Exception):+ pass