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: expand home directory in custom CSS paths (#10829)
Dmitry Nefedovde87d5a7a92a
diff --git a/docs/guides/configuration/theming.md b/docs/guides/configuration/theming.mdindex e664062fed..5f0d4ef9e7 100644--- a/docs/guides/configuration/theming.md+++ b/docs/guides/configuration/theming.md@@ -8,6 +8,8 @@ To include a custom CSS file, in the configuration dropdown, add the relative fiapp = marimo.App(css_file="custom.css")```+CSS paths also support `~` for your home directory, e.g. `~/theme.css`.+## Theming at the project levelYou may also set the `custom_css` field in your project configuration to apply a custom CSS file. This theme won't be applied if the notebook is shared with someone else, but it will be applied to all notebooks open inside the project.diff --git a/marimo/_config/manager.py b/marimo/_config/manager.pyindex 2e48911597..c5128e7ec1 100644--- a/marimo/_config/manager.py+++ b/marimo/_config/manager.py@@ -302,10 +302,18 @@ class ProjectConfigManager(PartialMarimoConfigReader):if not isinstance(custom_css, list):return config- resolved_custom_css = [- str((self.pyproject_path.parent / path).absolute())- for path in custom_css- ]+ resolved_custom_css: list[str] = []+ for path in custom_css:+ try:+ expanded_path = Path(path).expanduser()+ except RuntimeError as e:+ LOGGER.warning(+ "Failed to resolve custom CSS file %s: %s", path, e+ )+ continue+ resolved_custom_css.append(+ str((self.pyproject_path.parent / expanded_path).absolute())+ )return {**config,"display": {**display, "custom_css": resolved_custom_css},diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.pyindex b3a9a8e4c9..44a56e0847 100644--- a/marimo/_session/notebook/file_manager.py+++ b/marimo/_session/notebook/file_manager.py@@ -662,7 +662,8 @@ def read_css_file(css_file: str, filename: str | None) -> str | None:"""Read the contents of a CSS file.Args:- css_file: The path to the CSS file.+ css_file: The path to the CSS file. Supports `~` for the home+ directory and relative paths resolved from the notebook directory.filename: The filename of the notebook.Returns:@@ -671,7 +672,11 @@ def read_css_file(css_file: str, filename: str | None) -> str | None:if not css_file:return None- filepath = Path(css_file)+ try:+ filepath = Path(css_file).expanduser()+ except RuntimeError as e:+ LOGGER.warning("Failed to resolve custom CSS file %s: %s", css_file, e)+ return None# If not an absolute path, make it absolute using the filenameif not filepath.is_absolute():diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.pyindex aff8c18e2d..4ec8b1b0ca 100644--- a/tests/_config/test_manager.py+++ b/tests/_config/test_manager.py@@ -725,6 +725,54 @@ def test_project_config_manager_resolve_custom_css(tmp_path: Path) -> None:assert config["display"]["custom_css"] == expected_custom_css+def test_project_config_manager_resolve_custom_css_home_path(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))++ pyproject_path = tmp_path / "pyproject.toml"+ pyproject_content = """+ [tool.marimo.display]+ custom_css = ["~/theme.css"]+ """+ pyproject_path.write_text(textwrap.dedent(pyproject_content))++ manager = get_default_config_manager(current_path=str(pyproject_path))+ config = manager.get_config(hide_secrets=False)++ assert config["display"]["custom_css"] == [+ str((tmp_path / "theme.css").absolute())+ ]+++def test_project_config_manager_skips_unresolvable_css_home_directory(+ tmp_path: Path,+) -> None:+ pyproject_path = tmp_path / "pyproject.toml"+ pyproject_path.write_text(+ textwrap.dedent("""+ [tool.marimo.display]+ custom_css = ["~/theme.css", "styles.css"]+ theme = "dark"+ """)+ )+ manager = ProjectConfigManager(str(pyproject_path))+ with patch(+ "pathlib.Path.expanduser",+ side_effect=[+ RuntimeError("Could not determine home directory."),+ tmp_path / "styles.css",+ ],+ ):+ config = manager.get_config(hide_secrets=False)++ assert config["display"] == {+ "custom_css": [str(tmp_path / "styles.css")],+ "theme": "dark",+ }++def test_project_config_manager_resolve_invalid_custom_css(tmp_path: Path,) -> None:diff --git a/tests/_session/notebook/test_app_file_manager.py b/tests/_session/notebook/test_app_file_manager.pyindex a4faa647fd..dbee61fd71 100644--- a/tests/_session/notebook/test_app_file_manager.py+++ b/tests/_session/notebook/test_app_file_manager.py@@ -5,6 +5,7 @@ import osimport threadingfrom concurrent.futures import ThreadPoolExecutor, waitfrom typing import TYPE_CHECKING+from unittest.mock import patchimport pytest@@ -12,6 +13,7 @@ from marimo._session.notebook import (AppFileManager,load_notebook,new_notebook,+ read_css_file,)if TYPE_CHECKING:@@ -92,6 +94,25 @@ def test_new_notebook_advances_document_version() -> None:assert fm.app.cell_manager.document.version > 0+def test_read_css_file_expands_home_directory(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ css = "body { color: red; }"+ (tmp_path / "theme.css").write_text(css, encoding="utf-8")++ assert read_css_file("~/theme.css", filename=None) == css+++def test_read_css_file_skips_unresolvable_home_directory() -> None:+ with patch(+ "pathlib.Path.expanduser",+ side_effect=RuntimeError("Could not determine home directory."),+ ):+ assert read_css_file("~/theme.css", filename=None) is None++@pytest.mark.parametrize("suffix", [".py", ".md"])@pytest.mark.parametrize("first_writer", ["manifest", "cells"])def test_manifest_and_cell_saves_preserve_each_other(