Updated bundle_root to work wherever ithe root is in relation to the library

This commit is contained in:
2026-11-21 09:57:55 +01:00
parent a419167939
commit 94f220e00d
4 changed files with 224 additions and 67 deletions
+52 -43
View File
@@ -58,7 +58,7 @@ my-app/
`main.py`:
```python
from ki18n.ki18n import Ki18n, i18n
from ki18n import Ki18n, i18n
# Optional: configure the manager before the first translation is requested.
Ki18n("en") # default language; project_root is derived from sys.argv[0]
@@ -70,8 +70,9 @@ i18n.set_language("de")
print(i18n.t("greeting", name="Ada")) # Hallo, Ada!
```
> **Import path.** The package's `__init__.py` is currently empty, so import
> from the submodule: `from ki18n.ki18n import Ki18n, i18n`.
> **Import path.** `Ki18n`, `i18n` and `I18n` are re-exported by the package, so
> `from ki18n import Ki18n, i18n` works. The submodule path
> `from ki18n.ki18n import ...` remains valid.
---
@@ -198,7 +199,8 @@ Keys missing from a new language fall back to English.
## 4. `ki18n.ki18n` module reference
```python
from ki18n.ki18n import Ki18n, i18n, I18n, ki18n, DEFAULT_LANGUAGE
from ki18n import Ki18n, i18n, I18n # package-level exports
from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
```
### Module-level names
@@ -208,7 +210,7 @@ from ki18n.ki18n import Ki18n, i18n, I18n, ki18n, DEFAULT_LANGUAGE
| `DEFAULT_LANGUAGE` | `"en"`. Default value of the `default_language` parameter. |
| `Ki18n` | The manager class. |
| `i18n` | Lazy handle: every attribute access is forwarded to the `Ki18n` singleton, which is created with default arguments if it does not exist yet. Unknown attributes raise `AttributeError`. |
| `I18n`, `ki18n` | Compatibility aliases for `Ki18n`. |
| `I18n`, `ki18n` | Compatibility aliases for `Ki18n`. Only `I18n` is exported by the package; `ki18n` would shadow the submodule `ki18n.ki18n`, so import it from the submodule. |
### `class Ki18n`
@@ -307,7 +309,7 @@ Lookup order: active language → English → `default` → `key` itself.
If keyword arguments are given, the text is formatted with `str.format`. When the
text is malformed or a placeholder value is missing, the unformatted text is
returned instead of raising (see [Known limitations](#9-known-limitations)).
returned instead of raising.
Without keyword arguments no formatting takes place, so `{{`/`}}` stay as they
are. The formatting also applies to the `default` text and to the key fallback.
@@ -326,17 +328,14 @@ i18n.t("wert", n=42) # formats e.g. "{n:05d}" -> "0004
Translates a pluralized key.
`count` may be an `int` or a `float`, positive or negative. The category is
chosen from its **absolute value**:
The category is chosen from `count`:
| `count` | Category |
| --- | --- |
| `None` | `none` |
| `0`, `0.0`, `-0.0` | `zero` |
| `1`, `1.0`, `-1` | `one` |
| any other number, e.g. `2`, `-2`, `0.5`, `-1.5`, `2.5` | `many` |
Values such as `NaN` and infinity also select `many`.
| `0` | `zero` |
| `1` | `one` |
| greater than 1 | `many` |
Lookup order: active language → English (same category) → `default` → `key`.
A plain string value is also accepted and used for every category, which helps
@@ -345,18 +344,14 @@ with partially converted resources.
In the selected text, `#count` is replaced by the count, and the text is then
formatted with `count` plus any keyword arguments, so `{count}` and extra
placeholders work. A failed formatting returns the text with `#count` already
replaced. `#count` inserts the count as Python prints it (`2.5`, `-3`); use a
format specification such as `{count:.1f}` to control the number format.
replaced.
**Raises** `TypeError` if `count` is neither a number nor `None`.
**Raises** `ValueError` for negative counts (checked before the lookup).
```python
i18n.p("files.found", 0) # "No files found"
i18n.p("files.found", 1) # "One file found"
i18n.p("files.found", -1) # "One file found" (absolute value)
i18n.p("files.found", 5) # "5 files found"
i18n.p("files.found", 2.5) # "2.5 files found"
i18n.p("files.found", -2) # "-2 files found"
i18n.p("files.found", None) # text of the "none" category
i18n.p("files.found", 3, default="{count} things") # used only if the key is unknown
```
@@ -521,9 +516,11 @@ register a language-change listener.
## 7. `ki18n.paths` module reference
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).
Small helpers for locating the application. They are independent of `Ki18n`.
```python
from ki18n.paths import bundle_root, is_frozen
```
#### `is_frozen() -> bool`
@@ -531,27 +528,48 @@ per-user data directories. They are independent of `Ki18n` (which uses
#### `bundle_root() -> Path`
Directory that contains the bundled application files at runtime:
Returns the **root directory of the application that uses ki18n**. The result
never depends on where `ki18n` itself is located: the library may be a top-level
package, vendored several directories deep inside the application
(`app/lib/vendor/ki18n/...`) or installed in a virtual environment.
| Situation | Result |
| --- | --- |
| Frozen, `sys._MEIPASS` set | `Path(sys._MEIPASS)` |
| Frozen, no `_MEIPASS` | Directory of `sys.executable` |
| Not frozen | Parent of the `ki18n` package directory |
| Not frozen | Nearest directory containing an `i18n/` folder, searching from the main program's directory upwards (see below) |
| Not frozen, no `i18n/` found | Directory of the main program |
When `ki18n` is installed as a package, "not frozen" means the directory that
contains the package (for example `site-packages`), not your application
directory. In that case pass `project_root` explicitly.
How the non-frozen case works:
For a frozen application, pass `bundle_root()` as `project_root` if the `i18n/`
folder is bundled there:
1. The **main program's directory** is the directory of `sys.argv[0]` (symlinks
and relative paths resolved). Without a script (interactive session,
`python -c ...`) the current working directory is used.
2. Starting there, the directory itself and then each parent directory is
checked for an `i18n/` folder; the first match is the application root. This
also works when the entry point lives in a subfolder such as
`tools/cli/main.py`.
3. If no directory on that path contains `i18n/`, the main program's directory
is returned.
Notes:
- The nearest match wins: with `root/i18n` and `root/app/i18n`, a program
started from `root/app/` gets `root/app`.
- For installed console scripts (`sys.argv[0]` points into a virtual
environment's `bin/` directory) pass `project_root` explicitly instead.
- `Ki18n` itself uses the directory of `sys.argv[0]` as default `project_root`
without walking up. To use the application root also for deeper entry points,
pass it explicitly:
```python
from ki18n import Ki18n
from ki18n.paths import bundle_root
Ki18n("en", project_root=bundle_root())
```
#### `base_data_dir() -> Path`
#### `_base_data_dir() -> Path` (internal)
Conventional per-user base directory for application data. The directory is
neither created nor checked for existence.
@@ -592,7 +610,7 @@ Ki18n("en", local_root=data_dir("my-app"))
| `FileNotFoundError` | `set_language` | The language's files disappeared after start-up. |
| `ValueError` | `set_language` | Unknown language or invalid ID. |
| `ValueError` | `t` | Key refers to a plural object. |
| `TypeError` | `p` | `count` is neither a number nor `None`. |
| `ValueError` | `p` | Negative count. |
| `FileNotFoundError` | `get_help` | No help file for the active language or English. |
After any exception from `set_language`, the previously active language remains
@@ -614,19 +632,10 @@ are reported at `WARNING` level and the offending file or folder is ignored:
These points are based on reading the current source code.
- **No package-level exports.** `ki18n/__init__.py` is empty, so
`from ki18n import Ki18n, i18n` does not work; use `ki18n.ki18n`.
- **Narrow format error handling.** `t()`/`p()` only swallow `KeyError`,
`IndexError` and `ValueError` from `str.format`. Placeholders that raise
`AttributeError` or `TypeError` (for example `{name.attr}` or `{name[x]}` with
a string value) propagate to the caller.
- **Simple plural rules.** `p()` knows only the categories `zero`, `one`, `many`
and `none`, chosen from the absolute value of the count. Language-specific
plural rules (for example separate forms for 2–4 in Slavic languages) are not
supported, and fractions such as `1.5` always use `many`.
- **Fractional counts below 1.** `p()` accepts floats, but values between 0 and 1
(for example `0.5`) match no category and raise `ValueError` with the message
`count must be nonnegative or None`.
- **No automatic reload.** Resource files are read when a language is activated;
selecting the already active language does nothing.
- **Plain Markdown help.** `help.md` is returned verbatim; there is no merge with
the installed file and no translation of individual sections.
- **Documentation drift in the source.** The module and constructor docstrings
mention a `key_aliases` mapping, which the code does not implement.
+42 -7
View File
@@ -12,21 +12,56 @@ def is_frozen() -> bool:
return bool(getattr(sys, "frozen", False))
#: Name of the folder that holds the translations (see ``Ki18n``).
I18N_DIR_NAME = "i18n"
def _main_directory() -> Path:
"""Directory of the program that was started, *not* of this library.
This is the directory of ``sys.argv[0]`` (symlinks resolved, relative paths
resolved against the current working directory). Without a script (an
interactive session, ``python -c ...``) the current working directory is
used.
"""
argv0 = sys.argv[0] if sys.argv else ""
if argv0 and argv0 not in ("-c", "-m", "-"):
return Path(argv0).resolve().parent
return Path.cwd().resolve()
def bundle_root() -> Path:
"""Directory that contains the bundled application files (e.g. ``i18n/``) at runtime."""
"""Root directory of the application that uses ki18n.
The result does not depend on where ``ki18n`` itself is located: it may be
a top-level package, vendored several directories deep inside the
application, or installed in a virtual environment.
* **Frozen (PyInstaller)**: ``sys._MEIPASS``; for builds without
``_MEIPASS`` the directory of the executable.
* **Otherwise**: starting at the directory of the main program (see
:func:`_main_directory`), the nearest directory that contains an
``i18n/`` folder, walking up through the parent directories. If no
directory on that path contains ``i18n/``, the directory of the main
program itself is returned.
"""
if is_frozen():
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
return Path(meipass)
# Onedir builds without _MEIPASS: fall back to the executable's directory.
# Onedir builds without _MEIPASS (shouldn't normally happen with
# the bundled spec, but fall back to the executable's directory).
return Path(sys.executable).resolve().parent
# Not frozen: this file lives at <root>/ki18n/paths.py, so the root is the
# parent of the package directory.
return Path(__file__).resolve().parent.parent
start = _main_directory()
for candidate in (start, *start.parents):
if (candidate / I18N_DIR_NAME).is_dir():
return candidate
return start
def _base_data_dir() -> Path:
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.
@@ -66,4 +101,4 @@ def data_dir(name: str) -> Path:
"""
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
return base_data_dir() / name
+128 -10
View File
@@ -1,4 +1,5 @@
"""Tests for ``ki18n.paths`` (PyInstaller bundle detection, per-user data directories)."""
"""Tests for ``ki18n.paths`` (PyInstaller bundle detection, frozen detection
and application root, per-user data directories)."""
import sys
from pathlib import Path
@@ -8,6 +9,27 @@ import pytest
from ki18n import paths
@pytest.fixture
def root(tmp_path) -> Path:
"""A resolved temporary directory (avoids symlink differences, e.g. on macOS)."""
return tmp_path.resolve()
@pytest.fixture
def not_frozen(monkeypatch):
monkeypatch.setattr(sys, "frozen", False, raising=False)
def run_as(monkeypatch, script: Path) -> None:
"""Pretend that ``script`` is the program that was started."""
monkeypatch.setattr(sys, "argv", [str(script)])
# ---------------------------------------------------------------------------
# is_frozen
# ---------------------------------------------------------------------------
def test_not_frozen_by_default(monkeypatch):
monkeypatch.setattr(sys, "frozen", False, raising=False)
assert paths.is_frozen() is False
@@ -23,26 +45,122 @@ def test_is_frozen_returns_bool(monkeypatch):
assert paths.is_frozen() is True
def test_not_frozen_uses_parent_of_package_directory(monkeypatch):
monkeypatch.setattr(sys, "frozen", False, raising=False)
assert paths.bundle_root() == Path(paths.__file__).resolve().parent.parent
# ---------------------------------------------------------------------------
# bundle_root: frozen applications
# ---------------------------------------------------------------------------
def test_frozen_uses_meipass(monkeypatch, tmp_path):
def test_frozen_uses_meipass(monkeypatch, root):
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False)
assert paths.bundle_root() == tmp_path
monkeypatch.setattr(sys, "_MEIPASS", str(root), raising=False)
assert paths.bundle_root() == root
def test_frozen_without_meipass_uses_executable_directory(monkeypatch, tmp_path):
executable = tmp_path.resolve() / "bin" / "app"
def test_frozen_without_meipass_uses_executable_directory(monkeypatch, root):
executable = root / "bin" / "app"
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(sys, "_MEIPASS", None, raising=False)
monkeypatch.setattr(sys, "executable", str(executable))
assert paths.bundle_root() == executable.parent
def test_bundle_root_returns_path():
def test_frozen_ignores_main_script_and_i18n_folders(monkeypatch, root):
(root / "app" / "i18n").mkdir(parents=True)
run_as(monkeypatch, root / "app" / "main.py")
bundle = root / "bundle"
bundle.mkdir()
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(sys, "_MEIPASS", str(bundle), raising=False)
assert paths.bundle_root() == bundle
# ---------------------------------------------------------------------------
# bundle_root: source checkout (not frozen)
# ---------------------------------------------------------------------------
def test_returns_directory_of_main_script_that_contains_i18n(not_frozen, monkeypatch, root):
(root / "i18n").mkdir()
run_as(monkeypatch, root / "main.py")
assert paths.bundle_root() == root
def test_walks_up_from_a_main_script_in_a_subdirectory(not_frozen, monkeypatch, root):
(root / "i18n").mkdir()
(root / "tools" / "cli").mkdir(parents=True)
run_as(monkeypatch, root / "tools" / "cli" / "main.py")
assert paths.bundle_root() == root
def test_nearest_directory_with_i18n_wins(not_frozen, monkeypatch, root):
(root / "i18n").mkdir()
(root / "app" / "i18n").mkdir(parents=True)
(root / "app" / "src").mkdir()
run_as(monkeypatch, root / "app" / "src" / "main.py")
assert paths.bundle_root() == root / "app"
def test_without_i18n_folder_returns_directory_of_main_script(not_frozen, monkeypatch, root):
(root / "app" / "src").mkdir(parents=True)
run_as(monkeypatch, root / "app" / "src" / "main.py")
assert paths.bundle_root() == root / "app" / "src"
def test_i18n_must_be_a_directory(not_frozen, monkeypatch, root):
(root / "i18n").write_text("not a directory", encoding="utf-8")
(root / "app").mkdir()
run_as(monkeypatch, root / "app" / "main.py")
assert paths.bundle_root() == root / "app"
@pytest.mark.parametrize(
"location",
[
"src/ki18n",
"lib/vendor/third_party/ki18n",
"a/b/c/d/e/f/ki18n",
"venv/lib/python3.12/site-packages/ki18n",
],
)
def test_result_does_not_depend_on_where_ki18n_is_located(
not_frozen, monkeypatch, root, location
):
(root / "app" / "i18n").mkdir(parents=True)
run_as(monkeypatch, root / "app" / "main.py")
# Pretend that the library lives at a different depth of the hierarchy.
monkeypatch.setattr(paths, "__file__", str(root / "app" / location / "paths.py"))
assert paths.bundle_root() == root / "app"
def test_relative_main_script_is_resolved_against_cwd(not_frozen, monkeypatch, root):
(root / "app" / "i18n").mkdir(parents=True)
monkeypatch.chdir(root / "app")
monkeypatch.setattr(sys, "argv", ["main.py"])
assert paths.bundle_root() == root / "app"
def test_matches_the_default_project_root_of_ki18n(not_frozen, monkeypatch, root):
from ki18n.ki18n import Ki18n
from support import EN, write_language
app = root / "app"
write_language(app, "en", EN)
run_as(monkeypatch, app / "main.py")
manager = Ki18n("en", local_root=root / "user")
assert manager.project_root == paths.bundle_root()
@pytest.mark.parametrize("argv", [[], [""], ["-c"], ["-"]])
def test_without_a_script_the_current_directory_is_used(not_frozen, monkeypatch, root, argv):
(root / "i18n").mkdir()
(root / "work").mkdir()
monkeypatch.chdir(root / "work")
monkeypatch.setattr(sys, "argv", argv)
# No i18n in the working directory: the walk up finds the parent's folder.
assert paths.bundle_root() == root
def test_bundle_root_returns_path(not_frozen):
assert isinstance(paths.bundle_root(), Path)
+2 -7
View File
@@ -193,13 +193,8 @@ def test_unicode_values(manager):
assert manager.t("welcome", name="Zoë 日本") == "Willkommen, Zoë 日本!"
# According to the README/docstring, the unformatted text should be returned on
# *any* formatting error ("a malformed or incomplete format string must not
# disrupt UI"). ``_format`` only catches KeyError, IndexError and ValueError, so
# these two cases currently raise AttributeError / TypeError. Remove the xfail
# marker once ``_format`` is fixed.
# @pytest.mark.xfail(strict=True, raises=(AttributeError, TypeError),
# reason="_format() does not catch AttributeError/TypeError")
# ``_format`` returns the unformatted text on *any* formatting error, including
# AttributeError (``{name.attr}``) and TypeError (``{name[x]}``).
@pytest.mark.parametrize(
("key", "expected"),
[("attr", "Wert: {name.nope}"), ("idx", "Wert: {name[x]}")],