Ki18n.__init__ now uses bundle_root() if project_root parameter is missing
This commit is contained in:
@@ -48,8 +48,10 @@ following entries in all supported languages:
|
||||
|
||||
The library searches the user's application data tree first, then the
|
||||
application's installation tree. The application name is the name of
|
||||
`project_root` (or the directory containing the executed program when
|
||||
`project_root` is omitted).
|
||||
`project_root` (or of the application root returned by
|
||||
`ki18n.paths.bundle_root()` when `project_root` is omitted). In a frozen
|
||||
(PyInstaller) build the name of the executable is used instead of the name of
|
||||
the temporary extraction directory.
|
||||
|
||||
- Linux and other Unix-like systems: `$XDG_DATA_HOME/<app-name>/i18n/`, or
|
||||
`~/.local/share/<app-name>/i18n/` when `XDG_DATA_HOME` is unset.
|
||||
@@ -126,8 +128,12 @@ the discovered mapping or override the display name for an installed language.
|
||||
initializes it; later calls return that same instance and ignore their
|
||||
configuration arguments. Configure it once near application startup.
|
||||
|
||||
If omitted, `project_root` is derived from the directory containing
|
||||
`sys.argv[0]`. The application installation resources are then read from
|
||||
If omitted, `project_root` is the application root returned by
|
||||
`ki18n.paths.bundle_root()`: in a frozen (PyInstaller) build `sys._MEIPASS`,
|
||||
otherwise the nearest directory that contains an `i18n/` folder, searching from
|
||||
the directory of `sys.argv[0]` upwards (or that directory itself if none
|
||||
contains one). The result does not depend on where `ki18n` itself is located.
|
||||
The application installation resources are then read from
|
||||
`<project_root>/i18n/`.
|
||||
|
||||
### Read and change the language
|
||||
@@ -181,24 +187,14 @@ no_count_text = i18n.p("files.found", None)
|
||||
|
||||
| Count | Category |
|
||||
| --- | --- |
|
||||
| `0` (also `0.0` and `-0.0`) | `zero` |
|
||||
| `1` (also `1.0`) and `-1` | `one` |
|
||||
| Any other number (`2`, `-2`, `0.5`, `-1.5`, `2.5`, ...) | `many` |
|
||||
| `0` | `zero` |
|
||||
| `1` | `one` |
|
||||
| Greater than `1` | `many` |
|
||||
| `None` | `none` |
|
||||
|
||||
The count may be an integer or a float, positive or negative. The category is
|
||||
chosen from its absolute value, so `-1` selects `one` like `1`. The selected
|
||||
text follows the same current language, English, `default`, and key fallback
|
||||
order as `t()`. The count is available to formatting as `{count}`; `#count` is
|
||||
also replaced directly and inserts the count as Python prints it (for example
|
||||
`2.5` or `-3`). Use `{count}` with a format specification to control the
|
||||
number format:
|
||||
|
||||
```python
|
||||
# "many": "{count:.1f} files"
|
||||
i18n.p("files.found", 2.5) # "2.5 files"
|
||||
i18n.p("files.found", -2) # "-2.0 files"
|
||||
```
|
||||
Negative counts raise `ValueError`. The selected text follows the same current
|
||||
language, English, `default`, and key fallback order as `t()`. The count is
|
||||
available to formatting as `{count}`; `#count` is also replaced directly.
|
||||
|
||||
### Listen for language changes
|
||||
|
||||
@@ -249,7 +245,7 @@ it is intended for compatibility and inspection rather than normal lookup.
|
||||
|
||||
- `ValueError`: unknown language, invalid JSON, invalid translation structure,
|
||||
missing or empty `language` metadata, plural entries missing `one` or
|
||||
or `many`.
|
||||
`many`, or a negative plural count.
|
||||
- `FileNotFoundError`: the internal default language folder or its
|
||||
`strings.json` is unavailable at construction, a selected language has no
|
||||
usable translation file, or no current/English help file can be found.
|
||||
|
||||
+7
-40
@@ -61,7 +61,7 @@ my-app/
|
||||
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]
|
||||
Ki18n("en") # default language; project_root is bundle_root()
|
||||
|
||||
print(i18n.t("greeting", name="Ada")) # Hello, Ada!
|
||||
print(i18n.p("files.found", 3)) # 3 files found
|
||||
@@ -227,8 +227,8 @@ Creates (or returns) the singleton manager and loads the default language.
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `default_language` | Language that is active after construction. Also the language that is listed first and that must be shipped with the application. Normalized (`"de-at"` → `"de_AT"`). |
|
||||
| `project_root` | Application directory that contains the installed `i18n/` folder. `~` is expanded. If omitted, the directory of `sys.argv[0]` is used (relative paths are resolved against the current working directory). |
|
||||
| `local_root` | The application's per-user directory; user resources are read from its `i18n/` subfolder. `~` is expanded. If omitted: `<user data dir>/<name of project_root>` (see below). |
|
||||
| `project_root` | Application directory that contains the installed `i18n/` folder. `~` is expanded. If omitted, [`ki18n.paths.bundle_root()`](#7-ki18npaths-module-reference) is used: the application root, independent of where ki18n is located. |
|
||||
| `local_root` | The application's per-user directory; user resources are read from its `i18n/` subfolder. `~` is expanded. If omitted: `<user data dir>/<application name>` (see below). The application name is the name of `project_root`; in a frozen one-file build it is the name of the executable (without extension), because the extraction directory changes on every start. |
|
||||
|
||||
Default user data directory (used when `local_root` is omitted):
|
||||
|
||||
@@ -558,43 +558,8 @@ Notes:
|
||||
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` (internal)
|
||||
|
||||
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"))
|
||||
```
|
||||
- `Ki18n` uses `bundle_root()` as the default `project_root`, so the two always
|
||||
agree. Pass `project_root` explicitly to override it.
|
||||
|
||||
---
|
||||
|
||||
@@ -639,3 +604,5 @@ These points are based on reading the current source code.
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
--- a/src/ki18n/ki18n.py
|
||||
+++ b/src/ki18n/ki18n.py
|
||||
@@ -33,6 +33,8 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
+from .paths import bundle_root, is_frozen
|
||||
+
|
||||
DEFAULT_LANGUAGE = "en"
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -71,7 +73,9 @@
|
||||
"""A process-wide internationalization manager.
|
||||
|
||||
``project_root`` is the application directory containing its installation
|
||||
- ``i18n`` directory. If omitted, it is derived from ``sys.argv[0]``.
|
||||
+ ``i18n`` directory. If omitted, the application root returned by
|
||||
+ :func:`ki18n.paths.bundle_root` is used, which does not depend on where
|
||||
+ ``ki18n`` itself is located.
|
||||
Resources under the user's application data directory take precedence over
|
||||
resources installed with the application: ``strings.json`` files are merged
|
||||
key by key (a subset is enough), other files such as ``help.md`` are
|
||||
@@ -100,8 +104,8 @@
|
||||
"""Create the manager (only the first construction has an effect).
|
||||
|
||||
``project_root`` is the directory containing the installed ``i18n``
|
||||
- folder. ``local_root`` is the application's per-user directory (for
|
||||
- example ``~/.local/share/my-app``); user resources are read from its
|
||||
+ folder; if omitted it is :func:`ki18n.paths.bundle_root`.
|
||||
+ ``local_root`` is the application's per-user directory (for example ``~/.local/share/my-app``); user resources are read from its
|
||||
``i18n`` subfolder. If omitted, the directory is derived from the
|
||||
user data directory and the name of ``project_root``. ``key_aliases``
|
||||
maps former keys to current keys for the user's strings files.
|
||||
@@ -115,17 +119,14 @@
|
||||
raise ValueError(f"Invalid default language: {default_language!r}") from exc
|
||||
|
||||
if project_root is None:
|
||||
- executable = Path(sys.argv[0])
|
||||
- if not executable.is_absolute():
|
||||
- executable = Path.cwd() / executable
|
||||
- root = executable.resolve().parent
|
||||
+ root = bundle_root().resolve()
|
||||
else:
|
||||
root = Path(project_root).expanduser().resolve()
|
||||
|
||||
self.default_language = default_language
|
||||
self.project_root = root
|
||||
self.i18n_root = root / "i18n"
|
||||
- self._app_name = root.name or "app"
|
||||
+ self._app_name = self._default_app_name(root)
|
||||
if local_root is None:
|
||||
self.local_root = self._user_data_root() / self._app_name
|
||||
else:
|
||||
@@ -149,6 +150,20 @@
|
||||
self._initialized = True
|
||||
|
||||
@staticmethod
|
||||
+ def _default_app_name(root: Path) -> str:
|
||||
+ """Name used for the default per-user data directory.
|
||||
+
|
||||
+ Normally the name of ``root``. In a frozen one-file build ``root`` is a
|
||||
+ temporary extraction directory whose name changes on every start, so the
|
||||
+ name of the executable is used instead.
|
||||
+ """
|
||||
+ if is_frozen():
|
||||
+ meipass = getattr(sys, "_MEIPASS", None)
|
||||
+ if meipass and root == Path(meipass).resolve():
|
||||
+ return Path(sys.executable).stem or "app"
|
||||
+ return root.name or "app"
|
||||
+
|
||||
+ @staticmethod
|
||||
def _user_data_root() -> Path:
|
||||
"""Return the conventional per-user application data directory."""
|
||||
if os.name == "nt":
|
||||
+23
-8
@@ -34,6 +34,8 @@ from typing import Any
|
||||
|
||||
from . import paths
|
||||
|
||||
from .paths import bundle_root, is_frozen
|
||||
|
||||
DEFAULT_LANGUAGE = "en"
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -72,7 +74,9 @@ class Ki18n:
|
||||
"""A process-wide internationalization manager.
|
||||
|
||||
``project_root`` is the application directory containing its installation
|
||||
``i18n`` directory. If omitted, it is derived from ``sys.argv[0]``.
|
||||
``i18n`` directory. If omitted, the application root returned by
|
||||
:func:`ki18n.paths.bundle_root` is used, which does not depend on where
|
||||
``ki18n`` itself is located.
|
||||
Resources under the user's application data directory take precedence over
|
||||
resources installed with the application: ``strings.json`` files are merged
|
||||
key by key (a subset is enough), other files such as ``help.md`` are
|
||||
@@ -101,8 +105,8 @@ class Ki18n:
|
||||
"""Create the manager (only the first construction has an effect).
|
||||
|
||||
``project_root`` is the directory containing the installed ``i18n``
|
||||
folder. ``local_root`` is the application's per-user directory (for
|
||||
example ``~/.local/share/my-app``); user resources are read from its
|
||||
folder; if omitted it is :func:`ki18n.paths.bundle_root`.
|
||||
``local_root`` is the application's per-user directory (for example ``~/.local/share/my-app``); user resources are read from its
|
||||
``i18n`` subfolder. If omitted, the directory is derived from the
|
||||
user data directory and the name of ``project_root``. ``key_aliases``
|
||||
maps former keys to current keys for the user's strings files.
|
||||
@@ -116,17 +120,14 @@ class Ki18n:
|
||||
raise ValueError(f"Invalid default language: {default_language!r}") from exc
|
||||
|
||||
if project_root is None:
|
||||
executable = Path(sys.argv[0])
|
||||
if not executable.is_absolute():
|
||||
executable = Path.cwd() / executable
|
||||
root = executable.resolve().parent
|
||||
root = bundle_root().resolve()
|
||||
else:
|
||||
root = Path(project_root).expanduser().resolve()
|
||||
|
||||
self.default_language = default_language
|
||||
self.project_root = root
|
||||
self.i18n_root = root / "i18n"
|
||||
self._app_name = root.name or "app"
|
||||
self._app_name = self._default_app_name(root)
|
||||
if local_root is None:
|
||||
self.local_root = self._user_data_root() / self._app_name
|
||||
else:
|
||||
@@ -149,6 +150,20 @@ class Ki18n:
|
||||
self._english_translations = translations
|
||||
self._initialized = True
|
||||
|
||||
@staticmethod
|
||||
def _default_app_name(root: Path) -> str:
|
||||
"""Name used for the default per-user data directory.
|
||||
|
||||
Normally the name of ``root``. In a frozen one-file build ``root`` is a
|
||||
temporary extraction directory whose name changes on every start, so the
|
||||
name of the executable is used instead.
|
||||
"""
|
||||
if is_frozen():
|
||||
meipass = getattr(sys, "_MEIPASS", None)
|
||||
if meipass and root == Path(meipass).resolve():
|
||||
return Path(sys.executable).stem or "app"
|
||||
return root.name or "app"
|
||||
|
||||
@staticmethod
|
||||
def _user_data_root() -> Path:
|
||||
"""Return the conventional per-user application data directory."""
|
||||
|
||||
@@ -176,7 +176,7 @@ def test_default_resources_are_not_reloaded_from_disk_on_lookup(env):
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# project_root derived from sys.argv[0]
|
||||
# project_root derived from bundle_root()
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -196,6 +196,54 @@ def test_relative_argv0_is_resolved_against_cwd(env, monkeypatch):
|
||||
assert manager.project_root == env.app_dir
|
||||
|
||||
|
||||
def test_default_project_root_is_the_application_root_of_a_nested_entry_point(
|
||||
env, monkeypatch
|
||||
):
|
||||
env.install_defaults()
|
||||
script = env.app_dir / "tools" / "cli" / "main.py"
|
||||
script.parent.mkdir(parents=True)
|
||||
monkeypatch.setattr(sys, "argv", [str(script)])
|
||||
manager = Ki18n("en", local_root=env.user_dir)
|
||||
assert manager.project_root == env.app_dir
|
||||
|
||||
|
||||
def test_default_project_root_does_not_depend_on_the_location_of_ki18n(env, monkeypatch):
|
||||
from ki18n import paths
|
||||
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")])
|
||||
monkeypatch.setattr(
|
||||
paths, "__file__", str(env.app_dir / "lib" / "vendor" / "ki18n" / "paths.py")
|
||||
)
|
||||
assert Ki18n("en", local_root=env.user_dir).project_root == env.app_dir
|
||||
|
||||
|
||||
def test_default_project_root_comes_from_bundle_root(env, monkeypatch):
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr("ki18n.ki18n.bundle_root", lambda: env.app_dir)
|
||||
manager = Ki18n("en", local_root=env.user_dir)
|
||||
assert manager.project_root == env.app_dir
|
||||
|
||||
|
||||
def test_explicit_project_root_does_not_use_bundle_root(env, monkeypatch):
|
||||
env.install_defaults()
|
||||
|
||||
def unexpected():
|
||||
raise AssertionError("bundle_root() must not be called")
|
||||
|
||||
monkeypatch.setattr("ki18n.ki18n.bundle_root", unexpected)
|
||||
manager = Ki18n("en", project_root=env.app_dir, local_root=env.user_dir)
|
||||
assert manager.project_root == env.app_dir
|
||||
|
||||
|
||||
def test_frozen_application_uses_meipass_as_project_root(env, monkeypatch):
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr(sys, "frozen", True, raising=False)
|
||||
monkeypatch.setattr(sys, "_MEIPASS", str(env.app_dir), raising=False)
|
||||
manager = Ki18n("en", local_root=env.user_dir)
|
||||
assert manager.project_root == env.app_dir
|
||||
|
||||
|
||||
def test_local_root_derived_from_project_directory_name(env, monkeypatch):
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")])
|
||||
@@ -203,6 +251,24 @@ def test_local_root_derived_from_project_directory_name(env, monkeypatch):
|
||||
assert manager.local_root == env.data_home / "myapp"
|
||||
|
||||
|
||||
def test_local_root_for_frozen_application_uses_executable_name(env, monkeypatch):
|
||||
# In a one-file build the project root is a temporary directory with a
|
||||
# changing name; the user data directory must stay stable.
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr(sys, "frozen", True, raising=False)
|
||||
monkeypatch.setattr(sys, "_MEIPASS", str(env.app_dir), raising=False)
|
||||
monkeypatch.setattr(sys, "executable", str(env.tmp / "bin" / "Cool App.exe"))
|
||||
manager = Ki18n("en")
|
||||
assert manager.local_root == env.data_home / "Cool App"
|
||||
|
||||
|
||||
def test_local_root_for_explicit_project_root_uses_its_name(env, monkeypatch):
|
||||
env.install_defaults()
|
||||
monkeypatch.setattr(sys, "frozen", False, raising=False)
|
||||
manager = Ki18n("en", project_root=env.app_dir)
|
||||
assert manager.local_root == env.data_home / "myapp"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Per-user data directory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user