Skip to content

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.

load snippets location from config (#3462)

bennyweise5a5c50b3e912
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 04c073b114..3b0a8a67b3 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -12,7 +12,7 @@ if sys.version_info < (3, 11):
else:
from typing import NotRequired
-from typing import Any, Dict, Literal, Optional, TypedDict, Union, cast
+from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
from marimo._output.rich_help import mddoc
from marimo._utils.deep_merge import deep_merge
@@ -227,6 +227,19 @@ class GoogleAiConfig(TypedDict, total=False):
api_key: str
+@dataclass
+class SnippetsConfig(TypedDict):
+ """Configuration for snippets.
+
+ **Keys.**
+
+ - `custom_path`: the path to the custom snippets directory
+ """
+
+ custom_paths: NotRequired[List[str]]
+ include_default_snippets: NotRequired[bool]
+
+
@mddoc
@dataclass
class MarimoConfig(TypedDict):
@@ -242,6 +255,7 @@ class MarimoConfig(TypedDict):
package_management: PackageManagementConfig
ai: NotRequired[AiConfig]
experimental: NotRequired[Dict[str, Any]]
+ snippets: NotRequired[SnippetsConfig]
@mddoc
@@ -259,6 +273,7 @@ class PartialMarimoConfig(TypedDict, total=False):
package_management: PackageManagementConfig
ai: NotRequired[AiConfig]
experimental: NotRequired[Dict[str, Any]]
+ snippets: SnippetsConfig
DEFAULT_CONFIG: MarimoConfig = {
@@ -287,6 +302,10 @@ DEFAULT_CONFIG: MarimoConfig = {
"browser": "default",
"follow_symlink": False,
},
+ "snippets": {
+ "custom_paths": [],
+ "include_default_snippets": True,
+ },
}
diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.py
index 67782b0e8d..0dc28cb627 100644
--- a/marimo/_snippets/snippets.py
+++ b/marimo/_snippets/snippets.py
@@ -1,11 +1,15 @@
# Copyright 2024 Marimo. All rights reserved.
-import os
from dataclasses import dataclass
+from pathlib import Path
from typing import Any, Awaitable, Generator, List, Optional
+from marimo import _loggers
from marimo._ast.codegen import get_app
+from marimo._config.manager import get_default_config_manager
from marimo._utils.paths import import_files
+LOGGER = _loggers.marimo_logger()
+
@dataclass
class SnippetSection:
@@ -28,7 +32,7 @@ class Snippets:
async def read_snippets() -> Snippets:
snippets: List[Snippet] = []
- for file in snippet_files():
+ for file in read_snippet_filenames_from_config():
app = get_app(file)
assert app is not None
sections: List[SnippetSection] = []
@@ -85,11 +89,35 @@ def is_markdown(code: str) -> bool:
return code.startswith("mo.md")
-def snippet_files() -> Generator[str, Any, None]:
- root = os.path.realpath(
- str(import_files("marimo").joinpath("_snippets").joinpath("data"))
+def read_snippet_filenames_from_config() -> Generator[str, Any, None]:
+ # Get custom snippets path from config if present
+ config = get_default_config_manager(current_path=None).get_config()
+ custom_paths = config.get("snippets", {}).get("custom_paths", [])
+ include_default_snippets = config.get("snippets", {}).get(
+ "include_default_snippets", True
)
- for _root, _dirs, files in os.walk(root):
- for file in files:
- if file.endswith(".py"):
- yield os.path.join(root, file)
+ return read_snippet_filenames(include_default_snippets, custom_paths)
+
+
+def read_snippet_filenames(
+ include_default_snippets: bool, custom_paths: List[str]
+) -> Generator[str, Any, None]:
+ paths = []
+ if include_default_snippets:
+ paths.append(import_files("marimo") / "_snippets" / "data")
+ if custom_paths:
+ paths.extend([Path(p) for p in custom_paths])
+ for root_path in paths:
+ if not root_path.is_dir():
+ # Note: currently no handling of permissions errors, but theoretically
+ # this shouldn't be required for `is_dir` or `rglob`
+ # Other possible errors:
+ # - RecursionError: not possible, since by default symlinks are not followed
+ # - FileNotFoundError: not possible, `is_dir` checks if the path exists,
+ # but also resolve() is not called with strict=True
+ LOGGER.warning(
+ "Snippets path %s not a directory - ignoring", root_path
+ )
+ continue
+ for file in root_path.resolve().rglob("*.py"):
+ yield str(file)
diff --git a/openapi/api.yaml b/openapi/api.yaml
index baa18ab495..5fc3c9ae49 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1226,6 +1226,15 @@ components:
- browser
- follow_symlink
type: object
+ snippets:
+ properties:
+ custom_paths:
+ items:
+ type: string
+ type: array
+ include_default_snippets:
+ type: boolean
+ type: object
required:
- completion
- display
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 8f7a0444c7..b07d79d927 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2579,6 +2579,10 @@ export interface components {
browser: "default" | string;
follow_symlink: boolean;
};
+ snippets?: {
+ custom_paths?: string[];
+ include_default_snippets?: boolean;
+ };
};
MarimoExceptionRaisedError: {
exception_type: string;
diff --git a/tests/_snippets/test_snippets.py b/tests/_snippets/test_snippets.py
index d651e83ee8..8ec2e73aee 100644
--- a/tests/_snippets/test_snippets.py
+++ b/tests/_snippets/test_snippets.py
@@ -1,4 +1,10 @@
-from marimo._snippets.snippets import get_title_from_code, read_snippets
+import pytest
+
+from marimo._snippets.snippets import (
+ get_title_from_code,
+ read_snippet_filenames,
+ read_snippets,
+)
async def test_snippets() -> None:
@@ -36,3 +42,25 @@ def test_get_title_from_code_with_multiple_titles() -> None:
def test_get_title_from_code_with_non_title_hashes() -> None:
code = "print('# This is not a title')"
assert get_title_from_code(code) == ""
+
+
+ ("include_default_snippets", "custom_paths", "expected_snippets"),
+ [
+ (True, [], 38),
+ (False, [], 0),
+ (True, ["/notarealdirectory"], 38),
+ (False, ["/notarealdirectory"], 0),
+ (False, ["marimo/_snippets/data"], 38),
+ (False, ["marimo/_snippets/data", "/notarealdirectory"], 38),
+ ],
+)
+def test_read_snippet_filenames(
+ include_default_snippets, custom_paths, expected_snippets
+) -> None:
+ filenames = list(
+ read_snippet_filenames(include_default_snippets, custom_paths)
+ )
+ assert len(filenames) == expected_snippets
+ assert all(filename.endswith(".py") for filename in filenames)
+ assert all("_snippets/data" in filename for filename in filenames)