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.

feat: xdg config file (#2367)

pakelleyf7f8eaf069af
diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md
index 20ae5e0848..7ffaed964d 100644
--- a/docs/guides/configuration.md
+++ b/docs/guides/configuration.md
@@ -19,6 +19,7 @@ User Configuration applies globally across all marimo notebooks and is stored in
1. Current directory
2. Parent directories (moving up the tree)
3. Home directory (`~/.marimo.toml`)
+4. [XDG](https://xdgbasedirectoryspecification.com/) directory (`~/.config/marimo/marimo.toml` or `$XDG_CONFIG_HOME/marimo/marimo.toml`)
If no `.marimo.toml` file is found, marimo creates a default one in your home directory.
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.md
index de80924b7e..1131df68c5 100644
--- a/docs/guides/editor_features/ai_completion.md
+++ b/docs/guides/editor_features/ai_completion.md
@@ -27,7 +27,7 @@ marimo using `pip` if you need Copilot.
4. Right-click on the extension window and select "Inspect" to open the developer tools for the extension. Then click on "Network"
5. Copy the token and paste it into the input area, and then press "Enter Token"
6. This action will log a new API request in the **Network** tab. Click on "Preview" to get the API key.
-7. Paste the API key in the marimo settings in the UI, or add it to your `~/.marimo.toml` file as follows:
+7. Paste the API key in the marimo settings in the UI, or add it to your `marimo.toml` file as follows:
```toml
[completion]
@@ -57,7 +57,7 @@ the bottom of your notebook. You can also refactor existing cells by inputting
1. Install openai: `pip install openai`
-2. Add the following to your `~/.marimo.toml`:
+2. Add the following to your `marimo.toml`:
```toml
[ai.open_ai]
@@ -74,7 +74,7 @@ base_url = "https://api.openai.com/v1"
To use Anthropic with marimo:
1. Sign up for an account at [Anthropic](https://console.anthropic.com/) and grab your [Anthropic Key](https://console.anthropic.com/settings/keys).
-2. Add the following to your `~/.marimo.toml`:
+2. Add the following to your `marimo.toml`:
```toml
[ai.open_ai]
@@ -102,7 +102,7 @@ Gemma 2) on your local machine. To integrate Ollama with marimo:
2. We also recommend `codellama` (code specific) or `llama3.1` (more advanced, but larger).
3. Start the Ollama server: `ollama run llama2`
4. Visit <http://localhost:11434> to confirm that the server is running.
-5. Add the following to your `~/.marimo.toml`:
+5. Add the following to your `marimo.toml`:
```toml
[ai.open_ai]
diff --git a/docs/guides/editor_features/hotkeys.md b/docs/guides/editor_features/hotkeys.md
index cd7c2a1ddb..4bcc111c09 100644
--- a/docs/guides/editor_features/hotkeys.md
+++ b/docs/guides/editor_features/hotkeys.md
@@ -1,6 +1,6 @@
# Hotkeys
-If you'd like to override the default hotkeys, you can do so in the hotkeys menu (`Mod-Shift-h`), or modifying your `~/.marimo.toml`.
+If you'd like to override the default hotkeys, you can do so in the hotkeys menu (`Mod-Shift-h`), or modifying your `marimo.toml`.
You can find a list of available hotkeys below:
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 3356cf3bdf..ab9c89874d 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -690,8 +690,8 @@ export const UserConfigForm: React.FC = () => {
<>
<SettingGroup title="AI Assist">
<p className="text-sm text-muted-secondary">
- Add an API key to <Kbd className="inline">~/.marimo.toml</Kbd>{" "}
- to activate marimo's AI assistant; see{" "}
+ Add an API key to <Kbd className="inline">marimo.toml</Kbd> to
+ activate marimo's AI assistant; see{" "}
<a
className="text-link hover:underline"
href="https://docs.marimo.io/guides/editor_features/ai_completion.html"
@@ -807,7 +807,7 @@ export const UserConfigForm: React.FC = () => {
const configMessage = (
<p className="text-muted-secondary">
- User configuration is stored in <Kbd className="inline">.marimo.toml</Kbd>
+ User configuration is stored in <Kbd className="inline">marimo.toml</Kbd>
<br />
Run <Kbd className="inline">marimo config show</Kbd> in your terminal to
show your current configuration and file location.
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 06067c2a6d..0827b69fb3 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
from typing import Optional
from marimo import _loggers
@@ -12,7 +11,10 @@ from marimo._config.config import (
merge_default_config,
remove_secret_placeholders,
)
-from marimo._config.utils import CONFIG_FILENAME, get_config_path, load_config
+from marimo._config.utils import (
+ get_or_create_config_path,
+ load_config,
+)
LOGGER = _loggers.marimo_logger()
@@ -44,8 +46,4 @@ class UserConfigManager:
return self.config
def get_config_path(self) -> str:
- return get_config_path() or self._default_config_path()
-
- def _default_config_path(self) -> str:
- home = os.path.expanduser("~")
- return os.path.join(home, CONFIG_FILENAME)
+ return get_or_create_config_path()
diff --git a/marimo/_config/utils.py b/marimo/_config/utils.py
index f9e6269356..0c250a3622 100644
--- a/marimo/_config/utils.py
+++ b/marimo/_config/utils.py
@@ -34,6 +34,32 @@ def _check_directory_for_file(directory: str, filename: str) -> Optional[str]:
return None
+def _xdg_config_path() -> str:
+ """Search XDG paths for marimo config file"""
+ home_expansion = os.path.expanduser("~")
+ home_directory = os.path.realpath(home_expansion)
+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
+ home_directory, ".config"
+ )
+ return os.path.join(xdg_config_home, "marimo", "marimo.toml")
+
+
+def get_or_create_config_path() -> str:
+ """Find path of config file, or create it
+
+ If no config file is found, one will be created under the proper XDG path
+ (i.e. `~/.config/marimo` or `$XDG_CONFIG_HOME/marimo`)
+ """
+ current_config_path = get_config_path()
+ if current_config_path:
+ return current_config_path
+ else:
+ config_path = _xdg_config_path()
+ os.makedirs(os.path.dirname(config_path), exist_ok=True)
+ open(config_path, "a").close()
+ return config_path
+
+
def get_config_path() -> Optional[str]:
"""Find path of config file (.marimo.toml).
@@ -43,6 +69,9 @@ def get_config_path() -> Optional[str]:
If current directory isn't contained in home, just searches current
directory and home.
+ If not found between current directory and home, will search XDG paths
+ (i.e. `~/.config/marimo` and `$XDG_CONFIG_HOME/marimo`).
+
May raise an OSError.
"""
@@ -83,6 +112,10 @@ def get_config_path() -> Optional[str]:
if os.path.isfile(config_path):
return config_path
+ xdg_config_path = _xdg_config_path()
+ if os.path.isfile(xdg_config_path):
+ return xdg_config_path
+
return None
diff --git a/tests/_config/test_config.py b/tests/_config/test_config.py
index 89eaa7e930..ca414ecb11 100644
--- a/tests/_config/test_config.py
+++ b/tests/_config/test_config.py
@@ -1,6 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+from typing import List, Optional
+from unittest import mock
+
from marimo._config.config import (
DEFAULT_CONFIG,
MarimoConfig,
@@ -9,6 +16,7 @@ from marimo._config.config import (
merge_default_config,
remove_secret_placeholders,
)
+from marimo._config.utils import get_config_path, get_or_create_config_path
def assert_config(override: MarimoConfig) -> None:
@@ -151,3 +159,79 @@ def test_remove_secret_placeholders() -> None:
# Ensure the original config is not modified
assert config["ai"]["open_ai"]["api_key"] == "********"
+
+
+@contextmanager
+def _mock_file_exists(
+ exists: Optional[str | List[str]] = None,
+ doesnt_exist: Optional[str | List[str]] = None,
+):
+ if isinstance(exists, str):
+ exists = [exists]
+ if isinstance(doesnt_exist, str):
+ doesnt_exist = [doesnt_exist]
+
+ isfile = os.path.isfile
+
+ def mock_exists(check_path):
+ if (exists is not None) and (check_path in exists):
+ return True
+ if (doesnt_exist is not None) and (check_path in doesnt_exist):
+ return False
+ return isfile(check_path)
+
+ with mock.patch(
+ "marimo._config.utils.os.path.isfile",
+ side_effect=mock_exists,
+ ):
+ yield
+
+
+def test_get_config_path():
+ xdg_config_path = str(Path("~/.config/marimo/marimo.toml").expanduser())
+ home_config_path = str(Path("~/.marimo.toml").expanduser())
+
+ # If neither config exists, return None
+ with _mock_file_exists(doesnt_exist=[xdg_config_path, home_config_path]):
+ found_config_path = get_config_path()
+ assert found_config_path is None
+
+ # If only XDG path exists, use XDG path
+ with _mock_file_exists(
+ exists=xdg_config_path, doesnt_exist=home_config_path
+ ):
+ found_config_path = get_config_path()
+ assert found_config_path == xdg_config_path
+
+ # If both config paths exist, home config takes precedence
+ with _mock_file_exists(exists=[xdg_config_path, home_config_path]):
+ found_config_path = get_config_path()
+ assert found_config_path == home_config_path
+
+
+def test_get_or_create_config_path():
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Use temp dir to avoid creating stray xdg config.
+ # Still creates home one though, unfortunately.
+ os.environ["XDG_CONFIG_HOME"] = temp_dir
+ xdg_config_path = str(Path(temp_dir) / "marimo/marimo.toml")
+ home_config_path = str(Path("~/.marimo.toml").expanduser())
+
+ # If neither config exists, XDG config should be created and used
+ with _mock_file_exists(
+ doesnt_exist=[xdg_config_path, home_config_path]
+ ):
+ found_config_path = get_or_create_config_path()
+ assert found_config_path == xdg_config_path
+
+ # If only XDG path exists, use XDG path
+ with _mock_file_exists(
+ exists=xdg_config_path, doesnt_exist=home_config_path
+ ):
+ found_config_path = get_or_create_config_path()
+ assert found_config_path == xdg_config_path
+
+ # If both config paths exist, home config takes precedence
+ with _mock_file_exists(exists=[xdg_config_path, home_config_path]):
+ found_config_path = get_or_create_config_path()
+ assert found_config_path == home_config_path