diff --git a/doc/API.md b/doc/API.md index 3766453..4d603ce 100644 --- a/doc/API.md +++ b/doc/API.md @@ -514,8 +514,9 @@ register a language-change listener. ## 7. `ki18n.paths` module reference -Small helpers for applications that are bundled with PyInstaller. They are -independent of `Ki18n`. +Small helpers for applications that are bundled with PyInstaller and for locating +per-user data directories. They are independent of `Ki18n` (which uses +`base_data_dir()` for its default user directory). #### `is_frozen() -> bool` @@ -539,6 +540,33 @@ from ki18n.paths import bundle_root Ki18n("en", project_root=bundle_root()) ``` +#### `base_data_dir() -> Path` + +Conventional per-user base directory for application data. The directory is +neither created nor checked for existence. + +| Platform | Result | +| --- | --- | +| Windows | `%LOCALAPPDATA%`, else `~/AppData/Local` | +| macOS (Darwin) | `$XDG_DATA_HOME` if set, else `~/Library/Application Support` | +| Linux and other POSIX | `$XDG_DATA_HOME` if set, else `~/.local/share` | + +An empty environment variable counts as unset; a leading `~` in `XDG_DATA_HOME` +is expanded. + +#### `data_dir(name: str) -> Path` + +Data directory of the application called `name`: `base_data_dir() / name`, for +example `data_dir("ki18n")` is `~/.local/share/ki18n` on Linux. The directory is +not created. + +Raises `ValueError` if `name` is empty, `.` or `..`, or contains `/` or `\`. + +```python +from ki18n.paths import data_dir +Ki18n("en", local_root=data_dir("my-app")) +``` + --- ## 8. Errors and logging diff --git a/src/ki18n/ki18n.py b/src/ki18n/ki18n.py index c73c3fc..af66ca6 100644 --- a/src/ki18n/ki18n.py +++ b/src/ki18n/ki18n.py @@ -25,7 +25,6 @@ from __future__ import annotations import json import logging -import os import re import sys from collections.abc import Callable @@ -33,6 +32,8 @@ from copy import deepcopy from pathlib import Path from typing import Any +from . import paths + DEFAULT_LANGUAGE = "en" log = logging.getLogger(__name__) @@ -151,18 +152,7 @@ class Ki18n: @staticmethod def _user_data_root() -> Path: """Return the conventional per-user application data directory.""" - if os.name == "nt": - local_app_data = os.environ.get("LOCALAPPDATA") - if local_app_data: - return Path(local_app_data) - return Path.home() / "AppData" / "Local" - - xdg_data_home = os.environ.get("XDG_DATA_HOME") - if xdg_data_home: - return Path(xdg_data_home).expanduser() - if sys.platform == "darwin": - return Path.home() / "Library" / "Application Support" - return Path.home() / ".local" / "share" + return paths.base_data_dir() @staticmethod def _language_dir(root: Path, language_id: str) -> Path | None: diff --git a/src/ki18n/paths.py b/src/ki18n/paths.py index 958615e..2819f40 100644 --- a/src/ki18n/paths.py +++ b/src/ki18n/paths.py @@ -9,21 +9,6 @@ from pathlib import Path logger = logging.getLogger(__name__) -# APP_DIR_NAME = "borg-sphere" -# LOG_NAME = "borg-sphere.log" -# -# #: Former names of the application (until renamed): data folder, log file, environment variables -# LEGACY_APP_DIR_NAME = "vorta-tui" -# LEGACY_LOG_NAME = "vorta-tui.log" -# LEGACY_ENV_PREFIX = "VORTA_TUI_" -# ENV_PREFIX = "BORG_SPHERE_" -# -# #: Results from :func:`migrate_legacy_data_dir` -# MIGRATED = "migrated" # Folder has been migrated -# NOTHING_TO_DO = "none" # not an old folder (or already migrated) -# BOTH_EXIST = "both-exist" # old and new folders exist: nothing touched -# FAILED = "failed" # Moving not possible (e.g. different mount) - def is_frozen() -> bool: """True inside a PyInstaller-built executable.""" @@ -43,3 +28,46 @@ def bundle_root() -> Path: # Plain source checkout or a pex zipapp: this file lives at # /app/runtime_paths.py. return Path(__file__).resolve().parent.parent + + +def _base_data_dir() -> Path: + """Return the conventional per-user base directory for application data. + + The directory is not created and not checked for existence. + + * Windows: ``%LOCALAPPDATA%``, else ``~/AppData/Local``. + * macOS (Darwin): ``$XDG_DATA_HOME`` if set, else + ``~/Library/Application Support``. + * Linux and other POSIX systems: ``$XDG_DATA_HOME`` if set, else + ``~/.local/share``. + + An environment variable that is empty counts as unset. A leading ``~`` in + ``XDG_DATA_HOME`` is expanded. + """ + if sys.platform == "win32": + local_app_data = os.environ.get("LOCALAPPDATA") + if local_app_data: + return Path(local_app_data) + return Path.home() / "AppData" / "Local" + + xdg_data_home = os.environ.get("XDG_DATA_HOME") + if xdg_data_home: + return Path(xdg_data_home).expanduser() + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" + return Path.home() / ".local" / "share" + + +def data_dir(name: str) -> Path: + """Return the data directory of the application called ``name``. + + This is ``/``, for example ``~/.local/share/ki18n`` + for ``data_dir("ki18n")`` on Linux. The directory is not created. + + :raises ValueError: if ``name`` is empty, ``.`` or ``..``, or contains a + path separator (``/`` or ``\\``), because it must be a single directory + name. + """ + if not name or name in {".", ".."} or "/" in name or "\\" in name: + raise ValueError(f"Invalid application directory name: {name!r}") + return _base_data_dir() / name diff --git a/test/test_paths.py b/test/test_paths.py index 73e1587..24f2845 100644 --- a/test/test_paths.py +++ b/test/test_paths.py @@ -1,8 +1,10 @@ -"""Tests for ``ki18n.paths`` (PyInstaller / source checkout detection).""" +"""Tests for ``ki18n.paths`` (PyInstaller / source checkout detection, data directories).""" import sys from pathlib import Path +import pytest + from ki18n import paths @@ -42,3 +44,129 @@ def test_frozen_without_meipass_uses_executable_directory(monkeypatch, tmp_path) def test_bundle_root_returns_path(): assert isinstance(paths.bundle_root(), Path) + + +# --------------------------------------------------------------------------- +# Per-user data directories +# --------------------------------------------------------------------------- + + +@pytest.fixture +def home(tmp_path, monkeypatch) -> Path: + """Pseudo home directory; XDG_DATA_HOME and LOCALAPPDATA are removed.""" + home_dir = tmp_path.resolve() + monkeypatch.setattr(Path, "home", staticmethod(lambda: home_dir)) + monkeypatch.setenv("HOME", str(home_dir)) + monkeypatch.setenv("USERPROFILE", str(home_dir)) + monkeypatch.delenv("XDG_DATA_HOME", raising=False) + monkeypatch.delenv("LOCALAPPDATA", raising=False) + return home_dir + + +def set_platform(monkeypatch, platform: str) -> None: + monkeypatch.setattr(sys, "platform", platform) + + +class TestBaseDataDirLinux: + @pytest.mark.parametrize("platform", ["linux", "freebsd14", "openbsd7"]) + def test_default_without_xdg(self, home, monkeypatch, platform): + set_platform(monkeypatch, platform) + assert paths.base_data_dir() == home / ".local" / "share" + + def test_xdg_data_home_is_used_when_set(self, home, monkeypatch): + set_platform(monkeypatch, "linux") + monkeypatch.setenv("XDG_DATA_HOME", str(home / "xdg")) + assert paths.base_data_dir() == home / "xdg" + + def test_xdg_data_home_expands_user(self, home, monkeypatch): + set_platform(monkeypatch, "linux") + monkeypatch.setenv("XDG_DATA_HOME", "~/share") + assert paths.base_data_dir() == home / "share" + + def test_empty_xdg_data_home_is_treated_as_unset(self, home, monkeypatch): + set_platform(monkeypatch, "linux") + monkeypatch.setenv("XDG_DATA_HOME", "") + assert paths.base_data_dir() == home / ".local" / "share" + + def test_localappdata_is_ignored(self, home, monkeypatch): + set_platform(monkeypatch, "linux") + monkeypatch.setenv("LOCALAPPDATA", str(home / "local-app-data")) + assert paths.base_data_dir() == home / ".local" / "share" + + +class TestBaseDataDirDarwin: + def test_default_without_xdg(self, home, monkeypatch): + set_platform(monkeypatch, "darwin") + assert paths.base_data_dir() == home / "Library" / "Application Support" + + def test_xdg_data_home_takes_precedence(self, home, monkeypatch): + set_platform(monkeypatch, "darwin") + monkeypatch.setenv("XDG_DATA_HOME", str(home / "xdg")) + assert paths.base_data_dir() == home / "xdg" + + def test_empty_xdg_data_home_is_treated_as_unset(self, home, monkeypatch): + set_platform(monkeypatch, "darwin") + monkeypatch.setenv("XDG_DATA_HOME", "") + assert paths.base_data_dir() == home / "Library" / "Application Support" + + +class TestBaseDataDirWindows: + def test_localappdata_is_used_when_set(self, home, monkeypatch): + set_platform(monkeypatch, "win32") + monkeypatch.setenv("LOCALAPPDATA", str(home / "local-app-data")) + assert paths.base_data_dir() == home / "local-app-data" + + def test_fallback_without_localappdata(self, home, monkeypatch): + set_platform(monkeypatch, "win32") + assert paths.base_data_dir() == home / "AppData" / "Local" + + def test_empty_localappdata_is_treated_as_unset(self, home, monkeypatch): + set_platform(monkeypatch, "win32") + monkeypatch.setenv("LOCALAPPDATA", "") + assert paths.base_data_dir() == home / "AppData" / "Local" + + def test_xdg_data_home_is_ignored(self, home, monkeypatch): + set_platform(monkeypatch, "win32") + monkeypatch.setenv("XDG_DATA_HOME", str(home / "xdg")) + assert paths.base_data_dir() == home / "AppData" / "Local" + + +def test_base_data_dir_returns_path(home): + assert isinstance(paths.base_data_dir(), Path) + + +class TestDataDir: + @pytest.mark.parametrize( + ("platform", "expected"), + [ + ("linux", Path(".local") / "share" / "ki18n"), + ("darwin", Path("Library") / "Application Support" / "ki18n"), + ("win32", Path("AppData") / "Local" / "ki18n"), + ], + ) + def test_appends_name_to_base_directory(self, home, monkeypatch, platform, expected): + set_platform(monkeypatch, platform) + assert paths.data_dir("ki18n") == home / expected + + def test_uses_base_data_dir(self, tmp_path, monkeypatch): + monkeypatch.setattr(paths, "base_data_dir", lambda: tmp_path) + assert paths.data_dir("my-app") == tmp_path / "my-app" + + def test_returns_path(self, home): + assert isinstance(paths.data_dir("ki18n"), Path) + + def test_name_with_space_is_kept(self, tmp_path, monkeypatch): + monkeypatch.setattr(paths, "base_data_dir", lambda: tmp_path) + assert paths.data_dir("My App") == tmp_path / "My App" + + def test_directory_is_not_created(self, tmp_path, monkeypatch): + monkeypatch.setattr(paths, "base_data_dir", lambda: tmp_path) + result = paths.data_dir("ki18n") + assert not result.exists() + assert list(tmp_path.iterdir()) == [] + + @pytest.mark.parametrize("name", ["", ".", "..", "a/b", "a\\b", "/abs", "../x"]) + def test_invalid_name_is_rejected(self, tmp_path, monkeypatch, name): + monkeypatch.setattr(paths, "base_data_dir", lambda: tmp_path) + with pytest.raises(ValueError): + paths.data_dir(name)