diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..f4665fd --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + + { + "name": "Python Debugger: Current File", + "type": "debugpy", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal", + "python": "${workspaceFolder}/.venv/bin/python" + } + ] +} \ No newline at end of file diff --git a/LICENSE b/LICENSE index 33561f8..ab45a90 100644 --- a/LICENSE +++ b/LICENSE @@ -1,18 +1,21 @@ MIT License -Copyright (c) 2026 ingoadmin +Copyright (c) 2026 ikoch -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and -associated documentation files (the "Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the -following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO -EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 4e85863..7b7fe82 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,259 @@ # ki18n -Internationalization (stings and help) of python projects \ No newline at end of file +Reusable, file-backed internationalization for Python applications. Translation +strings and program help are stored outside Python source in language-specific +resource folders. The selected language is set by the operating system locale +and can be overridden by the user. + +## Resource layout + +Each language folder can contain `strings.json` and `help.md`: + +```text +/i18n/ +├── en/ +│ ├── strings.json +│ └── help.md +├── de/ +│ ├── strings.json +│ └── help.md +├── de_DE/ +│ ├── strings.json +│ └── help.md +└── de_AT/ + ├── strings.json + └── help.md +``` + +Each language folder must include `strings.json` with a non-empty `language` +entry. The folder name is the language ID and the `language` value is its +display name. `get_available_languages()` discovers this mapping from both +the user data and installed `i18n` trees. + +To use the included textual dialogs the strings.json must include the +following entries in all supported languages: + +```json +{ + "language": "English", + "app.title": "Sample application", + "title_select_language": "Select language", + "title_help": "Example help", + "btn_close": "Close", + "btn_cancel": "Cancel", + "msg_help_missing": "Help file is missing!", +} +``` + + +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). + +- Linux and other Unix-like systems: `$XDG_DATA_HOME//i18n/`, or + `~/.local/share//i18n/` when `XDG_DATA_HOME` is unset. +- macOS: `~/Library/Application Support//i18n/` when + `XDG_DATA_HOME` is unset. +- Windows: `%LOCALAPPDATA%//i18n/`. +- Installation resources: `/i18n/`. + +User resources take precedence over installed resources. Language discovery +checks the user data tree first, then the installed tree; when both contain +the same language, the user data `language` value is used. The user data may +contain only a subset of the language strings if the language strings at the +project root contain the complete translations. + +The default language must still have an installed folder and `strings.json`. +Within each resource tree, locale lookup tries the most specific ID and then +its parents. For example, `de_CH` tries `de_CH`, then `de`; `de_DE.UTF-8` is +normalized to `de_DE`, then tries `de`. Language IDs are case-insensitive. +Hyphens are accepted as separators, and the returned language ID is normalized +(for example, `DE-de.utf8` becomes `de_DE`). When the requested language is not +configured, the returned ID is the most specific configured parent language. +For example, with only `de` configured, `set_language("de_CH")` selects `de`. + +## Translation files + +`strings.json` is a flat keyspace. Values are either strings or plural objects: + +```json +{ + "language": "English", + "button.save": "Save", + "status.generated": "Generated: {files}", + "files.found": { + "zero": "No files", + "one": "One file", + "many": "#count files" + } +} +``` + +Plural objects must include `one` and `many`. The `zero` and `none` categories +are optional; if omitted, each defaults to that entry's `many` text. `p()` +replaces `#count` and formats `{count}` along with any other keyword +placeholders. + +## Help + +The help.md is a complete document that contains all the help as markdown. +It also is located in the country specific folders and can be overwritten +by the user. It may be displayed with the textual class HelpScreen. + + +## API + +### Create and configure the manager + +```python +from pathlib import Path +from ki18n import Ki18n + +manager = Ki18n( + default_language="en", + project_root=Path(__file__).resolve().parent, +) +``` + +The default language is `en`. Each language's display name is read from the +`language` entry in its `strings.json`. The default language folder and its +valid `strings.json` must exist under `/i18n/` during +construction. Language folders under the user data tree can add languages to +the discovered mapping or override the display name for an installed language. + +`Ki18n` is a process-wide singleton. Only the first successful construction +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 +`/i18n/`. + +### Read and change the language + +```python +language = i18n.get_language() +default = i18n.get_default_language() +languages = i18n.get_available_languages() + +i18n.set_language("de") +``` + +`get_available_languages()` returns a copy of the mapping discovered from +user and installed resources. Language IDs are case-insensitive. A regional +variant can be requested when its parent +language is configured, even if the regional language is not configured; for +example, `set_language("de_CH")` selects `de` when only `de` is configured. +`get_language()` then returns `de`, which can be used to index the available +languages mapping. Unknown languages raise `ValueError`. A language change +loads and validates its translation file before changing state. Selecting the +active language is a no-op. + +### Translate strings + +```python +save_label = i18n.t("button.save") +message = i18n.t("status.generated", files="main.py") +fallback = i18n.t("missing.key", default="Fallback text") +``` + +`t(key, default=None, **kwargs)` uses this fallback order: + +1. Current language. +2. English. +3. The supplied `default`. +4. The key itself. + +Keyword arguments are applied with `str.format()`. If formatting fails because +a placeholder is missing or the format string is invalid, the unformatted +text is returned. Calling `t()` for a plural object raises `ValueError`; use +`p()` for pluralized entries. + +### Translate pluralized strings + +```python +files_text = i18n.p("files.found", 3) +no_count_text = i18n.p("files.found", None) +``` + +`p(key, count, default=None, **kwargs)` selects a category as follows: + +| Count | Category | +| --- | --- | +| `0` | `zero` | +| `1` | `one` | +| Greater than `1` | `many` | +| `None` | `none` | + +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 + +```python +def language_changed(code: str) -> None: + refresh_ui() + +i18n.add_language_change_listener(language_changed) +i18n.remove_language_change_listener(language_changed) +``` + +Listeners receive the normalized, configured language ID. Registering the same +callback twice has no additional effect. The compatibility aliases +`add_listener()` and `remove_listener()` are also available. + +### Read help + +```python +help_text = i18n.get_help() +``` + +`get_help()` returns the active language's `help.md`, following the same +regional and user-resource lookup rules. If no matching help file exists, it +tries English. If neither is available, it raises `FileNotFoundError`. + +### Module-style compatibility handle + +For applications that prefer the earlier module-style access, the module +exports a lazy `i18n` handle for code that prefers a module-style instance: + +```python +from ki18n import Ki18n, i18n + +# Configure the singleton first when custom settings are needed. +Ki18n("en", project_root="/path/to/app") +i18n.set_language("de") +print(i18n.t("button.save")) +``` + +The handle initializes the singleton with default settings on first use if no +`Ki18n` instance has been constructed yet. `I18n` and `ki18n` remain +available as compatibility aliases for the class. + +`_get_translations()` returns a deep copy of the current translation mapping; +it is intended for compatibility and inspection rather than normal lookup. + +## Errors + +- `ValueError`: unknown language, invalid JSON, invalid translation structure, + missing or empty `language` metadata, plural entries missing `one` or + `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. + +## Tests + +The test suite uses [pytest](https://docs.pytest.org/) and +[pytest-asyncio](https://pytest-asyncio.readthedocs.io/); the Textual dialogs are +driven with Textual's `Pilot`. Tests create temporary application and user-data +directories and do not access real user language resources. + +Install the development dependencies and run the tests from the repository root: + +```sh +uv sync # or: pip install -e . --group dev +uv run pytest # or: python3 -m pytest +``` diff --git a/demoapp.py b/demoapp.py new file mode 100644 index 0000000..5cce714 --- /dev/null +++ b/demoapp.py @@ -0,0 +1,52 @@ +from pathlib import Path + +# set to the real folder where ki18n lives +from ki18n.ki18n import Ki18n, i18n + + +def main() -> None: + print("setting the default language and the available languages") + manager = Ki18n( + default_language="en", + project_root=Path(__file__).resolve().parent, + ) + default = i18n.get_default_language() + print(f"Default : {default}") + available = i18n.get_available_languages() + print(f"Available : {available}") + + langstr = available[i18n.get_language()] + title = i18n.t("app.title") + print(f"Translated title in {langstr} : {title}") + + i18n.set_language("de") + langstr = available[i18n.get_language()] + title = i18n.t("app.title") + print(f"Translated title in {langstr} : {title}") + + i18n.set_language("en-US") + out = i18n.p("files.found", 0) + print(f"Pluralized string for zero files : {out}") + out = i18n.p("files.found", 1) + print(f"Pluralized string for one files : {out}") + out = i18n.p("files.found", 5) + print(f"Pluralized string for five files : {out}") + i18n.set_language("de_CH") + langstr = available[i18n.get_language()] + print(f"The same in {langstr}") + out = i18n.p("files.found", 0) + print(f"Pluralized string for zero files : {out}") + out = i18n.p("files.found", 1) + print(f"Pluralized string for one files : {out}") + out = i18n.p("files.found", 5) + print(f"Pluralized string for five files : {out}") + + filenumber = 6 + out = i18n.t("status.generated", files=filenumber) + print(f"String with placeholder for files : {out}") + + + + +if __name__ == "__main__": + main() diff --git a/doc/API.md b/doc/API.md new file mode 100644 index 0000000..3766453 --- /dev/null +++ b/doc/API.md @@ -0,0 +1,592 @@ +# ki18n API Documentation + +ki18n is a small, file-backed internationalization library for Python +applications. Translations live in plain JSON files, can be overridden per user +without touching the installed application, and can be consumed through a +process-wide manager (`Ki18n`) or ready-made [Textual](https://textual.textualize.io/) +dialogs. + +- Python: 3.10 or newer +- Runtime dependency: `textual` (only needed for the dialogs in + `ki18n.help_screen` and `ki18n.language_select_screen`; `ki18n.ki18n` itself + uses the standard library only) + +## Contents + +1. [Quick start](#1-quick-start) +2. [Concepts](#2-concepts) +3. [Resource files](#3-resource-files) +4. [`ki18n.ki18n` module reference](#4-ki18nki18n-module-reference) +5. [Resolution rules](#5-resolution-rules) +6. [Textual dialogs](#6-textual-dialogs) +7. [`ki18n.paths` module reference](#7-ki18npaths-module-reference) +8. [Errors and logging](#8-errors-and-logging) +9. [Known limitations](#9-known-limitations) + +--- + +## 1. Quick start + +Project layout: + +```text +my-app/ +├── main.py +└── i18n/ + ├── en/ + │ ├── strings.json + │ └── help.md + └── de/ + ├── strings.json + └── help.md +``` + +`i18n/en/strings.json`: + +```json +{ + "language": "English", + "greeting": "Hello, {name}!", + "files.found": { + "zero": "No files found", + "one": "One file found", + "many": "#count files found" + } +} +``` + +`main.py`: + +```python +from ki18n.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] + +print(i18n.t("greeting", name="Ada")) # Hello, Ada! +print(i18n.p("files.found", 3)) # 3 files found + +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`. + +--- + +## 2. Concepts + +### Singleton manager + +`Ki18n` is a process-wide singleton. Only the **first** construction has an +effect; later `Ki18n(...)` calls return the same instance and ignore their +arguments. If the first construction fails (for example because resources are +missing), the instance stays uninitialized and construction can simply be +retried. + +The module-level handle `i18n` is a lazy proxy. It creates the singleton with +default arguments on first attribute access, so an application can still call +`Ki18n(...)` with its own configuration before the first use. + +### Installed and user resources + +Resources are read from two locations: + +| Location | Path | Purpose | +| --- | --- | --- | +| Installed | `/i18n/` | Shipped with the application. Must contain the default language. | +| User | `/i18n/` | Optional per-user customization and additional languages. | + +User resources take precedence over installed ones. `strings.json` files are +**merged key by key** (a user file may contain just the keys it wants to change +or add), whereas `help.md` is **replaced as a whole**. + +### Language IDs + +Language IDs are normalized before use: + +| Input | Normalized | +| --- | --- | +| `en`, `EN` | `en` | +| `de-de`, `de_de`, `DE_de` | `de_DE` | +| `de_DE.UTF-8`, `de_DE@euro` | `de_DE` (encoding/modifier suffixes removed) | +| `zh-hant-tw` | `zh_Hant_TW` (script: title case, region: upper case) | +| `es_419` | `es_419` (three-digit region) | + +Parts may only contain ASCII letters and digits. Anything else (empty parts, +`/`, spaces, non-strings, …) is invalid. + +A regional ID falls back to progressively broader parents: +`sr_Latn_RS` → `sr_Latn` → `sr`. Folder names are matched case-insensitively +on every platform. + +--- + +## 3. Resource files + +### Directory layout + +```text +/i18n//strings.json +/i18n//help.md (optional) +``` + +The folder name is a language ID (`en`, `de`, `de_AT`, …). It is normalized, so +`de-at` and `de_AT` name the same language. Two folders that normalize to the +same ID are a configuration error (an exception for installed resources, a +warning for user resources). Files directly inside `i18n/` and folders without +a `strings.json` are ignored for language discovery. + +### `strings.json` + +A UTF-8 encoded JSON object (a byte-order mark is not accepted). Every value is +either a **string** or a **plural object**. + +```json +{ + "language": "Deutsch", + "app.title": "Beispiel", + "welcome": "Willkommen, {name}!", + "files.found": { + "zero": "Keine Datei gefunden", + "one": "Eine Datei gefunden", + "many": "#count Dateien gefunden", + "none": "Anzahl unbekannt" + } +} +``` + +| Rule | Details | +| --- | --- | +| `language` | Display name of the language (non-empty string). Required in every installed file. Optional in user files that customize an installed language (the installed name is inherited). Required in user files that introduce a new language. | +| Keys | Arbitrary strings. Dots are only a naming convention. | +| String values | Used by `t()` (and by `p()` as a non-plural fallback). May contain `str.format` placeholders such as `{name}`. | +| Plural objects | Keys must be from `zero`, `one`, `many`, `none`; values must be strings. `one` and `many` are **mandatory**. | +| `zero` / `none` | Default to the text of `many` when omitted. | +| `#count` | Inside plural texts, replaced by the count. `{count}` works as well. | + +Invalid files (bad JSON, wrong value types, missing `one`/`many`, unknown plural +categories, invalid UTF-8, …) are rejected with `ValueError`. For installed files +this is an error; for user files it is logged and the file is ignored as a +whole (see [Errors and logging](#8-errors-and-logging)). + +### `help.md` + +A Markdown document for the help dialog (`Ki18n.get_help()` / +`HelpScreen`). Read as UTF-8. + +### Customizing as a user + +To change some translations of an installed language, create +`/i18n//strings.json` with only the affected keys: + +```json +{ "greeting": "Moin, {name}!" } +``` + +To add a whole new language, provide a complete file including `language`: + +```json +{ "language": "Français", "greeting": "Bonjour, {name} !" } +``` + +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 +``` + +### Module-level names + +| Name | Description | +| --- | --- | +| `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`. | + +### `class Ki18n` + +```python +Ki18n( + default_language: str = "en", + project_root: str | Path | None = None, + local_root: str | Path | None = None, +) +``` + +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: `/` (see below). | + +Default user data directory (used when `local_root` is omitted): + +| Platform | Directory | +| --- | --- | +| Windows | `%LOCALAPPDATA%`, otherwise `~/AppData/Local` | +| Linux and other POSIX | `$XDG_DATA_HOME`, otherwise `~/.local/share` | +| macOS | `$XDG_DATA_HOME`, otherwise `~/Library/Application Support` | + +**Raises** + +| Exception | Condition | +| --- | --- | +| `ValueError` | `default_language` is not a valid language ID. | +| `FileNotFoundError` | The installed `i18n/` directory, the default language folder or its `strings.json` does not exist. | +| `ValueError` | An installed `strings.json` is invalid, lacks `language`, or two installed folders normalize to the same ID. | + +**Attributes** (read them, do not modify them) + +| Attribute | Type | Description | +| --- | --- | --- | +| `default_language` | `str` | Normalized default language. | +| `project_root` | `Path` | Resolved application directory. | +| `i18n_root` | `Path` | `project_root / "i18n"`. | +| `local_root` | `Path` | Per-user directory. | +| `available_languages` | `dict[str, str]` | Language ID → display name, in discovery order. Prefer `get_available_languages()`. | + +The manager is not synchronized: it performs no locking, so use it from one +thread or guard calls externally. + +--- + +#### `get_language() -> str` + +Returns the ID of the active language (always one of the keys of +`get_available_languages()`). + +#### `get_default_language() -> str` + +Returns the normalized default language passed to the constructor. + +#### `get_available_languages() -> dict[str, str]` + +Returns a new dictionary that maps language IDs to display names. The default +language comes first, the rest is sorted by display name (case-insensitive). +Languages come from the installed folder and the user folder; see +[Resolution rules](#5-resolution-rules). Modifying the returned dictionary has +no effect on the manager. + +```python +>>> i18n.get_available_languages() +{'en': 'English', 'de': 'Deutsch', 'fr': 'Français'} +``` + +#### `set_language(code: str) -> None` + +Activates a language and notifies the listeners. + +1. `code` is normalized. An invalid ID raises `ValueError`. +2. If the language is not available, the most specific available parent is used + (`de_CH` → `de`). If none is available, `ValueError("Unknown language: ...")` + is raised. +3. If the resolved language is already active, nothing happens (no reload, no + notification). +4. The language's files are loaded and validated **before** the state changes. + If loading fails (`FileNotFoundError` or `ValueError`), the previous language + stays active and no listener is called. +5. Listeners are called with the resolved language ID. + +Translations are read from disk on each actual switch, so changes to files +become visible after switching away and back. + +#### `t(key: str, default: str | None = None, **kwargs) -> str` + +Translates a simple (non-plural) key. + +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)). +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. + +An empty string is a valid translation and is returned as is. + +**Raises** `ValueError` if the key refers to a plural object; use `p()`. + +```python +i18n.t("welcome", name="Ada") # "Welcome, Ada!" +i18n.t("missing.key") # "missing.key" +i18n.t("missing.key", default="Fallback") # "Fallback" +i18n.t("wert", n=42) # formats e.g. "{n:05d}" -> "00042" +``` + +#### `p(key: str, count: int | float | None, default: str | None = None, **kwargs) -> str` + +Translates a pluralized key. + +The category is chosen from `count`: + +| `count` | Category | +| --- | --- | +| `None` | `none` | +| `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 +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. + +**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", 5) # "5 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 +``` + +#### `get_help() -> str` + +Returns the Markdown help text of the active language, falling back to the +English help text if the active language has none. See +[Resolution rules](#5-resolution-rules) for the search order. The file is read +on every call. + +**Raises** `FileNotFoundError` if no help file is found. + +#### `add_language_change_listener(callback: Callable[[str], None]) -> None` + +Registers a callback that is called with the new language ID after each +successful change of the active language. Registering the same callback again +has no effect. + +Details: + +- Callbacks run synchronously, in registration order, after the new language is + active (calling `t()` inside a callback returns the new texts). +- A callback may remove itself while it is being notified. +- Exceptions raised by a callback propagate out of `set_language()`; the new + language is already active at that point and later callbacks are not called. + +#### `remove_language_change_listener(callback: Callable[[str], None]) -> None` + +Unregisters a callback. Removing a callback that is not registered is harmless. + +#### `add_listener` / `remove_listener` + +Compatibility aliases for the two methods above. + +#### Internal helpers + +Names starting with an underscore (for example `_get_translations()`, which +returns a deep copy of the active translation mapping) are not part of the +public API and may change. + +--- + +## 5. Resolution rules + +### Available languages + +1. All folders in the user and installed `i18n/` roots are scanned. +2. A language is **available** if its folder contains a valid `strings.json` + with a non-empty `language` entry. +3. The display name comes from the user file if it defines one, otherwise from + the installed file. A user file without `language` that customizes an + installed language inherits the installed name. +4. A user folder for a language that is **not** installed and whose file lacks + `language` is ignored with a warning. +5. Invalid **user** folders and files are ignored with a warning. Invalid + **installed** folders and files raise `ValueError`. + +### Loading a language (`strings.json`) + +For a language such as `de_AT`, files are merged from lowest to highest +priority: + +1. installed `de` +2. installed `de_AT` +3. user `de` +4. user `de_AT` + +Later files override earlier ones key by key. A plural object replaces the whole +installed entry for that key. If no file exists for the language, +`FileNotFoundError` is raised. + +### Finding a single file (`help.md`) + +The first existing file wins, in this order (for `de_AT`): + +1. user `de_AT` +2. user `de` +3. installed `de_AT` +4. installed `de` + +If nothing is found and the language is not English, the same search is repeated +for `en`. Otherwise `FileNotFoundError` is raised. + +### Translating a key + +`t()` and `p()`: active language (all merged layers) → English (merged the same +way; optional when another default language is used and no English resources +exist) → `default` argument → the key. + +--- + +## 6. Textual dialogs + +Both dialogs are `textual.screen.ModalScreen` subclasses that read their texts +from the active language through `i18n`. They require `textual` to be installed. + +```python +from ki18n.help_screen import HelpScreen +from ki18n.language_select_screen import LanguageSelectScreen +``` + +### Required translation keys + +| Key | Used by | Meaning | +| --- | --- | --- | +| `title_select_language` | `LanguageSelectScreen` | Dialog title. | +| `btn_cancel` | `LanguageSelectScreen` | Cancel button label. | +| `title_help` | `HelpScreen` | Dialog title. | +| `btn_close` | `HelpScreen` | Close button label. | +| `msg_help_missing` | `HelpScreen` | Shown instead of the help text when no `help.md` exists. | + +Missing keys fall back to English and finally to the key name. + +### `HelpScreen(toc: bool = True)` + +`ModalScreen[None]`. Shows `i18n.get_help()` in a scrollable Markdown viewer. + +| Parameter | Description | +| --- | --- | +| `toc` | Show the Markdown table of contents. | + +- Closes with the **Close** button or Esc; the dismiss result is `None`. +- Widget IDs: `#help-title`, `#help-text`, `#help-close`. + +```python +self.push_screen(HelpScreen()) +self.push_screen(HelpScreen(toc=False)) +``` + +### `LanguageSelectScreen()` + +`ModalScreen[str | None]`. Shows one button per available language (in the order +of `get_available_languages()`); the active language is highlighted with the +`primary` button variant. + +- Result: the selected language ID (for example `"de"` or `"de_AT"`), or `None` + if the dialog is cancelled (**Cancel** button or Esc). +- The dialog does **not** change the language itself; apply the result with + `i18n.set_language()`. +- Widget IDs: `#language-dialog`, `#language-title`, `#language-options`, + `#lang-` (for example `#lang-de_AT`), `#language-dialog-buttons`, + `#language-cancel`. + +```python +from textual.app import App + +class MyApp(App): + def action_choose_language(self) -> None: + def apply(selected: str | None) -> None: + if selected is not None and selected != i18n.get_language(): + i18n.set_language(selected) + + self.push_screen(LanguageSelectScreen(), apply) +``` + +Dialogs read their texts when they are composed, so they show the language that +is active when they are opened. To refresh your own widgets after a change, +register a language-change listener. + +--- + +## 7. `ki18n.paths` module reference + +Small helpers for applications that are bundled with PyInstaller. They are +independent of `Ki18n`. + +#### `is_frozen() -> bool` + +`True` inside a PyInstaller-built executable (`sys.frozen` is set). + +#### `bundle_root() -> Path` + +Directory that contains the bundled application files at runtime: + +| Situation | Result | +| --- | --- | +| Frozen, `sys._MEIPASS` set | `Path(sys._MEIPASS)` | +| Frozen, no `_MEIPASS` | Directory of `sys.executable` | +| Source checkout | Parent of the `ki18n` package directory | + +For a frozen application, pass `bundle_root()` as `project_root` if the `i18n/` +folder is bundled there: + +```python +from ki18n.paths import bundle_root +Ki18n("en", project_root=bundle_root()) +``` + +--- + +## 8. Errors and logging + +### Exceptions + +| Exception | Raised by | Cause | +| --- | --- | --- | +| `ValueError` | constructor | Invalid default language ID. | +| `ValueError` | constructor, `set_language` | Invalid or inconsistent **installed** resource files (bad JSON, bad value types, missing `language`, missing `one`/`many`, duplicate folders). | +| `FileNotFoundError` | constructor | Missing installed `i18n/` folder, default language folder, or its `strings.json`. | +| `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. | +| `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 +in effect. + +### Logging + +The library logs through the standard `logging` module, logger name +`ki18n.ki18n`. Problems in **user** resources never stop the application; they +are reported at `WARNING` level and the offending file or folder is ignored: + +- `Custom language folder ignored: ...` (invalid or duplicate folder name) +- `Custom translation file ignored: ...` (invalid file) +- `Custom language '' ignored: ...` (new language without a `language` entry) + +--- + +## 9. Known limitations + +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. +- **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. diff --git a/i18n/de/help.md b/i18n/de/help.md new file mode 100644 index 0000000..b4805de --- /dev/null +++ b/i18n/de/help.md @@ -0,0 +1,3 @@ +# Hilfe (Deutsch) + +Ersetze diesen Platzhalter durch den applikationsspezifischen Hilfetext. diff --git a/i18n/de/strings.json b/i18n/de/strings.json new file mode 100644 index 0000000..2c5088e --- /dev/null +++ b/i18n/de/strings.json @@ -0,0 +1,26 @@ +{ + "language": "Deutsch", + "app.title": "Beispielanwendung", + "title_select_language": "Sprache wählen", + "title_help": "Beispiel-Hilfe", + "btn_close": "Schließen", + "btn_cancel": "Abbrechen", + "msg_help_missing": "Hilfe-Datei fehlt!", + + "default_and_available": "Setze die Vorgabesprache und die verfügbaren Sprachen", + "lang_default": "Vorgabe : {default_language}", + "lang_available": "Verfügbar : {available_languages}", + "translated_title": "Übersetzter Titel in {langstr} : {titlestr}", + "pluralized_string": "Ein/Mehrzahl Zeichenkette für {numstr} Dateien : {outstr}", + "pluralized_zero": "null", + "pluralized_one": "eine", + "pluralized_five": "fünf", + + "status.generated": "Generiert: {files}", + "files.found": { + "zero": "Keine Datei gefunden", + "one": "Eine Datei gefunden", + "many": "#count Dateien gefunden", + "none": "Parameter Anzahl der Dateien fehlt !" + } +} diff --git a/i18n/en/help.md b/i18n/en/help.md new file mode 100644 index 0000000..e45453a --- /dev/null +++ b/i18n/en/help.md @@ -0,0 +1,3 @@ +# Help (English) + +Replace this placeholder with the application's language-specific help text. diff --git a/i18n/en/strings.json b/i18n/en/strings.json new file mode 100644 index 0000000..e8fb78a --- /dev/null +++ b/i18n/en/strings.json @@ -0,0 +1,27 @@ +{ + "language": "English", + "app.title": "Sample application", + "title_select_language": "Select language", + "title_help": "Example help", + "btn_close": "Close", + "btn_cancel": "Cancel", + "msg_help_missing": "Help file is missing!", + + + "default_and_available": "Setting the default language and the available languages", + "lang_default": "Default : {default_language}", + "lang_available": "Available : {available_languages}", + "translated_title": "Translated title in {langstr} : {titlestr}", + "pluralized_string": "Pluralized string for {numstr} files : {outstr}", + "pluralized_zero": "zero", + "pluralized_one": "one", + "pluralized_five": "five", + "status.generated": "Generated: {files}", + "files.found": { + "zero": "Found no files", + "one": "Found one file", + "many": "found #count files", + "none": "Parameter file count is missing!" + } + +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..4bfc598 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,68 @@ +[project] +name = "ki18n" +version = "0.1.0" +description = "File-backed internationalization support for Python applications" +readme = "README.md" +requires-python = ">=3.10" +authors = [ + { name = "ikoch" }, +] +license = "MIT" +license-files = ["LICENSE"] +classifiers = [ + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] + +dependencies = [ + "textual==8.2.8", +] + +[dependency-groups] +# Install with `uv sync` (the dev group is included by default) or +# `pip install --group dev`. +dev = [ + "pytest>=8.0", + "pytest-asyncio>=1.0", +] + +[build-system] +requires = ["uv_build>=0.11.14,<0.12.0"] +build-backend = "uv_build" + +[tool.uv.build-backend] +# Which module or directory is packaged (default is src/) +module-root = "src" +module-name = "ki18n" + +source-exclude = [ + "test/*", +] +wheel-exclude = [ + "test/*" +] + +[tool.pytest.ini_options] +minversion = "8.0" +testpaths = ["test"] +# Make the src layout importable without installing the project. +pythonpath = ["src"] +# The Textual dialog tests are async and drive the app with textual's Pilot. +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +addopts = "-ra" + +[[tool.uv.index]] +name = "pypiserver" +url = "http://172.21.181.21:8888/simple" +publish-url = "http://172.21.181.21:8888/" +default = false + +[[tool.uv.index]] +name = "pypi" +url = "https://pypi.org/simple" +publish-url = "https://upload.pypi.org/legacy/" +default = true diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..9df194d --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +pytest>=8.0 +pytest-asyncio>=1.0 +-r requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0c8b497 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +textual==8.2.8 diff --git a/src/ki18n/__init__.py b/src/ki18n/__init__.py new file mode 100644 index 0000000..23bd16a --- /dev/null +++ b/src/ki18n/__init__.py @@ -0,0 +1,14 @@ +"""ki18n: file-backed internationalization support for Python applications. + +The public names are re-exported here so that applications can write:: + + from ki18n import Ki18n, i18n + +The Textual dialogs live in :mod:`ki18n.help_screen` and +:mod:`ki18n.language_select_screen`; they are not imported here, so importing +this package does not require Textual. +""" + +from .ki18n import I18n, Ki18n, i18n + +__all__ = ["I18n", "Ki18n", "i18n"] diff --git a/src/ki18n/help_screen.py b/src/ki18n/help_screen.py new file mode 100644 index 0000000..d5037f7 --- /dev/null +++ b/src/ki18n/help_screen.py @@ -0,0 +1,70 @@ +"""Modal dialog showing the current language's help text as Markdown.""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal +from textual.screen import ModalScreen +from textual.widgets import Button, Label, MarkdownViewer + +from .ki18n import i18n + + +class HelpScreen(ModalScreen[None]): + """Renders ``I18n.get_help()`` in a scrollable Markdown viewer.""" + + DEFAULT_CSS = """\ +HelpScreen { + align: center middle; +} +HelpScreen > Container { + width: 80%; + max-width: 100; + height: 80%; + border: thick $primary 80%; + background: $surface; + padding: 1 2; +} +HelpScreen #help-title { + text-style: bold; + margin-bottom: 1; + height: auto; +} +HelpScreen MarkdownViewer { + height: 1fr; + margin-bottom: 1; +} +HelpScreen Horizontal { + align-horizontal: center; + height: auto; +} +""" + + BINDINGS = [ + ("escape", "close", "Close"), + ] + # tableOfContent = True + + def __init__(self, toc=True): + super().__init__() + self.tableOfContent=toc + + def compose(self) -> ComposeResult: + try: + help_text = i18n.get_help() + except FileNotFoundError: + help_text = i18n.t("msg_help_missing") + + with Container(): + yield Label(i18n.t("title_help"), id="help-title") + yield MarkdownViewer( + help_text, show_table_of_contents=self.tableOfContent, id="help-text" + ) + with Horizontal(): + yield Button(i18n.t("btn_close"), id="help-close") + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.dismiss(None) + + def action_close(self) -> None: + self.dismiss(None) diff --git a/src/ki18n/ki18n.py b/src/ki18n/ki18n.py new file mode 100644 index 0000000..c73c3fc --- /dev/null +++ b/src/ki18n/ki18n.py @@ -0,0 +1,515 @@ +"""Reusable, file-backed internationalization support provided by ki18n. + +Language resources are resolved from the user's application data directory +first and the application's ``i18n`` directory second. The user directory is +``/i18n``; ``local_root`` is the application's per-user directory +(for example ``~/.local/share/my-app``) and can be passed explicitly. Without +it, ``/`` is used, which only matches +the application's own directory when the project directory is named like it. + +``strings.json`` files are **merged** per language: the user's file may contain +just the keys it wants to change or add; everything else comes from the +installed file (and from the regional parents of the language). Invalid user +files are logged and ignored. ``help.md`` is a single document and is replaced +as a whole by the user's file. + +The :class:`Ki18n` manager is a process-wide singleton: only its first +construction uses the provided default language, project root and local root. + +``key_aliases`` maps former translation keys to current ones. It is applied to the **user's** +``strings.json`` files only (with a logged warning), so files written for an older key scheme keep +working. If a file contains both a former and the current key, the current key wins. +""" + +from __future__ import annotations + +import json +import logging +import os +import re +import sys +from collections.abc import Callable +from copy import deepcopy +from pathlib import Path +from typing import Any + +DEFAULT_LANGUAGE = "en" + +log = logging.getLogger(__name__) + +_PLURAL_CATEGORIES = frozenset({"zero", "one", "many", "none"}) +_TranslationValue = str | dict[str, str] + + +def _normalize_language_id(code: str) -> str: + """Normalize a locale ID, removing POSIX encoding/modifier suffixes.""" + if not isinstance(code, str): + raise ValueError("Language IDs must be strings") + code = code.strip().split(".", 1)[0].split("@", 1)[0].replace("-", "_") + parts = code.split("_") + if not parts or any(not re.fullmatch(r"[A-Za-z0-9]+", part) for part in parts): + raise ValueError(f"Invalid language ID: {code!r}") + + normalized = [parts[0].lower()] + for part in parts[1:]: + if len(part) == 4 and part.isalpha(): # script, e.g. Hant + normalized.append(part.title()) + elif (len(part) == 2 and part.isalpha()) or (len(part) == 3 and part.isdigit()): + normalized.append(part.upper()) # region, e.g. US or 419 + else: + normalized.append(part.lower()) + return "_".join(normalized) + + +def _language_fallbacks(code: str) -> tuple[str, ...]: + """Return a locale and its progressively broader parent IDs.""" + parts = _normalize_language_id(code).split("_") + return tuple("_".join(parts[:end]) for end in range(len(parts), 0, -1)) + + +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]``. + 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 + replaced per file. Within one location a regional variant (``de_AT``) + overrides its parent (``de``); user files override installed files. + """ + + _instance: Ki18n | None = None + + def __new__( + cls, + default_language: str = DEFAULT_LANGUAGE, + project_root: str | Path | None = None, + local_root: str | Path | None = None, + ) -> Ki18n: + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__( + self, + default_language: str = DEFAULT_LANGUAGE, + project_root: str | Path | None = None, + local_root: str | Path | None = None, + ) -> None: + """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 + ``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. + """ + if getattr(self, "_initialized", False): + return + + try: + default_language = _normalize_language_id(default_language) + except ValueError as exc: + 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 + 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" + if local_root is None: + self.local_root = self._user_data_root() / self._app_name + else: + self.local_root = Path(local_root).expanduser().resolve() + self._user_i18n_root = self.local_root / "i18n" + self._listeners: list[Callable[[str], None]] = [] + self._current_language = default_language + self._english_translations: dict[str, _TranslationValue] | None = None + + # Discover user languages first, then installed languages, while still + # requiring the default language to ship with the application. + languages = self._discover_available_languages(default_language) + self.available_languages = languages + + # Load before marking the singleton initialized. A failure leaves it + # safe to retry construction with corrected resources/configuration. + translations = self._load_strings(default_language) + self._translations = translations + if default_language == "en": + self._english_translations = translations + self._initialized = True + + @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" + + @staticmethod + def _language_dir(root: Path, language_id: str) -> Path | None: + """Find the directory of a language below ``root`` (case-insensitive on every platform).""" + language_dir = root / language_id + if language_dir.is_dir(): + return language_dir + if root.is_dir(): + for entry in root.iterdir(): + if entry.is_dir() and entry.name.casefold() == language_id.casefold(): + return entry + return None + + def _resource_path(self, code: str, filename: str) -> Path | None: + """Find a single resource through regional fallbacks in user-first order.""" + for root in (self._user_i18n_root, self.i18n_root): + for language_id in _language_fallbacks(code): + language_dir = self._language_dir(root, language_id) + if language_dir is not None and (language_dir / filename).is_file(): + return language_dir / filename + return None + + def _strings_layers(self, code: str) -> list[tuple[Path, bool]]: + """All ``strings.json`` files of a language, lowest priority first. + + Order: installed parent -> installed region -> user parent -> user region. + Each entry is ``(path, is_user_file)``. + """ + layers: list[tuple[Path, bool]] = [] + for root, is_user in ((self.i18n_root, False), (self._user_i18n_root, True)): + for language_id in reversed(_language_fallbacks(code)): + language_dir = self._language_dir(root, language_id) + if language_dir is not None and (language_dir / "strings.json").is_file(): + layers.append((language_dir / "strings.json", is_user)) + return layers + + def _discover_available_languages(self, default_language: str) -> dict[str, str]: + """Read language names from user and installed resource folders.""" + if not self.i18n_root.is_dir(): + raise FileNotFoundError(f"Internal i18n directory not found: {self.i18n_root}") + + default_directory = self.i18n_root / default_language + if not default_directory.is_dir() and self.i18n_root.is_dir(): + try: + default_directory = next( + entry for entry in self.i18n_root.iterdir() + if entry.is_dir() + and entry.name.casefold() == default_language.casefold() + ) + except StopIteration: + raise FileNotFoundError( + f"Default language directory {default_language!r} not found in " + f"{self.i18n_root}" + ) from None + default_strings = default_directory / "strings.json" + if not default_strings.is_file(): + raise FileNotFoundError( + f"Default language strings not found: {default_strings}" + ) + + languages: dict[str, str] = {} + unnamed_user_languages: set[str] = set() + # User resources first: their language name (if any) wins; a user file without + # ``language`` is a subset of an installed language and inherits its name. + for root, is_user in ((self._user_i18n_root, True), (self.i18n_root, False)): + if not root.is_dir(): + continue + root_codes: set[str] = set() + for language_dir in root.iterdir(): + if not language_dir.is_dir(): + continue + try: + code = _normalize_language_id(language_dir.name) + if code in root_codes: + raise ValueError( + f"Duplicate language directory ignoring case in {root}: {code!r}" + ) + except ValueError as exc: + if not is_user: + raise + log.warning("Custom language folder %s ignored: %s", language_dir, exc) + continue + root_codes.add(code) + strings_path = language_dir / "strings.json" + if not strings_path.is_file(): + continue + try: + data = self._read_strings_file(strings_path) + except ValueError as exc: + if not is_user: + raise + log.warning("Custom translation file %s ignored: %s", strings_path, exc) + continue + language_name = data.get("language") + if isinstance(language_name, str) and language_name.strip(): + languages.setdefault(code, language_name) + elif is_user: + unnamed_user_languages.add(code) + else: + raise ValueError( + f"Language resource must define a non-empty string " + f"for 'language': {strings_path}" + ) + for code in sorted(unnamed_user_languages - languages.keys()): + log.warning( + "Custom language %r ignored: its strings.json must define 'language' " + "(or the language must be bundled).", code, + ) + return languages + + @staticmethod + def _read_strings_file(path: Path) -> dict[str, _TranslationValue]: + """Read and validate one strings.json file.""" + try: + with path.open("r", encoding="utf-8") as stream: + data: Any = json.load(stream) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + raise ValueError(f"Invalid translation JSON: {path}") from exc + + if not isinstance(data, dict): + raise ValueError(f"Translation file must contain a JSON object: {path}") + for key, value in tuple(data.items()): + if not isinstance(key, str): + raise ValueError(f"Translation keys must be strings: {path}") + if isinstance(value, str): + continue + if (not isinstance(value, dict) + or not all( + isinstance(category, str) + and category in _PLURAL_CATEGORIES + and isinstance(text, str) + for category, text in value.items() + )): + raise ValueError( + f"Translation values must be strings or plural objects " + f"with string values for zero/one/many/none: {path}" + ) + missing = {"one", "many"} - value.keys() + if missing: + required = ", ".join(sorted(missing)) + raise ValueError( + f"Plural translation {key!r} is missing mandatory " + f"category/ies {required}: {path}" + ) + value.setdefault("zero", value["many"]) + value.setdefault("none", value["many"]) + return data + + def _load_strings(self, code: str) -> dict[str, _TranslationValue]: + """Load a language: installed files overlaid with the user's (subset) files.""" + merged: dict[str, _TranslationValue] = {} + found = False + for path, is_user in self._strings_layers(code): + try: + data = self._read_strings_file(path) + except ValueError as exc: + if not is_user: + raise + log.warning("Custom translation file %s ignored: %s", path, exc) + continue + merged.update(data) + found = True + if not found: + raise FileNotFoundError( + f"Translation file not found for language {code!r} " + f"in {self._user_i18n_root} or {self.i18n_root}" + ) + return merged + + def _get_english_translations(self) -> dict[str, _TranslationValue]: + if self._english_translations is None: + self._english_translations = self._load_strings("en") + return self._english_translations + + def get_language(self) -> str: + """Return the currently active language shortcut.""" + return self._current_language + + def get_default_language(self) -> str: + """Return the language selected when this manager was initialized.""" + return self.default_language + + def get_available_languages(self) -> dict[str, str]: + """Return discovered languages ordered by display name.""" + return dict( + sorted( + self.available_languages.items(), + key=lambda language: ( + language[0] != self.default_language, + language[1].casefold(), + ), + ) + ) + + def _get_translations(self) -> dict[str, _TranslationValue]: + """Return a copy of the current language's translation mapping.""" + return deepcopy(self._translations) + + def set_language(self, code: str) -> None: + """Load and activate a language, then notify registered listeners.""" + requested_code = code + try: + code = _normalize_language_id(code) + except ValueError as exc: + raise ValueError(f"Unknown language: {requested_code!r}") from exc + # Resolve unavailable regional variants to the most specific configured + # parent so get_language() always indexes available_languages. + code = next( + (parent for parent in _language_fallbacks(code) + if parent in self.available_languages), + None, + ) + if code is None: + raise ValueError(f"Unknown language: {requested_code!r}") + if code == self._current_language: + return + + # Complete all I/O and validation before changing active state. + translations = self._load_strings(code) + self._translations = translations + self._current_language = code + for callback in tuple(self._listeners): + callback(code) + + def add_language_change_listener(self, callback: Callable[[str], None]) -> None: + """Register a callback that receives the newly selected language.""" + if callback not in self._listeners: + self._listeners.append(callback) + + def remove_language_change_listener(self, callback: Callable[[str], None]) -> None: + """Remove a registered language-change callback, if present.""" + if callback in self._listeners: + self._listeners.remove(callback) + + # Compatibility aliases used by the previous module-style API. + add_listener = add_language_change_listener + remove_listener = remove_language_change_listener + + @staticmethod + def _format(text: str, kwargs: dict[str, Any]) -> str: + if kwargs: + try: + return text.format(**kwargs) + except (KeyError, IndexError, ValueError): + # A malformed or incomplete format string must not disrupt UI. + return text + except (AttributeError): + return text + except (TypeError): + return text + return text + + def _fallback_translation(self, key: str) -> _TranslationValue | None: + """Look up a key in the active language, then English.""" + value = self._translations.get(key) + if value is not None: + return value + try: + return self._get_english_translations().get(key) + except FileNotFoundError: + # English is optional when another language is configured. + return None + + def t(self, key: str, default: str | None = None, **kwargs: Any) -> str: + """Translate ``key`` using current language, English, default, then key.""" + value = self._fallback_translation(key) + if isinstance(value, dict): + raise ValueError(f"Translation {key!r} is pluralized; use p()") + text = value if value is not None else (default if default is not None else key) + + return self._format(text, kwargs) + + def p( + self, + key: str, + count: int | float | None, + default: str | None = None, + **kwargs: Any, + ) -> str: + """Translate a pluralized key using its count category. + + Categories are ``zero`` for 0, ``one`` for 1, ``many`` for values + greater than 1, and ``none`` when count is ``None``. If that category + is missing from the active language, the same category is tried in + English before ``default`` and the key itself. + """ + if count is None: + category = "none" + elif count == 0: + category = "zero" + elif count == 1: + category = "one" + elif count > 1: + category = "many" + else: + raise ValueError("count must be nonnegative or None") + + value = self._translations.get(key) + text: str | None = None + if isinstance(value, dict): + text = value.get(category) + elif isinstance(value, str): + # A plain string remains usable through p() as a non-plural + # fallback, which is useful for partially converted resources. + text = value + + if text is None: + try: + english_value = self._get_english_translations().get(key) + except FileNotFoundError: + english_value = None + if isinstance(english_value, dict): + text = english_value.get(category) + elif isinstance(english_value, str): + text = english_value + + if text is None: + text = default if default is not None else key + format_args = dict(kwargs) + format_args["count"] = count + text = text.replace("#count", str(count)) + return self._format(text, format_args) + + def get_help(self) -> str: + """Read current-language help, falling back to English help.""" + path = self._resource_path(self._current_language, "help.md") + if path is None and self._current_language != "en": + path = self._resource_path("en", "help.md") + if path is None: + raise FileNotFoundError( + f"Help file not found for language {self._current_language!r} " + f"or English in {self._user_i18n_root} and {self.i18n_root}" + ) + return path.read_text(encoding="utf-8") + + +class _LazyI18n: + """Compatibility handle that initializes the singleton on first use.""" + + def __getattr__(self, name: str) -> Any: + return getattr(Ki18n(), name) + + +# Compatibility aliases for applications using the earlier class names. +ki18n = Ki18n +I18n = Ki18n + +# Import-compatible handle for ``from ki18n import i18n``. Deferring +# construction lets applications supply their configuration first. +i18n = _LazyI18n() diff --git a/src/ki18n/language_select_screen.py b/src/ki18n/language_select_screen.py new file mode 100644 index 0000000..651381d --- /dev/null +++ b/src/ki18n/language_select_screen.py @@ -0,0 +1,64 @@ +"""Language picker modal backed by the application's ki18n resources.""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal, Vertical +from textual.screen import ModalScreen +from textual.widgets import Button, Label + +from .ki18n import i18n + + +class LanguageSelectScreen(ModalScreen[str | None]): + """Return the selected language ID, or ``None`` when cancelled.""" + + DEFAULT_CSS = """\ +LanguageSelectScreen { align: center middle; } +LanguageSelectScreen > Container { + width: 50%; + max-width: 50; + height: auto; + border: thick $primary 80%; + background: $surface; + padding: 1 2; +} +LanguageSelectScreen #language-title { + text-style: bold; + margin-bottom: 1; +} +LanguageSelectScreen Vertical#language-options { + height: auto; + margin-bottom: 1; +} +LanguageSelectScreen Button { + width: 100%; + margin-bottom: 1; +} +LanguageSelectScreen Horizontal { + align-horizontal: center; + height: auto; +} + +/* Help dialog */""" + BINDINGS = [("escape", "cancel", "")] + + def compose(self) -> ComposeResult: + with Container(id="language-dialog"): + yield Label(i18n.t("title_select_language"), id="language-title") + with Vertical(id="language-options"): + for code, display_name in i18n.get_available_languages().items(): + variant = "primary" if code == i18n.get_language() else "default" + yield Button(display_name, id=f"lang-{code}", variant=variant) + with Horizontal(id="language-dialog-buttons"): + yield Button(i18n.t("btn_cancel"), id="language-cancel") + + def on_button_pressed(self, event: Button.Pressed) -> None: + button_id = event.button.id or "" + if button_id == "language-cancel": + self.dismiss(None) + elif button_id.startswith("lang-"): + self.dismiss(button_id.removeprefix("lang-")) + + def action_cancel(self) -> None: + self.dismiss(None) diff --git a/src/ki18n/paths.py b/src/ki18n/paths.py new file mode 100644 index 0000000..958615e --- /dev/null +++ b/src/ki18n/paths.py @@ -0,0 +1,45 @@ +"""Standard paths of the application (and transfer of data from the previous version ``vorta-tui``).""" + +from __future__ import annotations + +import logging +import os +import sys +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.""" + return bool(getattr(sys, "frozen", False)) + + +def bundle_root() -> Path: + """Directory that contains ``i18n/`` and ``core`` at runtime.""" + if is_frozen(): + meipass = getattr(sys, "_MEIPASS", None) + if meipass: + return Path(meipass) + # 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 + + # Plain source checkout or a pex zipapp: this file lives at + # /app/runtime_paths.py. + return Path(__file__).resolve().parent.parent diff --git a/src/ki18n/py.typed b/src/ki18n/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/test/README.md b/test/README.md new file mode 100644 index 0000000..9640535 --- /dev/null +++ b/test/README.md @@ -0,0 +1,60 @@ +# Tests for ki18n + +The suite uses [pytest](https://docs.pytest.org/) with +[pytest-asyncio](https://pytest-asyncio.readthedocs.io/). The Textual dialogs are +operated through Textual's `Pilot` (clicks and key presses in the headless test +driver `App.run_test`). + +Every test runs in temporary directories (installed and user resources; +`XDG_DATA_HOME` and `LOCALAPPDATA` are redirected), so real user data is never +read. The `Ki18n` singleton is reset before and after every test. + +```sh +uv sync # installs the dev dependency group (pytest, pytest-asyncio) +uv run pytest # or: python3 -m pytest +uv run pytest -k plural # run a subset +``` + +Configuration lives in `pyproject.toml` (`[tool.pytest.ini_options]`): +`testpaths`, `pythonpath = ["src"]` (no installation needed) and +`asyncio_mode = "auto"`. + +## Layout + +| File | Contents | +| --- | --- | +| `conftest.py` | Fixtures: `env`, `installed`, `manager`, `log_warnings`, singleton reset | +| `support.py` | Example data (`EN`, `DE`, dialog keys) and the `Env` helper class | +| `test_normalize.py` | Language ID normalization, fallback chains | +| `test_paths.py` | `ki18n.paths` (PyInstaller / source checkout) | +| `test_construction.py` | Constructor, singleton, `project_root`/`local_root`, data directories | +| `test_discovery.py` | `get_available_languages()`, user and installed resources | +| `test_loading.py` | Validation and merging of `strings.json`, regional layers | +| `test_set_language.py` | `set_language()`, error cases, listeners | +| `test_translate.py` | `t()`: fallback order, formatting | +| `test_plural.py` | `p()`: categories, `#count`/`{count}`, fallbacks | +| `test_help.py` | `get_help()`: regions, user files, English fallback | +| `test_lazy_handle.py` | Module handle `i18n`, alias names | +| `test_public_api.py` | Public API as documented in the README | +| `test_shipped_resources.py` | Consistency of the shipped `i18n/` files | +| `test_screens.py` | `HelpScreen` / `LanguageSelectScreen` driven with `Pilot`, plus a small integration app | + +## Fixtures + +- `env` - isolated `Env`: `env.install(lang, strings, help)`, `env.user(...)`, + `env.make()` / `env.remake()`, directories `app_dir`, `user_dir`, `data_home`. +- `installed` - `env` with the example languages `en` and `de` installed, no manager yet. +- `manager` - `installed` plus a constructed `Ki18n` instance. +- `log_warnings` - callable returning the library's WARNING messages so far. + +## Known deviations between documentation and code + +Cases that describe documented behavior the code does not currently fulfil are +marked `xfail(strict=True)`. They are reported as `xfailed` now and turn into +failures (`XPASS(strict)`) once the code is fixed - remove the marker then. + +- `test_public_api.py::test_package_exports_documented_names` - + `from ki18n import Ki18n, i18n, I18n`: `__init__.py` is empty. +- `test_translate.py::test_other_formatting_errors_return_unformatted_text` - + `_format()` only catches `KeyError`, `IndexError` and `ValueError`, so + `{name.attr}` / `{name[x]}` raise `AttributeError` / `TypeError`. diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 index 0000000..093ac93 --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,65 @@ +"""Shared pytest fixtures for the ki18n tests.""" + +from __future__ import annotations + +import logging + +import pytest + +from ki18n.ki18n import Ki18n +from support import LOGGER, Env + + +@pytest.fixture(autouse=True) +def _reset_singleton(): + """Make sure no test sees (or leaks) a ``Ki18n`` singleton.""" + Ki18n._instance = None + yield + Ki18n._instance = None + + +@pytest.fixture +def env(tmp_path, monkeypatch) -> Env: + """Isolated application and user directories. + + ``XDG_DATA_HOME`` and ``LOCALAPPDATA`` point into the temporary directory, so + real user data is never touched. + """ + base = tmp_path.resolve() + environment = Env(base) + monkeypatch.setenv("XDG_DATA_HOME", str(environment.data_home)) + monkeypatch.setenv("LOCALAPPDATA", str(environment.data_home)) + return environment + + +@pytest.fixture +def manager(env: Env) -> Ki18n: + """Manager with the installed example languages ``en`` and ``de``.""" + env.install_defaults() + return env.make() + + +@pytest.fixture +def installed(env: Env) -> Env: + """Environment with the installed example languages ``en`` and ``de``. + + Unlike ``manager`` this does not create the ``Ki18n`` instance yet, so a test + can still add (user) resources before constructing it with ``installed.make()``. + """ + env.install_defaults() + return env + + +@pytest.fixture +def log_warnings(caplog): + """Return a function listing the library's WARNING messages so far.""" + caplog.set_level(logging.WARNING, logger=LOGGER) + + def messages() -> list[str]: + return [ + record.getMessage() + for record in caplog.records + if record.name == LOGGER and record.levelno >= logging.WARNING + ] + + return messages diff --git a/test/support.py b/test/support.py new file mode 100644 index 0000000..e6f49ad --- /dev/null +++ b/test/support.py @@ -0,0 +1,142 @@ +"""Shared test data and helpers for the ki18n test suite. + +Imported by ``conftest.py`` and the test modules (pytest puts the ``test`` +directory on ``sys.path`` because it is not a package). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from ki18n.ki18n import Ki18n + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +#: Logger used by the library for warnings about ignored user resources. +LOGGER = "ki18n.ki18n" + +# --------------------------------------------------------------------------- +# Example translations +# --------------------------------------------------------------------------- + +EN = { + "language": "English", + "greeting": "Hello", + "farewell": "Goodbye", + "only.en": "Only in English", + "welcome": "Welcome, {name}!", + "files.found": { + "zero": "No files", + "one": "One file", + "many": "#count files", + "none": "Count missing", + }, +} + +DE = { + "language": "Deutsch", + "greeting": "Hallo", + "farewell": "Tschüss", + "welcome": "Willkommen, {name}!", + "files.found": { + "zero": "Keine Dateien", + "one": "Eine Datei", + "many": "#count Dateien", + }, +} + +#: Keys used by ``HelpScreen`` and ``LanguageSelectScreen``. +DIALOG_EN = { + "title_select_language": "Select language", + "title_help": "Example help", + "btn_close": "Close", + "btn_cancel": "Cancel", + "msg_help_missing": "Help file is missing!", +} + +DIALOG_DE = { + "title_select_language": "Sprache wählen", + "title_help": "Beispiel-Hilfe", + "btn_close": "Schließen", + "btn_cancel": "Abbrechen", + "msg_help_missing": "Hilfe-Datei fehlt!", +} + + +def write_language( + root: Path, + language_dir: str, + strings: dict | str | bytes | None = None, + help_text: str | None = None, +) -> Path: + """Create ``/i18n//`` with ``strings.json``/``help.md``. + + ``strings`` may be a ``dict`` (written as JSON), a ``str`` (raw text, e.g. + broken JSON), ``bytes`` (raw bytes) or ``None`` (no file). + """ + directory = root / "i18n" / language_dir + directory.mkdir(parents=True, exist_ok=True) + if isinstance(strings, dict): + (directory / "strings.json").write_text( + json.dumps(strings, ensure_ascii=False, indent=2), encoding="utf-8" + ) + elif isinstance(strings, str): + (directory / "strings.json").write_text(strings, encoding="utf-8") + elif isinstance(strings, bytes): + (directory / "strings.json").write_bytes(strings) + if help_text is not None: + (directory / "help.md").write_text(help_text, encoding="utf-8") + return directory + + +class Env: + """An isolated application + user-data environment below ``base``.""" + + def __init__(self, base: Path) -> None: + self.tmp = base + #: "Installation directory" of the test application (name: ``myapp``) + self.app_dir = base / "myapp" + self.app_dir.mkdir() + #: Per-user data directory of the application + self.user_dir = base / "userdata" / "myapp" + self.user_dir.mkdir(parents=True) + #: Pseudo home / XDG directory for tests without an explicit local_root + self.data_home = base / "datahome" + self.data_home.mkdir() + + # -- Creating resources ------------------------------------------------- + + def install(self, language_dir, strings=None, help_text=None) -> Path: + """Installed resource (``/i18n/...``).""" + return write_language(self.app_dir, language_dir, strings, help_text) + + def user(self, language_dir, strings=None, help_text=None) -> Path: + """User resource (``/i18n/...``).""" + return write_language(self.user_dir, language_dir, strings, help_text) + + def install_defaults(self, with_help: bool = False) -> None: + """Install ``en`` and ``de`` with the example data.""" + self.install("en", EN, "# Help\n" if with_help else None) + self.install("de", DE, "# Hilfe\n" if with_help else None) + + def installed_file(self, language_dir: str, name: str) -> Path: + """Path of a file in an installed language folder.""" + return self.app_dir / "i18n" / language_dir / name + + # -- Creating managers -------------------------------------------------- + + def make(self, default: str = "en", **kwargs) -> Ki18n: + """Create the manager using the isolated directories.""" + kwargs.setdefault("project_root", self.app_dir) + kwargs.setdefault("local_root", self.user_dir) + return Ki18n(default, **kwargs) + + def remake(self, default: str = "en", **kwargs) -> Ki18n: + """Discard the singleton and create the manager again. + + Needed when a test creates further resources after the first ``make()`` + that must be discovered during construction. + """ + Ki18n._instance = None + return self.make(default, **kwargs) diff --git a/test/test_construction.py b/test/test_construction.py new file mode 100644 index 0000000..4b86e02 --- /dev/null +++ b/test/test_construction.py @@ -0,0 +1,248 @@ +"""Tests for construction, singleton behavior and path resolution.""" + +import os +import sys +from pathlib import Path + +import pytest + +from ki18n.ki18n import DEFAULT_LANGUAGE, Ki18n +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Singleton +# --------------------------------------------------------------------------- + + +def test_default_language_constant(): + assert DEFAULT_LANGUAGE == "en" + + +def test_repeated_construction_returns_same_instance(env): + env.install_defaults() + first = env.make() + assert Ki18n() is first + + +def test_later_arguments_are_ignored(env): + env.install_defaults() + first = env.make("en") + other_root = env.tmp / "other" + other_root.mkdir() + second = Ki18n("de", project_root=other_root, local_root=env.tmp / "x") + assert second is first + assert second.get_default_language() == "en" + assert second.project_root == env.app_dir + assert second.local_root == env.user_dir + + +def test_reinitialization_does_not_reset_active_language(env): + env.install_defaults() + manager = env.make() + manager.set_language("de") + Ki18n("en", project_root=env.app_dir) + assert manager.get_language() == "de" + + +def test_failed_construction_can_be_retried(env): + # The i18n directory exists, but the default language is missing. + (env.app_dir / "i18n").mkdir() + with pytest.raises(FileNotFoundError): + env.make() + env.install("en", EN) + manager = env.make() + assert manager.t("greeting") == "Hello" + assert Ki18n() is manager + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def test_defaults_after_construction(env): + env.install_defaults() + manager = env.make() + assert manager.get_default_language() == "en" + assert manager.get_language() == "en" + assert manager.project_root == env.app_dir + assert manager.i18n_root == env.app_dir / "i18n" + assert manager.local_root == env.user_dir + + +def test_project_and_local_root_may_be_strings(env): + env.install_defaults() + manager = Ki18n("en", project_root=str(env.app_dir), local_root=str(env.user_dir)) + assert manager.project_root == env.app_dir + assert manager.t("greeting") == "Hello" + + +def test_roots_expand_user_directory(env, monkeypatch): + env.install_defaults() + monkeypatch.setenv("HOME", str(env.tmp)) + monkeypatch.setenv("USERPROFILE", str(env.tmp)) + manager = Ki18n("en", project_root="~/myapp", local_root="~/userdata/myapp") + assert manager.project_root == env.app_dir + assert manager.local_root == env.user_dir + + +def test_local_root_defaults_to_user_data_dir_plus_app_name(env): + env.install_defaults() + manager = Ki18n("en", project_root=env.app_dir) + assert manager.local_root == env.data_home / "myapp" + + +def test_default_language_is_normalized(env): + env.install("de_AT", {"language": "Deutsch (Österreich)", "greeting": "Servus"}) + manager = env.make("de-at") + assert manager.get_default_language() == "de_AT" + assert manager.get_language() == "de_AT" + assert manager.t("greeting") == "Servus" + + +def test_default_language_directory_lookup_ignores_case(env): + env.install("EN", EN) + manager = env.make("en") + assert manager.t("greeting") == "Hello" + assert manager.get_available_languages() == {"en": "English"} + + +def test_non_english_default_language(env): + env.install_defaults() + manager = env.make("de") + assert manager.get_default_language() == "de" + assert manager.get_language() == "de" + assert manager.t("greeting") == "Hallo" + + +@pytest.mark.parametrize("code", ["!!", "", "de/DE", None]) +def test_invalid_default_language_raises_value_error(env, code): + env.install_defaults() + with pytest.raises(ValueError, match="Invalid default language"): + Ki18n(code, project_root=env.app_dir, local_root=env.user_dir) + + +def test_missing_i18n_directory_raises(env): + with pytest.raises(FileNotFoundError, match="i18n"): + env.make() + + +def test_missing_project_root_raises(env): + with pytest.raises(FileNotFoundError): + env.make(project_root=env.tmp / "does-not-exist") + + +def test_missing_default_language_directory_raises(env): + env.install("de", DE) + with pytest.raises(FileNotFoundError, match="'en'"): + env.make("en") + + +def test_default_language_without_strings_file_raises(env): + env.install("en", None, help_text="# Help") + with pytest.raises(FileNotFoundError): + env.make() + + +def test_default_language_path_must_be_a_directory(env): + (env.app_dir / "i18n").mkdir() + (env.app_dir / "i18n" / "en").write_text("not a directory", encoding="utf-8") + with pytest.raises(FileNotFoundError): + env.make() + + +@pytest.mark.parametrize( + "strings", + [ + "{ this is not json", + {"greeting": "Hello"}, # no "language" + {"language": " ", "greeting": "Hello"}, # blank "language" + {"language": "English", "x": {"one": "one"}}, # plural without "many" + ], + ids=["invalid-json", "no-language-name", "blank-language-name", "bad-plural"], +) +def test_invalid_default_language_resources_raise_value_error(env, strings): + env.install("en", strings) + with pytest.raises(ValueError): + env.make() + + +def test_default_resources_are_not_reloaded_from_disk_on_lookup(env): + env.install_defaults() + manager = env.make() + env.installed_file("en", "strings.json").write_text("garbage", encoding="utf-8") + assert manager.t("greeting") == "Hello" + + +# --------------------------------------------------------------------------- +# project_root derived from sys.argv[0] +# --------------------------------------------------------------------------- + + +def test_absolute_argv0_uses_its_directory(env, monkeypatch): + env.install_defaults() + monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")]) + manager = Ki18n("en", local_root=env.user_dir) + assert manager.project_root == env.app_dir + assert manager.i18n_root == env.app_dir / "i18n" + + +def test_relative_argv0_is_resolved_against_cwd(env, monkeypatch): + env.install_defaults() + monkeypatch.chdir(env.app_dir) + monkeypatch.setattr(sys, "argv", ["main.py"]) + 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")]) + manager = Ki18n("en") + assert manager.local_root == env.data_home / "myapp" + + +# --------------------------------------------------------------------------- +# Per-user data directory +# --------------------------------------------------------------------------- + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX-specific path logic") +class TestUserDataRootPosix: + def test_xdg_data_home_is_used_when_set(self, env): + assert Ki18n._user_data_root() == env.data_home + + def test_xdg_data_home_expands_user(self, env, monkeypatch): + monkeypatch.setenv("XDG_DATA_HOME", "~/share") + monkeypatch.setenv("HOME", str(env.tmp)) + assert Ki18n._user_data_root() == env.tmp / "share" + + def test_linux_default_without_xdg(self, env, monkeypatch): + monkeypatch.delenv("XDG_DATA_HOME") + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr(Path, "home", staticmethod(lambda: env.tmp)) + assert Ki18n._user_data_root() == env.tmp / ".local" / "share" + + def test_empty_xdg_data_home_is_treated_as_unset(self, env, monkeypatch): + monkeypatch.setenv("XDG_DATA_HOME", "") + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr(Path, "home", staticmethod(lambda: env.tmp)) + assert Ki18n._user_data_root() == env.tmp / ".local" / "share" + + def test_macos_default_without_xdg(self, env, monkeypatch): + monkeypatch.delenv("XDG_DATA_HOME") + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr(Path, "home", staticmethod(lambda: env.tmp)) + assert Ki18n._user_data_root() == env.tmp / "Library" / "Application Support" + + +@pytest.mark.skipif(os.name != "nt", reason="Windows-specific path logic") +class TestUserDataRootWindows: + def test_localappdata_is_used(self, env): + assert Ki18n._user_data_root() == env.data_home + + def test_fallback_without_localappdata(self, env, monkeypatch): + monkeypatch.delenv("LOCALAPPDATA") + monkeypatch.setattr(Path, "home", staticmethod(lambda: env.tmp)) + assert Ki18n._user_data_root() == env.tmp / "AppData" / "Local" diff --git a/test/test_discovery.py b/test/test_discovery.py new file mode 100644 index 0000000..79c6155 --- /dev/null +++ b/test/test_discovery.py @@ -0,0 +1,174 @@ +"""Tests for language discovery (``get_available_languages``).""" + +import pytest + +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Installed languages +# --------------------------------------------------------------------------- + + +def test_mapping_of_installed_languages(manager): + assert manager.get_available_languages() == {"en": "English", "de": "Deutsch"} + + +def test_default_language_first_then_sorted_by_display_name(env): + env.install("en", EN) + env.install("de", DE) + env.install("fr", {"language": "Français"}) + env.install("es", {"language": "español"}) + manager = env.make() + # "English" would sort after "Deutsch" alphabetically, but it is the default. + assert list(manager.get_available_languages()) == ["en", "de", "es", "fr"] + + +def test_non_english_default_language_comes_first(env): + env.install_defaults() + env.install("fr", {"language": "Français"}) + manager = env.make("de") + assert list(manager.get_available_languages()) == ["de", "en", "fr"] + + +def test_returned_mapping_is_a_copy(manager): + languages = manager.get_available_languages() + languages["xx"] = "Injected" + languages.pop("de") + assert manager.get_available_languages() == {"en": "English", "de": "Deutsch"} + + +def test_regional_directories_are_normalized(env): + env.install_defaults() + env.install("de_at", {"language": "Deutsch (Österreich)"}) + manager = env.make() + assert manager.get_available_languages()["de_AT"] == "Deutsch (Österreich)" + + +def test_directory_without_strings_file_is_not_a_language(env): + env.install_defaults() + env.install("fr", None, help_text="# Aide") + assert "fr" not in env.make().get_available_languages() + + +def test_plain_files_in_i18n_root_are_ignored(env): + env.install_defaults() + (env.app_dir / "i18n" / "README.txt").write_text("hi", encoding="utf-8") + assert set(env.make().get_available_languages()) == {"en", "de"} + + +def test_installed_directory_with_invalid_name_raises(env): + env.install_defaults() + env.install("not a language", {"language": "Broken"}) + with pytest.raises(ValueError): + env.make() + + +@pytest.mark.parametrize( + "strings", + ["{ kaputt", {"greeting": "Bonjour"}, {"language": " "}, {"language": 5}], + ids=["invalid-json", "no-language-name", "blank-language-name", "non-string-name"], +) +def test_invalid_installed_language_raises(env, strings): + env.install_defaults() + env.install("fr", strings) + with pytest.raises(ValueError): + env.make() + + +def test_duplicate_installed_directories_after_normalization_raise(env): + env.install_defaults() + env.install("de_DE", {"language": "Deutsch (Deutschland)"}) + env.install("de-DE", {"language": "Deutsch (Deutschland) 2"}) + with pytest.raises(ValueError, match="Duplicate"): + env.make() + + +# --------------------------------------------------------------------------- +# User languages +# --------------------------------------------------------------------------- + + +def test_user_directory_may_be_missing(installed): + assert not installed.user_dir.joinpath("i18n").exists() + assert set(installed.make().get_available_languages()) == {"en", "de"} + + +def test_user_can_add_a_language(installed): + installed.user("fr", {"language": "Français"}) + assert installed.make().get_available_languages()["fr"] == "Français" + + +def test_user_language_name_overrides_installed_name(installed): + installed.user("de", {"language": "Deutsch (angepasst)"}) + assert installed.make().get_available_languages()["de"] == "Deutsch (angepasst)" + + +def test_user_subset_without_language_name_inherits_installed_name(installed, log_warnings): + installed.user("de", {"greeting": "Moin"}) + manager = installed.make() + assert manager.get_available_languages()["de"] == "Deutsch" + assert log_warnings() == [] + + +def test_user_directory_names_are_matched_ignoring_case(installed): + installed.user("DE", {"language": "Deutsch (Benutzer)"}) + assert installed.make().get_available_languages()["de"] == "Deutsch (Benutzer)" + + +def test_unknown_user_language_without_name_is_ignored_with_warning(installed, log_warnings): + installed.user("fr", {"greeting": "Bonjour"}) + manager = installed.make() + assert "fr" not in manager.get_available_languages() + assert any("Custom language" in m and "'fr'" in m for m in log_warnings()) + + +def test_user_language_with_invalid_json_is_ignored_with_warning(installed, log_warnings): + installed.user("fr", "{ kaputt") + manager = installed.make() + assert "fr" not in manager.get_available_languages() + assert any("Custom translation file" in m for m in log_warnings()) + + +def test_invalid_user_file_of_installed_language_keeps_installed_name(installed, log_warnings): + installed.user("de", "{ kaputt") + manager = installed.make() + assert manager.get_available_languages()["de"] == "Deutsch" + assert log_warnings() + + +def test_user_language_with_invalid_plural_is_ignored_with_warning(installed, log_warnings): + installed.user("fr", {"language": "Français", "x": {"one": "un"}}) + manager = installed.make() + assert "fr" not in manager.get_available_languages() + assert log_warnings() + + +def test_user_directory_with_invalid_name_is_ignored_with_warning(installed, log_warnings): + installed.user("bad name", {"language": "Broken"}) + manager = installed.make() + assert set(manager.get_available_languages()) == {"en", "de"} + assert any("Custom language folder" in m for m in log_warnings()) + + +def test_plain_files_in_user_i18n_root_are_ignored(installed, log_warnings): + installed.user("fr", {"language": "Français"}) + (installed.user_dir / "i18n" / "notes.txt").write_text("hi", encoding="utf-8") + manager = installed.make() + assert "fr" in manager.get_available_languages() + assert log_warnings() == [] + + +def test_duplicate_user_directories_are_ignored_with_warning(installed, log_warnings): + installed.user("de_DE", {"language": "Deutsch (Deutschland)"}) + installed.user("de-DE", {"language": "Deutsch (Deutschland) 2"}) + manager = installed.make() + assert "de_DE" in manager.get_available_languages() + assert any("Duplicate" in m for m in log_warnings()) + + +def test_user_directory_without_strings_file_is_ignored(installed, log_warnings): + installed.user("fr", None, help_text="# Aide") + manager = installed.make() + assert "fr" not in manager.get_available_languages() + assert log_warnings() == [] diff --git a/test/test_help.py b/test/test_help.py new file mode 100644 index 0000000..dc78e20 --- /dev/null +++ b/test/test_help.py @@ -0,0 +1,154 @@ +"""Tests for ``Ki18n.get_help``.""" + +import pytest + +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Basic lookup +# --------------------------------------------------------------------------- + + +def test_returns_help_of_active_language(env): + env.install("en", EN, "# Help (English)\n") + env.install("de", DE, "# Hilfe (Deutsch)\n") + manager = env.make() + assert manager.get_help() == "# Help (English)\n" + manager.set_language("de") + assert manager.get_help() == "# Hilfe (Deutsch)\n" + + +def test_reads_utf8(env): + env.install("en", EN, "# Help\n") + env.install("de", DE, "# Größe – Übersicht ✓ 日本語\n") + manager = env.make() + manager.set_language("de") + assert manager.get_help() == "# Größe – Übersicht ✓ 日本語\n" + + +def test_help_is_read_on_every_call(env): + env.install("en", EN, "# one\n") + manager = env.make() + env.installed_file("en", "help.md").write_text("# two\n", encoding="utf-8") + assert manager.get_help() == "# two\n" + + +def test_falls_back_to_english_when_language_has_no_help(env): + env.install("en", EN, "# Help (English)\n") + env.install("de", DE) + manager = env.make() + manager.set_language("de") + assert manager.get_help() == "# Help (English)\n" + + +def test_missing_help_raises_file_not_found(manager): + manager.set_language("de") + with pytest.raises(FileNotFoundError, match="Help file not found"): + manager.get_help() + + +def test_missing_english_help_raises_file_not_found(manager): + with pytest.raises(FileNotFoundError): + manager.get_help() + + +def test_directory_named_help_md_is_not_a_help_file(env): + env.install("en", EN) + (env.app_dir / "i18n" / "en" / "help.md").mkdir() + manager = env.make() + with pytest.raises(FileNotFoundError): + manager.get_help() + + +# --------------------------------------------------------------------------- +# Regional variants +# --------------------------------------------------------------------------- + + +@pytest.fixture +def helped(env): + env.install("en", EN, "# EN\n") + env.install("de", DE, "# DE\n") + return env + + +def test_regional_help_wins_over_parent_help(helped): + helped.install("de_AT", {"language": "Österreichisch"}, "# DE_AT\n") + manager = helped.make() + manager.set_language("de_AT") + assert manager.get_help() == "# DE_AT\n" + + +def test_regional_language_without_help_uses_parent_help(helped): + helped.install("de_AT", {"language": "Österreichisch"}) + manager = helped.make() + manager.set_language("de_AT") + assert manager.get_help() == "# DE\n" + + +def test_unconfigured_region_uses_parent_help(helped): + manager = helped.make() + manager.set_language("de_CH") + assert manager.get_help() == "# DE\n" + + +# --------------------------------------------------------------------------- +# User help files +# --------------------------------------------------------------------------- + + +def test_user_help_replaces_installed_help_as_a_whole(helped): + helped.user("de", None, "# Benutzer\n") + manager = helped.make() + manager.set_language("de") + assert manager.get_help() == "# Benutzer\n" + # The installed file stays unchanged. + assert helped.installed_file("de", "help.md").read_text(encoding="utf-8") == "# DE\n" + + +def test_user_help_for_default_language(helped): + helped.user("en", None, "# My English help\n") + assert helped.make().get_help() == "# My English help\n" + + +def test_user_regional_help_wins_over_user_parent_help(helped): + helped.install("de_AT", {"language": "Österreichisch"}) + helped.user("de", None, "# user DE\n") + helped.user("de_AT", None, "# user DE_AT\n") + manager = helped.make() + manager.set_language("de_AT") + assert manager.get_help() == "# user DE_AT\n" + + +def test_user_parent_help_wins_over_installed_regional_help(helped): + helped.install("de_AT", {"language": "Österreichisch"}, "# inst DE_AT\n") + helped.user("de", None, "# user DE\n") + manager = helped.make() + manager.set_language("de_AT") + assert manager.get_help() == "# user DE\n" + + +def test_user_help_without_user_strings_file_is_used(helped): + # A user folder does not need a strings.json for help.md. + helped.user("de", None, "# nur Hilfe\n") + manager = helped.make() + manager.set_language("de") + assert manager.get_help() == "# nur Hilfe\n" + + +def test_english_fallback_may_come_from_user_directory(helped): + helped.install("fr", {"language": "Français"}) + helped.installed_file("en", "help.md").unlink() + helped.user("en", None, "# user EN\n") + manager = helped.make() + manager.set_language("fr") + assert manager.get_help() == "# user EN\n" + + +def test_user_help_in_language_without_installed_help(helped): + helped.installed_file("de", "help.md").unlink() + helped.user("de", None, "# user DE\n") + manager = helped.make() + manager.set_language("de") + assert manager.get_help() == "# user DE\n" diff --git a/test/test_lazy_handle.py b/test/test_lazy_handle.py new file mode 100644 index 0000000..69d03f2 --- /dev/null +++ b/test/test_lazy_handle.py @@ -0,0 +1,78 @@ +"""Tests for the module handle ``i18n`` and the compatibility aliases.""" + +import importlib +import sys + +import pytest + +from ki18n.ki18n import I18n, Ki18n, i18n, ki18n +from support import EN, DE + +# Via importlib, so that a future re-export of the class alias ``ki18n`` in the +# package does not shadow the submodule. +ki18n_module = importlib.import_module("ki18n.ki18n") + + +def test_class_aliases(): + assert I18n is Ki18n + assert ki18n is Ki18n + + +def test_module_exports_lazy_handle(): + assert ki18n_module.i18n is i18n + assert not isinstance(i18n, Ki18n) + + +def test_handle_delegates_to_configured_singleton(manager): + assert i18n.get_language() == "en" + assert i18n.t("greeting") == "Hello" + assert i18n.get_available_languages() == manager.get_available_languages() + assert i18n.get_default_language() == "en" + + +def test_handle_sees_changes_made_through_the_manager(manager): + manager.set_language("de") + assert i18n.get_language() == "de" + assert i18n.t("greeting") == "Hallo" + + +def test_changes_through_the_handle_are_visible_in_the_manager(manager): + i18n.set_language("de") + assert manager.get_language() == "de" + + +def test_handle_follows_a_new_singleton(env): + env.install_defaults() + env.make("de") + assert i18n.get_language() == "de" + env.remake("en") + assert i18n.get_language() == "en" + + +def test_handle_creates_singleton_with_defaults_on_first_use(env, monkeypatch): + env.install_defaults() + monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")]) + assert Ki18n._instance is None + assert i18n.t("greeting") == "Hello" + assert Ki18n._instance is not None + assert Ki18n._instance.project_root == env.app_dir + assert Ki18n._instance.get_default_language() == "en" + + +def test_handle_exposes_help_and_plural_api(env): + env.install("en", EN, "# Help\n") + env.install("de", DE) + env.make() + assert i18n.get_help() == "# Help\n" + assert i18n.p("files.found", 3) == "3 files" + + +def test_first_use_without_resources_raises_file_not_found(env, monkeypatch): + monkeypatch.setattr(sys, "argv", [str(env.app_dir / "main.py")]) + with pytest.raises(FileNotFoundError): + i18n.t("greeting") + + +def test_unknown_attribute_raises_attribute_error(manager): + with pytest.raises(AttributeError): + i18n.does_not_exist # noqa: B018 diff --git a/test/test_loading.py b/test/test_loading.py new file mode 100644 index 0000000..2cf2f95 --- /dev/null +++ b/test/test_loading.py @@ -0,0 +1,244 @@ +"""Tests for loading, validating and merging ``strings.json`` files.""" + +import pytest + +from ki18n.ki18n import Ki18n +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Validation (``Ki18n._read_strings_file``) +# --------------------------------------------------------------------------- + + +@pytest.fixture +def read(tmp_path): + """Write ``content`` to a file and run the library's validator on it.""" + + def _read(content): + path = tmp_path / "strings.json" + if isinstance(content, bytes): + path.write_bytes(content) + else: + path.write_text(content, encoding="utf-8") + return Ki18n._read_strings_file(path) + + return _read + + +def test_valid_file_with_non_ascii_text(read): + data = read('{"language": "Deutsch", "k": "Grüße, 日本語"}') + assert data == {"language": "Deutsch", "k": "Grüße, 日本語"} + + +def test_empty_object_is_valid(read): + assert read("{}") == {} + + +def test_plural_object_gets_defaults_for_zero_and_none(read): + data = read('{"k": {"one": "1 file", "many": "#count files"}}') + assert data["k"] == { + "one": "1 file", + "many": "#count files", + "zero": "#count files", + "none": "#count files", + } + + +def test_explicit_zero_and_none_are_kept(read): + data = read('{"k": {"zero": "none", "one": "1", "many": "n", "none": "unknown"}}') + assert data["k"]["zero"] == "none" + assert data["k"]["none"] == "unknown" + + +@pytest.mark.parametrize( + "content", + [ + pytest.param("{ kaputt", id="invalid-json"), + pytest.param("", id="empty-file"), + pytest.param("[1, 2]", id="json-array"), + pytest.param('"text"', id="json-string"), + pytest.param("42", id="json-number"), + pytest.param("null", id="null"), + pytest.param('{"k": 5}', id="number-value"), + pytest.param('{"k": true}', id="boolean-value"), + pytest.param('{"k": null}', id="null-value"), + pytest.param('{"k": ["a"]}', id="list-value"), + pytest.param('{"k": {"many": "n"}}', id="plural-missing-one"), + pytest.param('{"k": {"one": "1"}}', id="plural-missing-many"), + pytest.param('{"k": {}}', id="plural-empty"), + pytest.param('{"k": {"one": "1", "many": "n", "few": "f"}}', id="plural-unknown-category"), + pytest.param('{"k": {"one": 1, "many": "n"}}', id="plural-non-string-text"), + pytest.param('{"k": {"one": {"a": "b"}, "many": "n"}}', id="plural-nested-dict"), + pytest.param(b"\xff\xfe{", id="invalid-utf-8"), + ], +) +def test_invalid_content_raises_value_error(read, content): + with pytest.raises(ValueError): + read(content) + + +def test_missing_plural_category_error_names_key_and_category(read): + with pytest.raises(ValueError) as excinfo: + read('{"files.found": {"one": "1"}}') + assert "files.found" in str(excinfo.value) + assert "many" in str(excinfo.value) + + +# --------------------------------------------------------------------------- +# User overlay +# --------------------------------------------------------------------------- + + +def test_user_subset_overrides_single_keys(installed): + installed.user("de", {"greeting": "Moin"}) + manager = installed.make() + manager.set_language("de") + assert manager.t("greeting") == "Moin" + assert manager.t("farewell") == "Tschüss" + + +def test_user_can_add_new_keys(installed): + installed.user("de", {"brand.new": "Neu"}) + manager = installed.make() + manager.set_language("de") + assert manager.t("brand.new") == "Neu" + + +def test_user_overlay_applies_to_the_default_language(installed): + installed.user("en", {"greeting": "Howdy"}) + manager = installed.make() + assert manager.t("greeting") == "Howdy" + assert manager.t("farewell") == "Goodbye" + + +def test_user_overlay_applies_to_english_fallback(installed): + installed.user("en", {"only.en": "Customized fallback"}) + manager = installed.make() + manager.set_language("de") + assert manager.t("only.en") == "Customized fallback" + + +def test_user_plural_entry_replaces_whole_installed_entry(installed): + installed.user("de", {"files.found": {"one": "Genau eine", "many": "Viele: #count"}}) + manager = installed.make() + manager.set_language("de") + assert manager.p("files.found", 1) == "Genau eine" + assert manager.p("files.found", 3) == "Viele: 3" + # "zero" is not taken from the installed file, but derived from the + # user file's "many" text. + assert manager.p("files.found", 0) == "Viele: 0" + + +@pytest.mark.parametrize( + "content", + [ + pytest.param("{ kaputt", id="invalid-json"), + pytest.param("[1, 2, 3]", id="not-an-object"), + pytest.param({"greeting": "Moin", "x": {"one": "nur eins"}}, id="invalid-plural"), + pytest.param(b"\xff\xfe\x00", id="invalid-utf-8"), + ], +) +def test_invalid_user_file_is_ignored_as_a_whole(installed, log_warnings, content): + installed.user("de", content) + manager = installed.make() + manager.set_language("de") + # Even a valid key of a broken file is not applied. + assert manager.t("greeting") == "Hallo" + assert any("Custom translation file" in m for m in log_warnings()) + + +def test_installed_file_is_never_modified(installed): + path = installed.installed_file("de", "strings.json") + before = path.read_bytes() + installed.user("de", {"greeting": "Moin"}) + manager = installed.make() + manager.set_language("de") + assert path.read_bytes() == before + + +# --------------------------------------------------------------------------- +# Regional layering: installed parent < installed region < user parent < user region +# --------------------------------------------------------------------------- + + +def test_layer_priority(env): + env.install("en", EN) + env.install("de", {"language": "Deutsch", "k1": "inst-de", "k2": "inst-de", + "k3": "inst-de", "k4": "inst-de"}) + env.install("de_AT", {"language": "Österreichisch", "k1": "inst-at", + "k2": "inst-at", "k3": "inst-at"}) + env.user("de", {"k1": "user-de", "k2": "user-de"}) + env.user("de_AT", {"k1": "user-at"}) + manager = env.make() + manager.set_language("de_AT") + assert manager.t("k1") == "user-at" + assert manager.t("k2") == "user-de" + assert manager.t("k3") == "inst-at" + assert manager.t("k4") == "inst-de" + + +def test_region_inherits_everything_not_overridden_from_parent(env): + env.install("en", EN) + env.install("de", DE) + env.install("de_AT", {"language": "Österreichisch", "greeting": "Servus"}) + manager = env.make() + manager.set_language("de_AT") + assert manager.t("greeting") == "Servus" + assert manager.t("farewell") == "Tschüss" + + +def test_regional_variant_only_in_user_directory_with_installed_parent(installed): + installed.user("de_AT", {"language": "Österreichisch", "greeting": "Servus"}) + manager = installed.make() + manager.set_language("de_AT") + assert manager.t("greeting") == "Servus" + assert manager.t("farewell") == "Tschüss" + + +# --------------------------------------------------------------------------- +# Resources that change or vanish after start-up +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("damage", "error"), + [ + (lambda path: path.unlink(), FileNotFoundError), + (lambda path: path.write_text("{ kaputt", encoding="utf-8"), ValueError), + ], + ids=["deleted-file", "corrupted-file"], +) +def test_broken_installed_file_keeps_state_and_does_not_notify(env, damage, error): + env.install_defaults() + env.install("fr", {"language": "Français", "greeting": "Bonjour"}) + manager = env.make() + damage(env.installed_file("fr", "strings.json")) + calls = [] + manager.add_language_change_listener(calls.append) + with pytest.raises(error): + manager.set_language("fr") + assert manager.get_language() == "en" + assert manager.t("greeting") == "Hello" + assert calls == [] + + +# --------------------------------------------------------------------------- +# _get_translations +# --------------------------------------------------------------------------- + + +def test_get_translations_returns_current_language_mapping(manager): + assert manager._get_translations()["greeting"] == "Hello" + manager.set_language("de") + assert manager._get_translations()["greeting"] == "Hallo" + + +def test_get_translations_returns_a_deep_copy(manager): + translations = manager._get_translations() + translations["greeting"] = "Mutated" + translations["files.found"]["one"] = "Mutated" + translations["new"] = "x" + assert manager.t("greeting") == "Hello" + assert manager.p("files.found", 1) == "One file" + assert "new" not in manager._get_translations() diff --git a/test/test_normalize.py b/test/test_normalize.py new file mode 100644 index 0000000..46c1665 --- /dev/null +++ b/test/test_normalize.py @@ -0,0 +1,67 @@ +"""Tests for ``_normalize_language_id`` and ``_language_fallbacks``.""" + +import pytest + +from ki18n.ki18n import _language_fallbacks, _normalize_language_id + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("en", "en"), + ("EN", "en"), + ("de_de", "de_DE"), + ("de-DE", "de_DE"), + ("DE-de.utf8", "de_DE"), + ("de_DE.UTF-8", "de_DE"), + ("de_DE@euro", "de_DE"), + ("en_US.UTF-8@foo", "en_US"), + (" de ", "de"), + ("sr_latn_rs", "sr_Latn_RS"), + ("zh-hant-tw", "zh_Hant_TW"), + ("es_419", "es_419"), + ("de_variant1", "de_variant1"), + ("de_DE_POSIX", "de_DE_posix"), + ], +) +def test_valid_ids_are_normalized(raw, expected): + assert _normalize_language_id(raw) == expected + + +@pytest.mark.parametrize("raw", ["de_DE", "sr_Latn_RS", "en", "es_419"]) +def test_normalization_is_idempotent(raw): + assert _normalize_language_id(raw) == raw + + +@pytest.mark.parametrize( + "raw", + ["", " ", "_", "-", "de_", "_de", "de__DE", "!", "de/DE", "d e", ".UTF-8", + "../x", "dé", "de_D€"], +) +def test_invalid_ids_raise_value_error(raw): + with pytest.raises(ValueError): + _normalize_language_id(raw) + + +@pytest.mark.parametrize("raw", [None, 5, b"de", ["de"]]) +def test_non_string_raises_value_error(raw): + with pytest.raises(ValueError): + _normalize_language_id(raw) + + +@pytest.mark.parametrize( + ("code", "expected"), + [ + ("en", ("en",)), + ("de_CH", ("de_CH", "de")), + ("sr_Latn_RS", ("sr_Latn_RS", "sr_Latn", "sr")), + ("DE-de.UTF-8", ("de_DE", "de")), + ], +) +def test_language_fallbacks(code, expected): + assert _language_fallbacks(code) == expected + + +def test_language_fallbacks_reject_invalid_id(): + with pytest.raises(ValueError): + _language_fallbacks("!!") diff --git a/test/test_paths.py b/test/test_paths.py new file mode 100644 index 0000000..73e1587 --- /dev/null +++ b/test/test_paths.py @@ -0,0 +1,44 @@ +"""Tests for ``ki18n.paths`` (PyInstaller / source checkout detection).""" + +import sys +from pathlib import Path + +from ki18n import paths + + +def test_not_frozen_by_default(monkeypatch): + monkeypatch.setattr(sys, "frozen", False, raising=False) + assert paths.is_frozen() is False + + +def test_frozen_flag_detected(monkeypatch): + monkeypatch.setattr(sys, "frozen", True, raising=False) + assert paths.is_frozen() is True + + +def test_is_frozen_returns_bool(monkeypatch): + monkeypatch.setattr(sys, "frozen", 1, raising=False) + assert paths.is_frozen() is True + + +def test_source_checkout_uses_parent_of_package_directory(monkeypatch): + monkeypatch.setattr(sys, "frozen", False, raising=False) + assert paths.bundle_root() == Path(paths.__file__).resolve().parent.parent + + +def test_frozen_uses_meipass(monkeypatch, tmp_path): + monkeypatch.setattr(sys, "frozen", True, raising=False) + monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False) + assert paths.bundle_root() == tmp_path + + +def test_frozen_without_meipass_uses_executable_directory(monkeypatch, tmp_path): + executable = tmp_path.resolve() / "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(): + assert isinstance(paths.bundle_root(), Path) diff --git a/test/test_plural.py b/test/test_plural.py new file mode 100644 index 0000000..de2dfb3 --- /dev/null +++ b/test/test_plural.py @@ -0,0 +1,164 @@ +"""Tests for ``Ki18n.p`` (plural forms).""" + +import pytest + +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Category selection +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("count", "expected"), + [ + (0, "No files"), + (1, "One file"), + (2, "2 files"), + (3, "3 files"), + (5, "5 files"), + (100, "100 files"), + (10**9, "1000000000 files"), + (None, "Count missing"), + (0.0, "No files"), + (1.0, "One file"), + (2.5, "2.5 files"), + ], +) +def test_category_selection(manager, count, expected): + assert manager.p("files.found", count) == expected + + +@pytest.mark.parametrize("count", [-1, -100, -0.5]) +def test_negative_counts_raise_value_error(manager, count): + with pytest.raises(ValueError): + manager.p("files.found", count) + + +def test_negative_count_raises_even_for_unknown_key(manager): + with pytest.raises(ValueError): + manager.p("unknown.key", -1) + + +def test_returns_string(manager): + assert isinstance(manager.p("files.found", 3), str) + + +@pytest.mark.parametrize( + ("count", "expected"), + [(0, "Keine Dateien"), (1, "Eine Datei"), (4, "4 Dateien")], +) +def test_uses_active_language(manager, count, expected): + manager.set_language("de") + assert manager.p("files.found", count) == expected + + +# --------------------------------------------------------------------------- +# Placeholders +# --------------------------------------------------------------------------- + + +@pytest.fixture +def placeholders(env): + env.install("en", { + "language": "English", + "braces": {"one": "{count} item", "many": "{count} items"}, + "mixed": {"one": "#count file ({count})", "many": "#count files ({count})"}, + "folder": {"one": "#count file in {folder}", "many": "#count files in {folder}"}, + "twice": {"one": "x", "many": "#count of #count"}, + "plain": "Total: {count}", + }) + return env.make() + + +def test_brace_count_placeholder(placeholders): + assert placeholders.p("braces", 1) == "1 item" + assert placeholders.p("braces", 7) == "7 items" + + +def test_hash_and_brace_count_can_be_combined(placeholders): + assert placeholders.p("mixed", 3) == "3 files (3)" + + +def test_additional_keyword_placeholders(placeholders): + assert placeholders.p("folder", 3, folder="docs") == "3 files in docs" + assert placeholders.p("folder", 1, folder="docs") == "1 file in docs" + + +def test_missing_keyword_placeholder_returns_text_with_count_replaced(placeholders): + assert placeholders.p("folder", 3) == "3 files in {folder}" + + +def test_every_hash_count_occurrence_is_replaced(placeholders): + assert placeholders.p("twice", 4) == "4 of 4" + + +@pytest.mark.parametrize( + ("count", "expected"), + [(0, "Total: 0"), (1, "Total: 1"), (9, "Total: 9"), (None, "Total: None")], +) +def test_plain_string_is_used_for_every_category(placeholders, count, expected): + assert placeholders.p("plain", count) == expected + + +# --------------------------------------------------------------------------- +# Fallbacks +# --------------------------------------------------------------------------- + + +@pytest.fixture +def fallback(env): + env.install("en", {**EN, "english.plain": "English plain {count}"}) + env.install("de", DE) + env.install("fr", {"language": "Français"}) + return env.make() + + +@pytest.mark.parametrize( + ("count", "expected"), + [(0, "No files"), (1, "One file"), (3, "3 files"), (None, "Count missing")], +) +def test_falls_back_to_english_categories(fallback, count, expected): + fallback.set_language("fr") + assert fallback.p("files.found", count) == expected + + +def test_english_plain_string_is_used_as_fallback(fallback): + fallback.set_language("fr") + assert fallback.p("english.plain", 2) == "English plain 2" + + +def test_english_wins_over_default(fallback): + fallback.set_language("fr") + assert fallback.p("files.found", 3, default="Fallback") == "3 files" + + +def test_current_language_wins_over_english(fallback): + fallback.set_language("de") + assert fallback.p("files.found", 3, default="Fallback") == "3 Dateien" + + +def test_default_is_used_for_unknown_key(fallback): + assert fallback.p("unknown", 3, default="Fallback") == "Fallback" + + +def test_default_supports_count_placeholders(fallback): + assert fallback.p("unknown", 3, default="{count} things") == "3 things" + assert fallback.p("unknown", 2, default="#count things") == "2 things" + + +def test_default_supports_additional_keywords(fallback): + assert fallback.p("unknown", 3, default="{count} in {where}", where="here") == "3 in here" + + +def test_key_is_used_when_nothing_else_is_available(fallback): + assert fallback.p("unknown", 3) == "unknown" + + +def test_without_english_resources_unknown_key_falls_back_to_default_or_key(env): + env.install("de", DE) + manager = env.make("de") + assert manager.p("files.found", 1) == "Eine Datei" + assert manager.p("unknown", 1) == "unknown" + assert manager.p("unknown", 1, default="Vorgabe") == "Vorgabe" diff --git a/test/test_public_api.py b/test/test_public_api.py new file mode 100644 index 0000000..a507de8 --- /dev/null +++ b/test/test_public_api.py @@ -0,0 +1,51 @@ +"""Tests of the public API as described in the README.""" + +import importlib +from pathlib import Path + +import pytest + +import ki18n + +ki18n_module = importlib.import_module("ki18n.ki18n") + + +# The README shows ``from ki18n import Ki18n, i18n``. The package's +# ``__init__.py`` is currently empty, so these cases are expected to fail until +# the package re-exports the names (the demo scripts take the detour +# ``from ki18n.ki18n import ...``). Remove the xfail marker once it does. +# @pytest.mark.xfail(strict=True, raises=ImportError, +# reason="ki18n/__init__.py does not re-export the public names") +@pytest.mark.parametrize( + ("name", "target"), + [("Ki18n", "Ki18n"), ("i18n", "i18n"), ("I18n", "Ki18n")], +) +def test_package_exports_documented_names(name, target): + namespace: dict = {} + exec(f"from ki18n import {name}", namespace) + assert namespace[name] is getattr(ki18n_module, target) + + +def test_py_typed_marker_is_shipped(): + assert (Path(ki18n.__file__).parent / "py.typed").is_file() + + +@pytest.mark.parametrize( + "name", + [ + "get_language", + "get_default_language", + "get_available_languages", + "set_language", + "t", + "p", + "get_help", + "add_language_change_listener", + "remove_language_change_listener", + "add_listener", + "remove_listener", + "_get_translations", + ], +) +def test_manager_provides_documented_methods(name): + assert callable(getattr(ki18n_module.Ki18n, name)) diff --git a/test/test_screens.py b/test/test_screens.py new file mode 100644 index 0000000..98a4860 --- /dev/null +++ b/test/test_screens.py @@ -0,0 +1,317 @@ +"""Tests of the Textual dialogs ``HelpScreen`` and ``LanguageSelectScreen``. + +The dialogs run inside Textual's headless test driver (``App.run_test``) and are +operated through its ``Pilot`` (clicks and key presses), so no real terminal is +needed. The tests are ``async`` and rely on ``pytest-asyncio``. +""" + +import pytest +from textual.app import App +from textual.widgets import Button, Label, MarkdownViewer + +from ki18n.help_screen import HelpScreen +from ki18n.ki18n import i18n +from ki18n.language_select_screen import LanguageSelectScreen +from support import DE, DIALOG_DE, DIALOG_EN, EN + +pytestmark = pytest.mark.asyncio + +#: Terminal size used for all tests (large enough for every dialog). +SIZE = (120, 50) + +HELP_EN = "# Help (English)\n\nSome text.\n" +HELP_DE = "# Hilfe (Deutsch)\n" + + +# --------------------------------------------------------------------------- +# Fixtures and helpers +# --------------------------------------------------------------------------- + + +@pytest.fixture +def dialogs(env): + """Installed ``en``, ``de`` and a partially translated ``fr``.""" + env.install("en", {**EN, **DIALOG_EN}, HELP_EN) + env.install("de", {**DE, **DIALOG_DE}, HELP_DE) + env.install("fr", {"language": "Français", "greeting": "Bonjour", + "title_select_language": "Choisir la langue"}) + return env + + +@pytest.fixture +def i18n_manager(dialogs): + """The ``Ki18n`` singleton used by the dialogs (through the ``i18n`` handle).""" + return dialogs.make() + + +async def show(pilot, screen): + """Push ``screen`` and return a list that collects its dismiss result.""" + results = [] + pilot.app.push_screen(screen, results.append) + await pilot.pause() + return results + + +def text_of(widget) -> str: + return str(widget.content) + + +def language_buttons(screen): + return [b for b in screen.query(Button) if (b.id or "").startswith("lang-")] + + +# --------------------------------------------------------------------------- +# HelpScreen +# --------------------------------------------------------------------------- + + +class TestHelpScreen: + async def test_shows_help_of_active_language(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + viewer = screen.query_one("#help-text", MarkdownViewer) + assert viewer.document.source == HELP_EN + + async def test_shows_help_of_switched_language(self, i18n_manager): + i18n_manager.set_language("de") + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + viewer = screen.query_one("#help-text", MarkdownViewer) + assert viewer.document.source == HELP_DE + + async def test_title_and_close_button_use_active_language(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + assert text_of(screen.query_one("#help-title", Label)) == "Example help" + assert str(screen.query_one("#help-close", Button).label) == "Close" + + async def test_title_and_close_button_follow_language_change(self, i18n_manager): + i18n_manager.set_language("de") + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + assert text_of(screen.query_one("#help-title", Label)) == "Beispiel-Hilfe" + assert str(screen.query_one("#help-close", Button).label) == "Schließen" + + async def test_missing_help_shows_translated_message(self, dialogs, i18n_manager): + for language in ("en", "de"): + dialogs.installed_file(language, "help.md").unlink() + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + viewer = screen.query_one("#help-text", MarkdownViewer) + assert viewer.document.source == "Help file is missing!" + + async def test_table_of_contents_is_shown_by_default(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + await show(pilot, screen) + assert screen.query_one("#help-text", MarkdownViewer).show_table_of_contents is True + + async def test_table_of_contents_can_be_disabled(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen(toc=False) + await show(pilot, screen) + assert screen.query_one("#help-text", MarkdownViewer).show_table_of_contents is False + + async def test_clicking_close_dismisses_the_screen(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + results = await show(pilot, screen) + await pilot.click("#help-close") + assert results == [None] + assert pilot.app.screen is not screen + + async def test_escape_dismisses_the_screen(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = HelpScreen() + results = await show(pilot, screen) + await pilot.press("escape") + assert results == [None] + assert pilot.app.screen is not screen + + +# --------------------------------------------------------------------------- +# LanguageSelectScreen +# --------------------------------------------------------------------------- + + +class TestLanguageSelectScreen: + async def test_one_button_per_language_in_display_order(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + await show(pilot, screen) + buttons = language_buttons(screen) + assert [b.id for b in buttons] == ["lang-en", "lang-de", "lang-fr"] + assert [str(b.label) for b in buttons] == ["English", "Deutsch", "Français"] + + async def test_active_language_is_highlighted(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + await show(pilot, screen) + variants = {b.id: b.variant for b in language_buttons(screen)} + assert variants == {"lang-en": "primary", "lang-de": "default", "lang-fr": "default"} + + async def test_highlight_follows_language_change(self, i18n_manager): + i18n_manager.set_language("de") + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + await show(pilot, screen) + variants = {b.id: b.variant for b in language_buttons(screen)} + assert variants["lang-de"] == "primary" + assert variants["lang-en"] == "default" + + async def test_title_and_cancel_button_use_active_language(self, i18n_manager): + i18n_manager.set_language("de") + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + await show(pilot, screen) + assert text_of(screen.query_one("#language-title", Label)) == "Sprache wählen" + assert str(screen.query_one("#language-cancel", Button).label) == "Abbrechen" + + async def test_untranslated_keys_fall_back_to_english(self, i18n_manager): + i18n_manager.set_language("fr") + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + await show(pilot, screen) + assert text_of(screen.query_one("#language-title", Label)) == "Choisir la langue" + assert str(screen.query_one("#language-cancel", Button).label) == "Cancel" + + async def test_clicking_a_language_returns_its_id(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + results = await show(pilot, screen) + await pilot.click("#lang-de") + assert results == ["de"] + assert pilot.app.screen is not screen + + async def test_the_dialog_does_not_change_the_language_itself(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + await show(pilot, LanguageSelectScreen()) + await pilot.click("#lang-de") + assert i18n_manager.get_language() == "en" + + async def test_selected_id_can_be_applied_to_the_manager(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + results = await show(pilot, LanguageSelectScreen()) + await pilot.click("#lang-fr") + i18n_manager.set_language(results[0]) + assert i18n_manager.get_language() == "fr" + + async def test_first_button_is_focused_and_tab_moves_to_the_next(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + results = await show(pilot, LanguageSelectScreen()) + assert pilot.app.focused.id == "lang-en" + await pilot.press("tab", "enter") + assert results == ["de"] + + async def test_enter_selects_the_focused_language(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + results = await show(pilot, LanguageSelectScreen()) + await pilot.press("enter") + assert results == ["en"] + + async def test_regional_language_id_is_returned_unchanged(self, dialogs): + dialogs.install("de_AT", {"language": "Österreichisch"}) + dialogs.make() + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + results = await show(pilot, screen) + assert "lang-de_AT" in [b.id for b in language_buttons(screen)] + await pilot.click("#lang-de_AT") + assert results == ["de_AT"] + + async def test_clicking_cancel_returns_none(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + results = await show(pilot, screen) + await pilot.click("#language-cancel") + assert results == [None] + assert pilot.app.screen is not screen + + async def test_escape_returns_none(self, i18n_manager): + async with App().run_test(size=SIZE) as pilot: + screen = LanguageSelectScreen() + results = await show(pilot, screen) + await pilot.press("escape") + assert results == [None] + assert pilot.app.screen is not screen + + +# --------------------------------------------------------------------------- +# Both dialogs inside a small application (integration) +# --------------------------------------------------------------------------- + + +class DemoApp(App): + """Minimal app: ``l`` opens the language dialog, ``f1`` the help dialog.""" + + BINDINGS = [("l", "choose_language", "Language"), ("f1", "show_help", "Help")] + + def compose(self): + self.greeting = Label(i18n.t("greeting"), id="greeting") + yield self.greeting + + def on_mount(self) -> None: + i18n.add_language_change_listener(self._language_changed) + + def on_unmount(self) -> None: + i18n.remove_language_change_listener(self._language_changed) + + def _language_changed(self, code: str) -> None: + self.greeting.update(i18n.t("greeting")) + + def action_choose_language(self) -> None: + self.push_screen(LanguageSelectScreen(), self._apply_language) + + def _apply_language(self, code: str | None) -> None: + if code is not None: + i18n.set_language(code) + + def action_show_help(self) -> None: + self.push_screen(HelpScreen(toc=False)) + + +class TestIntegration: + async def test_choosing_a_language_updates_the_application(self, i18n_manager): + app = DemoApp() + async with app.run_test(size=SIZE) as pilot: + assert text_of(app.greeting) == "Hello" + await pilot.press("l") + assert isinstance(app.screen, LanguageSelectScreen) + await pilot.click("#lang-de") + assert not isinstance(app.screen, LanguageSelectScreen) + assert i18n.get_language() == "de" + assert text_of(app.greeting) == "Hallo" + + async def test_cancelling_keeps_the_language(self, i18n_manager): + app = DemoApp() + async with app.run_test(size=SIZE) as pilot: + await pilot.press("l") + await pilot.press("escape") + assert i18n.get_language() == "en" + assert text_of(app.greeting) == "Hello" + + async def test_help_dialog_shows_help_of_the_chosen_language(self, i18n_manager): + app = DemoApp() + async with app.run_test(size=SIZE) as pilot: + await pilot.press("l") + await pilot.click("#lang-de") + await pilot.press("f1") + assert isinstance(app.screen, HelpScreen) + viewer = app.screen.query_one("#help-text", MarkdownViewer) + assert viewer.document.source == HELP_DE + await pilot.press("escape") + assert not isinstance(app.screen, HelpScreen) + + async def test_dialogs_stack_above_the_application_screen(self, i18n_manager): + app = DemoApp() + async with app.run_test(size=SIZE) as pilot: + assert len(app.screen_stack) == 1 + await pilot.press("f1") + assert len(app.screen_stack) == 2 + await pilot.press("escape") + assert len(app.screen_stack) == 1 diff --git a/test/test_set_language.py b/test/test_set_language.py new file mode 100644 index 0000000..b3204da --- /dev/null +++ b/test/test_set_language.py @@ -0,0 +1,219 @@ +"""Tests for ``set_language`` and the language-change listeners.""" + +import pytest + +from ki18n.ki18n import Ki18n + + +# --------------------------------------------------------------------------- +# set_language +# --------------------------------------------------------------------------- + + +def test_initial_language_is_default(manager): + assert manager.get_language() == "en" + + +def test_switching_changes_translations(manager): + manager.set_language("de") + assert manager.get_language() == "de" + assert manager.t("greeting") == "Hallo" + manager.set_language("en") + assert manager.t("greeting") == "Hello" + + +def test_returns_none(manager): + assert manager.set_language("de") is None + + +def test_default_language_is_unchanged_by_switching(manager): + manager.set_language("de") + assert manager.get_default_language() == "en" + + +@pytest.mark.parametrize("code", ["DE", "De", "dE"]) +def test_language_ids_are_case_insensitive(manager, code): + manager.set_language(code) + assert manager.get_language() == "de" + + +def test_posix_style_ids_are_accepted(manager): + manager.set_language("de_DE.UTF-8") + assert manager.get_language() == "de" + + +def test_unavailable_region_resolves_to_configured_parent(manager): + manager.set_language("de_CH") + assert manager.get_language() == "de" + assert manager.t("greeting") == "Hallo" + assert manager.get_language() in manager.get_available_languages() + + +def test_unavailable_region_of_active_language_is_noop(manager): + calls = [] + manager.add_language_change_listener(calls.append) + manager.set_language("en_US") + assert manager.get_language() == "en" + assert calls == [] + + +@pytest.mark.parametrize("code", ["xx", "fr", "xx_YY"]) +def test_unknown_language_raises_value_error(manager, code): + with pytest.raises(ValueError, match="Unknown language"): + manager.set_language(code) + + +@pytest.mark.parametrize("code", ["", "!!", "de/DE", None, 42]) +def test_invalid_language_id_raises_value_error(manager, code): + with pytest.raises(ValueError, match="Unknown language"): + manager.set_language(code) + + +def test_failed_switch_keeps_state_and_does_not_notify(manager): + calls = [] + manager.add_language_change_listener(calls.append) + with pytest.raises(ValueError): + manager.set_language("xx") + assert manager.get_language() == "en" + assert manager.t("greeting") == "Hello" + assert calls == [] + + +def test_selecting_the_active_language_is_a_noop(env, manager): + calls = [] + manager.add_language_change_listener(calls.append) + # Changes on disk are not read in when the call is a no-op. + env.installed_file("en", "strings.json").write_text( + '{"language": "English", "greeting": "Changed"}', encoding="utf-8" + ) + manager.set_language("en") + assert manager.t("greeting") == "Hello" + assert calls == [] + + +def test_switching_reloads_from_disk(env, manager): + manager.set_language("de") + env.installed_file("de", "strings.json").write_text( + '{"language": "Deutsch", "greeting": "Servus"}', encoding="utf-8" + ) + manager.set_language("en") + manager.set_language("de") + assert manager.t("greeting") == "Servus" + + +def test_switching_to_configured_regional_language(env): + env.install_defaults() + env.install("de_AT", {"language": "Österreichisch", "greeting": "Servus"}) + manager = env.make() + manager.set_language("DE-at") + assert manager.get_language() == "de_AT" + assert manager.t("greeting") == "Servus" + assert manager.t("farewell") == "Tschüss" + + +def test_regional_request_resolves_to_most_specific_configured_parent(env): + env.install_defaults() + env.install("de_AT", {"language": "Österreichisch"}) + manager = env.make() + manager.set_language("de_AT_Wien") + assert manager.get_language() == "de_AT" + + +# --------------------------------------------------------------------------- +# Listeners +# --------------------------------------------------------------------------- + + +@pytest.fixture +def listener_manager(env): + env.install_defaults() + env.install("fr", {"language": "Français", "greeting": "Bonjour"}) + return env.make() + + +def test_listener_receives_normalized_configured_id(listener_manager): + calls = [] + listener_manager.add_language_change_listener(calls.append) + listener_manager.set_language("DE-ch.utf8") + assert calls == ["de"] + + +def test_listener_is_called_once_per_change(listener_manager): + calls = [] + listener_manager.add_language_change_listener(calls.append) + listener_manager.set_language("de") + listener_manager.set_language("de") + listener_manager.set_language("fr") + assert calls == ["de", "fr"] + + +def test_listener_sees_new_state(listener_manager): + seen = [] + listener_manager.add_language_change_listener( + lambda code: seen.append( + (code, listener_manager.get_language(), listener_manager.t("greeting")) + ) + ) + listener_manager.set_language("fr") + assert seen == [("fr", "fr", "Bonjour")] + + +def test_registering_twice_has_no_additional_effect(listener_manager): + calls = [] + listener_manager.add_language_change_listener(calls.append) + listener_manager.add_language_change_listener(calls.append) + listener_manager.set_language("de") + assert calls == ["de"] + + +def test_remove_listener(listener_manager): + calls = [] + listener_manager.add_language_change_listener(calls.append) + listener_manager.remove_language_change_listener(calls.append) + listener_manager.set_language("de") + assert calls == [] + + +def test_removing_unknown_or_removed_listener_is_harmless(listener_manager): + listener_manager.remove_language_change_listener(lambda code: None) + calls = [] + listener_manager.add_language_change_listener(calls.append) + listener_manager.remove_language_change_listener(calls.append) + listener_manager.remove_language_change_listener(calls.append) + + +def test_multiple_listeners_are_called_in_registration_order(listener_manager): + order = [] + listener_manager.add_language_change_listener(lambda code: order.append("a")) + listener_manager.add_language_change_listener(lambda code: order.append("b")) + listener_manager.add_language_change_listener(lambda code: order.append("c")) + listener_manager.set_language("de") + assert order == ["a", "b", "c"] + + +def test_listener_may_remove_itself_while_being_notified(listener_manager): + order = [] + + def once(code): + order.append("once") + listener_manager.remove_language_change_listener(once) + + def always(code): + order.append("always") + + listener_manager.add_language_change_listener(once) + listener_manager.add_language_change_listener(always) + listener_manager.set_language("de") + listener_manager.set_language("fr") + assert order == ["once", "always", "always"] + + +def test_compatibility_aliases(listener_manager): + assert Ki18n.add_listener is Ki18n.add_language_change_listener + assert Ki18n.remove_listener is Ki18n.remove_language_change_listener + calls = [] + listener_manager.add_listener(calls.append) + listener_manager.set_language("de") + listener_manager.remove_listener(calls.append) + listener_manager.set_language("fr") + assert calls == ["de"] diff --git a/test/test_shipped_resources.py b/test/test_shipped_resources.py new file mode 100644 index 0000000..2b3b977 --- /dev/null +++ b/test/test_shipped_resources.py @@ -0,0 +1,166 @@ +"""Consistency of the bundled language files under ``/i18n``. + +These tests check the resources that are actually shipped (read-only): valid +structure, the keys needed by the Textual dialogs, and matching keys and +placeholders across languages. +""" + +import re + +import pytest + +from ki18n.ki18n import Ki18n, _normalize_language_id +from support import PROJECT_ROOT + +I18N_DIR = PROJECT_ROOT / "i18n" + +pytestmark = pytest.mark.skipif( + not I18N_DIR.is_dir(), reason="no i18n directory in the project" +) + +#: Keys required by HelpScreen and LanguageSelectScreen according to the README. +DIALOG_KEYS = ( + "language", + "title_select_language", + "title_help", + "btn_close", + "btn_cancel", + "msg_help_missing", +) + +_PLACEHOLDER = re.compile(r"\{(\w*)\}") + + +def _language_dirs(): + return sorted(p for p in I18N_DIR.iterdir() if p.is_dir()) if I18N_DIR.is_dir() else [] + + +def _placeholders(value) -> dict[str, set[str]]: + """Placeholders per category (``""`` for plain strings).""" + if isinstance(value, str): + return {"": set(_PLACEHOLDER.findall(value))} + return {category: set(_PLACEHOLDER.findall(text)) for category, text in value.items()} + + +@pytest.fixture(scope="module") +def languages() -> dict[str, dict]: + """All shipped languages, loaded and validated by the library.""" + return { + directory.name: Ki18n._read_strings_file(directory / "strings.json") + for directory in _language_dirs() + } + + +@pytest.fixture +def shipped_manager(env): + return Ki18n("en", project_root=PROJECT_ROOT, local_root=env.user_dir) + + +# --------------------------------------------------------------------------- +# Static checks of the files +# --------------------------------------------------------------------------- + + +def test_default_language_is_shipped(languages): + assert "en" in languages + + +@pytest.mark.parametrize("directory", _language_dirs(), ids=lambda p: p.name) +class TestEachShippedLanguage: + def test_directory_name_is_a_normalized_language_id(self, directory): + assert _normalize_language_id(directory.name) == directory.name + + def test_has_a_display_name(self, languages, directory): + name = languages[directory.name].get("language") + assert isinstance(name, str) + assert name.strip() + + @pytest.mark.parametrize("key", DIALOG_KEYS) + def test_provides_dialog_key(self, languages, directory, key): + value = languages[directory.name].get(key) + assert isinstance(value, str) + assert value.strip() + + def test_ships_a_non_empty_help_file(self, directory): + help_file = directory / "help.md" + assert help_file.is_file() + assert help_file.read_text(encoding="utf-8").strip() + + def test_defines_the_same_keys_as_english(self, languages, directory): + reference = set(languages["en"]) + keys = set(languages[directory.name]) + assert keys - reference == set(), "extra keys" + assert reference - keys == set(), "missing keys" + + def test_plural_entries_match_english(self, languages, directory): + english = languages["en"] + for key, value in languages[directory.name].items(): + if key in english: + assert isinstance(value, dict) == isinstance(english[key], dict), key + + def test_placeholders_match_english(self, languages, directory): + english = languages["en"] + for key, value in languages[directory.name].items(): + if key not in english: + continue + expected = _placeholders(english[key]) + actual = _placeholders(value) + for category in expected.keys() & actual.keys(): + assert actual[category] == expected[category], (key, category) + + def test_plural_entries_define_all_categories_after_loading(self, languages, directory): + for key, value in languages[directory.name].items(): + if isinstance(value, dict): + assert set(value) == {"zero", "one", "many", "none"}, key + + +# --------------------------------------------------------------------------- +# With the manager +# --------------------------------------------------------------------------- + + +def test_manager_discovers_all_shipped_languages(shipped_manager): + expected = {_normalize_language_id(p.name) for p in _language_dirs()} + assert set(shipped_manager.get_available_languages()) == expected + + +def test_every_shipped_language_can_be_activated(shipped_manager): + for code in shipped_manager.get_available_languages(): + shipped_manager.set_language(code) + assert shipped_manager.get_language() == code + assert shipped_manager.t("title_help") != "title_help" + assert shipped_manager.get_help().strip() + + +def test_every_plural_entry_works_for_every_category(shipped_manager): + for code in shipped_manager.get_available_languages(): + shipped_manager.set_language(code) + plural_keys = [ + key for key, value in shipped_manager._get_translations().items() + if isinstance(value, dict) + ] + for key in plural_keys: + for count in (0, 1, 2, None): + text = shipped_manager.p(key, count) + assert isinstance(text, str) + assert text != key, (code, key, count) + + +def test_english_demo_plural_texts(shipped_manager): + assert shipped_manager.p("files.found", 0) == "Found no files" + assert shipped_manager.p("files.found", 1) == "Found one file" + assert shipped_manager.p("files.found", 5) == "found 5 files" + assert shipped_manager.p("files.found", None) == "Parameter file count is missing!" + + +def test_german_demo_plural_texts(shipped_manager): + shipped_manager.set_language("de") + assert shipped_manager.p("files.found", 0) == "Keine Datei gefunden" + assert shipped_manager.p("files.found", 1) == "Eine Datei gefunden" + assert shipped_manager.p("files.found", 5) == "5 Dateien gefunden" + + +def test_demo_placeholder_text(shipped_manager): + assert shipped_manager.t("status.generated", files=6) == "Generated: 6" + shipped_manager.set_language("de") + assert shipped_manager.t("status.generated", files=6) == "Generiert: 6" diff --git a/test/test_translate.py b/test/test_translate.py new file mode 100644 index 0000000..237044a --- /dev/null +++ b/test/test_translate.py @@ -0,0 +1,209 @@ +"""Tests for ``Ki18n.t`` (simple translation, fallbacks, formatting).""" + +import pytest + +from support import DE, EN + + +# --------------------------------------------------------------------------- +# Fallback order +# --------------------------------------------------------------------------- + + +def test_current_language(manager): + assert manager.t("greeting") == "Hello" + manager.set_language("de") + assert manager.t("greeting") == "Hallo" + + +def test_falls_back_to_english_when_key_is_missing_in_current_language(manager): + manager.set_language("de") + assert manager.t("only.en") == "Only in English" + + +def test_english_wins_over_supplied_default(manager): + manager.set_language("de") + assert manager.t("only.en", default="Fallback") == "Only in English" + + +def test_default_is_used_when_key_is_unknown(manager): + assert manager.t("missing.key", default="Fallback text") == "Fallback text" + + +def test_key_is_used_when_nothing_else_is_available(manager): + assert manager.t("missing.key") == "missing.key" + + +def test_empty_default_is_still_a_default(manager): + assert manager.t("missing.key", default="") == "" + + +def test_empty_translation_is_returned_and_does_not_fall_back(env): + env.install_defaults() + env.install("fr", {"language": "Français", "greeting": ""}) + manager = env.make() + manager.set_language("fr") + assert manager.t("greeting") == "" + + +def test_translation_is_not_stripped(env): + env.install_defaults() + env.install("fr", {"language": "Français", "padded": " x "}) + manager = env.make() + manager.set_language("fr") + assert manager.t("padded") == " x " + + +def test_pluralized_entry_must_use_p(manager): + with pytest.raises(ValueError, match="files.found") as excinfo: + manager.t("files.found") + assert "p()" in str(excinfo.value) + + +def test_english_pluralized_entry_must_use_p_in_other_language(env): + env.install_defaults() + env.install("fr", {"language": "Français"}) + manager = env.make() + manager.set_language("fr") + with pytest.raises(ValueError): + manager.t("files.found") + + +# --------------------------------------------------------------------------- +# Non-English default language +# --------------------------------------------------------------------------- + + +def test_without_english_resources_unknown_keys_fall_back_to_default_or_key(env): + env.install("de", DE) + manager = env.make("de") + assert manager.t("greeting") == "Hallo" + assert manager.t("missing") == "missing" + assert manager.t("missing", default="Vorgabe") == "Vorgabe" + + +def test_english_is_loaded_lazily_as_fallback_for_non_english_default(env): + env.install("de", DE) + env.install("en", EN) + manager = env.make("de") + assert manager.t("only.en") == "Only in English" + + +def test_broken_english_resources_are_not_swallowed(env): + # English is installed but broken: the error must not be swallowed + # (only a *missing* English is optional). + env.install("de", DE) + env.install("en", EN) + manager = env.make("de") + env.installed_file("en", "strings.json").write_text("{ kaputt", encoding="utf-8") + with pytest.raises(ValueError): + manager.t("only.en") + + +# --------------------------------------------------------------------------- +# Formatting +# --------------------------------------------------------------------------- + + +@pytest.fixture +def fr(env): + """Manager whose active language ``fr`` provides tricky format strings.""" + env.install_defaults() + env.install( + "fr", + { + "language": "Français", + "braces": "Literal {braces}", + "doubled": "a {{literal}} b", + "number": "Wert: {n:05d}", + "positional": "Hallo {}", + "indexed": "Hallo {0}", + "broken": "Offen {", + "badspec": "Wert: {n:d}", + "item": "Erstes: {items[0]}", + "attr": "Wert: {name.nope}", + "idx": "Wert: {name[x]}", + }, + ) + manager = env.make() + manager.set_language("fr") + return manager + + +def test_keyword_placeholder_is_formatted(manager): + assert manager.t("welcome", name="Ada") == "Welcome, Ada!" + + +def test_non_string_values_are_formatted(manager): + assert manager.t("welcome", name=42) == "Welcome, 42!" + + +def test_extra_keyword_arguments_are_ignored(manager): + assert manager.t("welcome", name="Ada", unused=1) == "Welcome, Ada!" + + +def test_missing_placeholder_value_returns_unformatted_text(manager): + assert manager.t("welcome", other="x") == "Welcome, {name}!" + + +def test_without_keyword_arguments_text_is_not_formatted(manager): + assert manager.t("welcome") == "Welcome, {name}!" + + +def test_without_keyword_arguments_escaped_braces_stay_untouched(fr): + assert fr.t("doubled") == "a {{literal}} b" + + +def test_escaped_braces_are_collapsed_when_formatting(fr): + assert fr.t("doubled", x=1) == "a {literal} b" + + +def test_format_specification(fr): + assert fr.t("number", n=42) == "Wert: 00042" + + +@pytest.mark.parametrize( + ("key", "kwargs", "expected"), + [ + ("badspec", {"n": "text"}, "Wert: {n:d}"), # ValueError + ("positional", {"x": 1}, "Hallo {}"), # IndexError + ("indexed", {"x": 1}, "Hallo {0}"), # IndexError + ("broken", {"x": 1}, "Offen {"), # ValueError + ("item", {"items": []}, "Erstes: {items[0]}"), # IndexError + ], +) +def test_formatting_errors_return_unformatted_text(fr, key, kwargs, expected): + assert fr.t(key, **kwargs) == expected + + +def test_indexing_placeholder(fr): + assert fr.t("item", items=["a", "b"]) == "Erstes: a" + + +def test_default_text_is_formatted(manager): + assert manager.t("unknown", default="Hi {name}", name="Bob") == "Hi Bob" + + +def test_key_fallback_is_formatted(manager): + assert manager.t("Hello {name}", name="Bob") == "Hello Bob" + + +def test_unicode_values(manager): + manager.set_language("de") + 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") +@pytest.mark.parametrize( + ("key", "expected"), + [("attr", "Wert: {name.nope}"), ("idx", "Wert: {name[x]}")], + ids=["attribute-error", "type-error"], +) +def test_other_formatting_errors_return_unformatted_text(fr, key, expected): + assert fr.t(key, name="text") == expected diff --git a/textualapp.py b/textualapp.py new file mode 100644 index 0000000..3f5e013 --- /dev/null +++ b/textualapp.py @@ -0,0 +1,89 @@ +""" +A textual app to showcase the use of the Ki18n class. +""" + +from __future__ import annotations +from pathlib import Path + +from textual import work +from textual.app import App, ComposeResult +from textual.widgets import Footer, Header, Log + +# set to the real folder where ki18n lives +from ki18n.ki18n import Ki18n, i18n +from ki18n.help_screen import HelpScreen +from ki18n.language_select_screen import LanguageSelectScreen + + +class TextualApp(App): + + BINDINGS = [ + ("f1", "help", "Help"), + ("ctrl+t", "switch_language", "Language"), + ("d", "toggle_dark", "Toggle dark mode") + ] + + def compose(self) -> ComposeResult: + yield Header() + yield Log() + yield Footer() + + def action_toggle_dark(self) -> None: + """An action to toggle dark mode.""" + self.theme = ( + "textual-dark" if self.theme == "textual-light" else "textual-light" + ) + + def on_ready(self) -> None: + self.log_all() + + @work + async def action_switch_language(self) -> None: + selected = await self.push_screen_wait(LanguageSelectScreen()) + if selected is None or selected == i18n.get_language(): + return + i18n.set_language(selected) + self.log_all() + + def action_help(self) -> None: + if not isinstance(self.screen, HelpScreen): + self.push_screen(HelpScreen()) + + def log_all(self) -> None: + log = self.query_one(Log) + log.write_line(i18n.t("default_and_available")) + + # default = i18n.get_default_language() + log.write_line(i18n.t("lang_default", default_language=i18n.get_default_language())) + available = i18n.get_available_languages() + out = "".join(f"{v}, " for v in available.values()).rstrip(', ') + log.write_line(i18n.t("lang_available", available_languages=out )) + log.write_line("\n") + + language = available[i18n.get_language()] + title = i18n.t("app.title") + log.write_line(i18n.t("translated_title", langstr=language, titlestr=title)) + log.write_line("\n") + + out = i18n.p("files.found", 0) + log.write_line(i18n.t("pluralized_string", numstr=i18n.t("pluralized_zero"), outstr=out)) + out = i18n.p("files.found", 1) + log.write_line(i18n.t("pluralized_string", numstr=i18n.t("pluralized_one"), outstr=out)) + out = i18n.p("files.found", 5) + log.write_line(i18n.t("pluralized_string", numstr=i18n.t("pluralized_five"), outstr=out)) + log.write_line("----------------------------------------------------------------------------\n") + + out = i18n.get_help() + log.write_line(out) + log.write_line("----------------------------------------------------------------------------\n\n") + + +if __name__ == "__main__": + + manager = Ki18n( + default_language="en", + project_root=Path(__file__).resolve().parent, + ) + + app = TextualApp() + app.run() diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..5f13536 --- /dev/null +++ b/uv.lock @@ -0,0 +1,311 @@ +version = 1 +revision = 3 +requires-python = ">=3.10" +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version < '3.11'", +] + +[[package]] +name = "backports-asyncio-runner" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/ff/70dca7d7cb1cbc0edb2c6cc0c38b65cba36cccc491eca64cabd5fe7f8670/backports_asyncio_runner-1.2.0.tar.gz", hash = "sha256:a5aa7b2b7d8f8bfcaa2b57313f70792df84e32a2a746f585213373f900b42162", size = 69893, upload-time = "2025-07-02T02:27:15.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "exceptiongroup" +version = "1.3.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/ac/f882fe3234606340c8729372da0fb98c634b97a560c9d375d9afea21496b/exceptiongroup-1.3.2.tar.gz", hash = "sha256:ca82e69f0cb535fbde934885744b67669a3efddd50fe7bc00d3398839fcaddec", size = 34687, upload-time = "2026-11-19T22:10:16.815Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/7d/0fb19ccdf794c448141461180d5992c50402f69f8515a801bfac7ad65f45/exceptiongroup-1.3.2-py3-none-any.whl", hash = "sha256:41c6a70dfec22050d3d8b43386b059a4dc0bca3f3d40a40971cb206fff1785af", size = 16854, upload-time = "2026-11-19T22:10:15.746Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "ki18n" +version = "0.1.0" +source = { editable = "." } +dependencies = [ + { name = "textual" }, +] + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, + { name = "pytest-asyncio" }, +] + +[package.metadata] +requires-dist = [{ name = "textual", specifier = "==8.2.8" }] + +[package.metadata.requires-dev] +dev = [ + { name = "pytest", specifier = ">=8.0" }, + { name = "pytest-asyncio", specifier = ">=1.0" }, +] + +[[package]] +name = "linkify-it-py" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/98/7a1a5f31fd5c7ba93e963b168e244b8e3dd705b3d2a718e3c3307583bf57/linkify_it_py-2.2.0.tar.gz", hash = "sha256:907acd2d17ac1fbb9ddb62c8957ccbd6158cac602231a15c3b0cd1e215f03cee", size = 32939, upload-time = "2026-08-29T07:07:08.305Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/d4/1152d1c7ab42d8b908be64fd200ddc870dc9d4925e951198702084aa1a7d/linkify_it_py-2.2.0-py3-none-any.whl", hash = "sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443", size = 21971, upload-time = "2026-08-29T07:07:07.164Z" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/fc/cee2c45553c9a9bf77d8b0c391560c556d7ed756b1f0bb35eb5d48db09ea/markdown_it_py-4.3.0.tar.gz", hash = "sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa", size = 242701, upload-time = "2026-11-10T16:18:30.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/31/5f0ac2f1a1c67423c995c731a11cd4ad05d081a2be969d74f868bdb9cc70/markdown_it_py-4.3.0-py3-none-any.whl", hash = "sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa", size = 96951, upload-time = "2026-11-10T16:18:28.975Z" }, +] + +[package.optional-dependencies] +linkify = [ + { name = "linkify-it-py" }, +] + +[[package]] +name = "mdit-py-plugins" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ad/a4/77a4e1be19fd9b08993c76d5e54979ac836b327754f1f5fecfed1b56cc67/mdit_py_plugins-0.7.0.tar.gz", hash = "sha256:26d2179227aaf4d1dc7acffe7a738cbd15cade6b5a61cff0a2cbf9fed93efede", size = 51268, upload-time = "2026-11-10T16:29:31.081Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/d3/d07e61326f150944ead0da9d0b39fb20d7fa367bbc951b10fca6bb1c7382/mdit_py_plugins-0.7.0-py3-none-any.whl", hash = "sha256:7f8e30403f3dd8bfe3afcdcbc6e61066d3f2e714167507b9c26eb385ec399353", size = 72937, upload-time = "2026-11-10T16:29:29.847Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.12.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/90/a1/d5f9002a70298c64a789779077d8dd90c10aa1f47fe40c86802df874f2a6/platformdirs-4.12.4.tar.gz", hash = "sha256:63743c02414e755de4e31b8f68125c1407495b86c5a006e203c01ff8b9924250", size = 60010, upload-time = "2026-10-07T23:30:32.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/ba/223e00b885e960edd5d4b4d178c88acce019bd5b83786093681b8c393492/platformdirs-4.12.4-py3-none-any.whl", hash = "sha256:78bfb9db2a8471ed7eebe3c3c932da413911042994e699b384fbb4493fa872d7", size = 32596, upload-time = "2026-10-07T23:30:30.825Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.5" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d7/9a/8475be631fb33ca1466915e70fd594c42a4e84b512db650eaa14f90fe75d/platformdirs-4.14.5.tar.gz", hash = "sha256:32e9921db7385aa8169bee4fe9501923e5715ba9fb7ea3b9c69b0d8e0639f7a1", size = 71464, upload-time = "2026-11-04T16:54:50.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/ae/ecbbbfd0e4343a6a521d49b3c8656fb4643dee2a4f6eaf941cf3280391a8/platformdirs-4.14.5-py3-none-any.whl", hash = "sha256:8e778c6fa421516f4d3369449f8df3b0e1b72c0e0005fe88e3ec772d0a14e750", size = 35402, upload-time = "2026-11-04T16:54:48.875Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-asyncio-runner", marker = "python_full_version < '3.11'" }, + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2c/de/80724f9b5b9eca1a654179cae6edc51aaa0a355a9834a736e2a188b91780/pytest_asyncio-1.5.0.tar.gz", hash = "sha256:92c8fa83ca419fd0d4bd6a34df6520dae435841d3733c319343249492adf37f7", size = 146227, upload-time = "2026-11-12T16:35:49.845Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/2d/e600d8f47597a803641704aba367c7266cd621f86561ec36da9888f160ec/pytest_asyncio-1.5.0-py3-none-any.whl", hash = "sha256:557f255ee03cc84f84a8d5f438bc9c6e0f714bf86970ae743c7ecb5a38d7e07d", size = 17215, upload-time = "2026-11-12T16:35:48.446Z" }, +] + +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + +[[package]] +name = "textual" +version = "8.2.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py", extra = ["linkify"] }, + { name = "mdit-py-plugins" }, + { name = "platformdirs", version = "4.12.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "platformdirs", version = "4.14.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "pygments" }, + { name = "rich" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/00/21/39a76b01bd5eea82a04baaca7580e105d8c59450df03998345bb2cfb307b/textual-8.2.8.tar.gz", hash = "sha256:3f106a9fbc73e39dd266c9712432087de78a6d644084c7c241d6a25c3169115b", size = 1860502, upload-time = "2026-06-30T06:51:24.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/be/35261223d9416a0751cdff1c7b4a6f881387218a12d439fe22fefebc8c04/textual-8.2.8-py3-none-any.whl", hash = "sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a", size = 731418, upload-time = "2026-06-30T06:51:26.364Z" }, +] + +[[package]] +name = "tomli" +version = "2.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/78/9ad63712633ed3ab5cc1a648d863d7e7da371e9425e209555a0fe711b695/tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6", size = 17662, upload-time = "2026-10-07T12:23:37.892Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/ab99b60ee52acd949684febabc3005d0045d0f66bebd9cdebd67372d26dd/tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545", size = 163901, upload-time = "2026-10-07T12:22:15.601Z" }, + { url = "https://files.pythonhosted.org/packages/bc/00/ee01b7ed4579180fff07142d290257f25ba786f23f3ec6005f620933c2f5/tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef", size = 163756, upload-time = "2026-10-07T12:22:16.957Z" }, + { url = "https://files.pythonhosted.org/packages/72/c2/4efebf65372f6583185f79799312109dddb61102d47e5c33dcfd1a297aca/tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b", size = 268038, upload-time = "2026-10-07T12:22:18.135Z" }, + { url = "https://files.pythonhosted.org/packages/53/07/5850468e925d898abb36038666f9c333a94d2a223e802a8ba5b6d319d23f/tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56", size = 276422, upload-time = "2026-10-07T12:22:19.567Z" }, + { url = "https://files.pythonhosted.org/packages/b4/87/f293984cdcf83c054196d4fd3dad44fc68ae55b4b8c44bc76cef360c3150/tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1", size = 272616, upload-time = "2026-10-07T12:22:20.794Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ce/db582886b3c1219d3fec93ebd669332482e5aee7a91e0f7838d84f2d1759/tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885", size = 276593, upload-time = "2026-10-07T12:22:22.12Z" }, + { url = "https://files.pythonhosted.org/packages/bf/72/7619b87dea4261fc27dd7b54c4461c129c1f7d9bb7ba3aec89c797a431b8/tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e", size = 101830, upload-time = "2026-10-07T12:22:23.651Z" }, + { url = "https://files.pythonhosted.org/packages/1e/74/220106da34502304b6751a2a9b8a9fbca6c3fd47e737a2e2e3da7c61c9db/tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8", size = 112742, upload-time = "2026-10-07T12:22:24.972Z" }, + { url = "https://files.pythonhosted.org/packages/27/99/7d9c8b41837a7773613e169504147375c157a290167aa59ad74a085f521f/tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980", size = 109332, upload-time = "2026-10-07T12:22:26.117Z" }, + { url = "https://files.pythonhosted.org/packages/52/ed/7baa86f87493646a594de388c7c1c40a39dd0461f7e9c0359cbeefc91fe8/tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df", size = 164854, upload-time = "2026-10-07T12:22:27.444Z" }, + { url = "https://files.pythonhosted.org/packages/a5/b1/44c0341f2224397855723c7a8a39f718ea6fcbcc3dacc66e5aeca0f334e3/tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b", size = 164074, upload-time = "2026-10-07T12:22:28.679Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e2d5b7d3fba47adedb23de616c16d428ea076c79a3d8e1d95d649ffe197e/tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0", size = 274274, upload-time = "2026-10-07T12:22:29.804Z" }, + { url = "https://files.pythonhosted.org/packages/43/90/6090e706ff27a6f89f4a40578e3324b95c3cd8c4150868aabf33a8f414c3/tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6", size = 286435, upload-time = "2026-10-07T12:22:31.297Z" }, + { url = "https://files.pythonhosted.org/packages/0a/9e/a2c40768df16c408f22430afb0a73e9d7e5f79c950884954649d1146b74d/tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc", size = 278119, upload-time = "2026-10-07T12:22:32.601Z" }, + { url = "https://files.pythonhosted.org/packages/12/25/3c0cb485b98e9cfac495629b1c93c87ccf0b72fbe9d2689fd8fe62c6d5a3/tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7", size = 286177, upload-time = "2026-10-07T12:22:33.745Z" }, + { url = "https://files.pythonhosted.org/packages/77/8b/0144c65f0e37e51c18d04ae15c21b19431c165002d0131fe9aa8b0b8b1e8/tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2", size = 102760, upload-time = "2026-10-07T12:22:34.887Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/5d6d8f42fc9a05fce69354e00ff256484192f5f2fc9a2165718fa0de61ec/tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7", size = 112722, upload-time = "2026-10-07T12:22:36.162Z" }, + { url = "https://files.pythonhosted.org/packages/30/65/df18032218db0fb9b769fb23c8039a051f15c811993995ea04c350273a32/tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea", size = 109534, upload-time = "2026-10-07T12:22:37.296Z" }, + { url = "https://files.pythonhosted.org/packages/42/e5/51736d70da209350969e15aca5c5ab6e2ce1ea87a0a892a6c13aec172a86/tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea", size = 163328, upload-time = "2026-10-07T12:22:38.373Z" }, + { url = "https://files.pythonhosted.org/packages/ec/55/086f80dab4ab497602644274e6dea7ec5dd0b4e262e443a8ad3bb7edee2d/tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043", size = 162246, upload-time = "2026-10-07T12:22:39.673Z" }, + { url = "https://files.pythonhosted.org/packages/aa/eb/3ecc94459f3635c92321f4e7bde571323fdb2267c50e19e3188a281eae3b/tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0", size = 272655, upload-time = "2026-10-07T12:22:41.08Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d7/494fd1f0c37a621f1ad9975c2efadb523e8101f144ed6edb2e7fe64738f2/tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b", size = 283595, upload-time = "2026-10-07T12:22:42.222Z" }, + { url = "https://files.pythonhosted.org/packages/70/51/bb8d62b1317e6640866f6949b2d5855e5300f2c99d46de1cd245570bba65/tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066", size = 276253, upload-time = "2026-10-07T12:22:43.625Z" }, + { url = "https://files.pythonhosted.org/packages/66/f4/f46bd7f0763cd47de2db697dca9257c6a4adfd1a93b018cc75c8190ed5a8/tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b", size = 283582, upload-time = "2026-10-07T12:22:44.983Z" }, + { url = "https://files.pythonhosted.org/packages/ac/03/70f2bcb2923a6db37818d917e124270a7f4cfd38ea576f5aa753a91c0ef5/tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68", size = 102628, upload-time = "2026-10-07T12:22:46.508Z" }, + { url = "https://files.pythonhosted.org/packages/dc/98/d52024bb5b0ff68b4f0d276d867f634c84a67319a7e9f6b7708a37742333/tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc", size = 113301, upload-time = "2026-10-07T12:22:47.647Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f2/540db3a70572a8c23a28aba3e9c358ce0ffffbafc990905c1343aa265b31/tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84", size = 109744, upload-time = "2026-10-07T12:22:48.925Z" }, + { url = "https://files.pythonhosted.org/packages/e4/49/caf6b307766eb9567664a8707e9d6be5fcc0e8903f18781c6677a60d80c7/tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105", size = 162899, upload-time = "2026-10-07T12:22:50.088Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/68cfce773a2733a49c74f99d627fb461bd990756860099eac25617889585/tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646", size = 162080, upload-time = "2026-10-07T12:22:51.558Z" }, + { url = "https://files.pythonhosted.org/packages/7e/b2/e5bb8651fdad593f670501a7d718b1a7f73f064d44dea15e04c04dfef45d/tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b", size = 273380, upload-time = "2026-10-07T12:22:52.918Z" }, + { url = "https://files.pythonhosted.org/packages/8d/d2/9e2d7f8b1dfe0e2b34c245986ebd55c4c553ea4ce6c47c443b332673253f/tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75", size = 283228, upload-time = "2026-10-07T12:22:54.173Z" }, + { url = "https://files.pythonhosted.org/packages/ba/df/ec7b876b7b1a2718bd74a3743c076fff565b04029ba33e8f61fac262739f/tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb", size = 277189, upload-time = "2026-10-07T12:22:55.342Z" }, + { url = "https://files.pythonhosted.org/packages/7d/7b/e192d9eed0b9cb80da799f4d77052297fb9a2c3cc9b19f571f56ea88add6/tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3", size = 283632, upload-time = "2026-10-07T12:22:56.735Z" }, + { url = "https://files.pythonhosted.org/packages/84/50/ff94454e75461d75623e47401ed323d65c10aab8fe9033242c20cd2fdf32/tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b", size = 103535, upload-time = "2026-10-07T12:22:58.084Z" }, + { url = "https://files.pythonhosted.org/packages/54/0b/bdacf05f963bd6026ebf6eeb0beda847d1d60e03e440725c64a4e08a0afd/tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a", size = 114621, upload-time = "2026-10-07T12:22:59.2Z" }, + { url = "https://files.pythonhosted.org/packages/61/99/53f438fa6ae4f9d4ed0ddde3e7242b3bdc34b48c8f9948b72b9e9b127676/tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3", size = 111572, upload-time = "2026-10-07T12:23:00.479Z" }, + { url = "https://files.pythonhosted.org/packages/b9/20/1f88f19427d380a40e90a770e087489eaafe4aeee070ae88ed2bbec00acd/tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4", size = 171814, upload-time = "2026-10-07T12:23:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d0/56/cbe5079c9f9a54b9b3e27fc82f08f3cb36edee75561679f53d2380c801d6/tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d", size = 171324, upload-time = "2026-10-07T12:23:03.18Z" }, + { url = "https://files.pythonhosted.org/packages/2b/30/1d53fd3b0f1cb3ba542e345ec32c26aefdddc4e829e4f3429af8a4f27782/tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9", size = 297441, upload-time = "2026-10-07T12:23:04.345Z" }, + { url = "https://files.pythonhosted.org/packages/66/d9/0800acb6a111686f764c1b91ef15cc42a20a66a46013bb42220f1d2c61c1/tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f", size = 307476, upload-time = "2026-10-07T12:23:05.671Z" }, + { url = "https://files.pythonhosted.org/packages/e8/63/30a8f3cd51b5bec37f04744bad0b0dc6160df84aad4f27b0e9283d66f221/tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374", size = 296113, upload-time = "2026-10-07T12:23:07.202Z" }, + { url = "https://files.pythonhosted.org/packages/ab/18/0b9ffc597e69c5a1e20a7823cb60d54b39a9f54e91edcb8574f022186758/tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442", size = 307725, upload-time = "2026-10-07T12:23:08.508Z" }, + { url = "https://files.pythonhosted.org/packages/ab/c7/18f8baae0b5607a60e8e19b4a7fedee43a8ff6458e3896dcbbadeeac9c22/tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03", size = 108546, upload-time = "2026-10-07T12:23:09.956Z" }, + { url = "https://files.pythonhosted.org/packages/72/34/4cca9739254130627bde87500b3f2b512154fe2f278efa7e2a5e10ad4bcb/tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1", size = 117814, upload-time = "2026-10-07T12:23:11.486Z" }, + { url = "https://files.pythonhosted.org/packages/7d/fb/afa530d47dd80a78fce43beac6bc6e00f84558eafcffbc6f37b21e80d056/tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0", size = 115188, upload-time = "2026-10-07T12:23:12.728Z" }, + { url = "https://files.pythonhosted.org/packages/66/98/316fdc00f8c0939e6fe50461dd343c162d3ad51d1286eb25b7db54361d50/tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc", size = 162775, upload-time = "2026-10-07T12:23:13.941Z" }, + { url = "https://files.pythonhosted.org/packages/c5/22/7b10fa5bb01c9539f53f69b619361b19350acc73657772ea7ac70ba309a8/tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276", size = 161406, upload-time = "2026-10-07T12:23:15.215Z" }, + { url = "https://files.pythonhosted.org/packages/9c/e7/1a069d86dfd20f1f84f71c63faed9f83c1d890bc06c27d82dc7d888fb573/tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52", size = 273855, upload-time = "2026-10-07T12:23:16.471Z" }, + { url = "https://files.pythonhosted.org/packages/ae/83/d1ef43d1687d092ab9c235455c76e6e709483b346b056f086095c7c263a5/tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7", size = 284910, upload-time = "2026-10-07T12:23:18.166Z" }, + { url = "https://files.pythonhosted.org/packages/cc/05/f4d9cf7de61822ece0c3873f30d291e324911c71a378b8bfe5ced13fd9f5/tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391", size = 277723, upload-time = "2026-10-07T12:23:19.355Z" }, + { url = "https://files.pythonhosted.org/packages/42/28/78262493141fa543151cf005760c3cb01d09fc28a11f993c05109902cb8c/tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859", size = 285115, upload-time = "2026-10-07T12:23:20.698Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b9/e1dab9a30bcb677b5cc5cee810609cfd64f24306a3055767dd3fda00b1e0/tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb", size = 103475, upload-time = "2026-10-07T12:23:21.941Z" }, + { url = "https://files.pythonhosted.org/packages/4c/bd/31a3790c11d6ea95fcf5e6022ac0f8d0543c9b61120b730fc481bd43d3b4/tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5", size = 114589, upload-time = "2026-10-07T12:23:23.098Z" }, + { url = "https://files.pythonhosted.org/packages/47/a2/4f6310fa699364f0e3af7ee3af88dddd9af066d33e716a0265bbe2b3ea84/tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd", size = 111493, upload-time = "2026-10-07T12:23:24.233Z" }, + { url = "https://files.pythonhosted.org/packages/68/14/00853f0b396d8971107ae1921bb5b322fdee1650d2f16bf06c20adb532e5/tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57", size = 171380, upload-time = "2026-10-07T12:23:25.512Z" }, + { url = "https://files.pythonhosted.org/packages/89/ad/fa6949321dadee46b27363974fb197b94c911c3b0f7a5fd26d7dc18fc2a0/tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd", size = 170553, upload-time = "2026-10-07T12:23:26.855Z" }, + { url = "https://files.pythonhosted.org/packages/53/aa/3056c919eb3e084df3752b2cf5f865dcc04af0b27dba2f66d7b28af4633a/tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01", size = 294428, upload-time = "2026-10-07T12:23:28.132Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/faeeb5d8769ea3832021d73e892c8391eae7b4b4f8b55a789127bd8b18a9/tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f", size = 304909, upload-time = "2026-10-07T12:23:29.381Z" }, + { url = "https://files.pythonhosted.org/packages/f6/52/f094c09e73fb654b621716d019acb5d29bdfd1be01df80c281d552bda48d/tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a", size = 293220, upload-time = "2026-10-07T12:23:30.608Z" }, + { url = "https://files.pythonhosted.org/packages/86/f5/0c30541078ca4b505ce3bd76ed931facbfec524dd018535d691d1af0a6d2/tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142", size = 305705, upload-time = "2026-10-07T12:23:32.181Z" }, + { url = "https://files.pythonhosted.org/packages/05/74/590e7d19d6a118fc5cc5704ff358e21d95b8573f6b9443b1519f29ca8825/tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5", size = 108432, upload-time = "2026-10-07T12:23:33.496Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b8/63a75cfb27a17c38550e44025d3a6e7be64516fd8608a3b75703bf37d81b/tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571", size = 117281, upload-time = "2026-10-07T12:23:34.648Z" }, + { url = "https://files.pythonhosted.org/packages/72/01/e8c1debb2173973372934c68fc8e46170ab60ef23ed4592dff4dec6e8993/tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7", size = 115069, upload-time = "2026-10-07T12:23:35.77Z" }, + { url = "https://files.pythonhosted.org/packages/60/3f/3e3f8fd0919249b0200c80fbc4f9a1e70be19f9883da71dfb7f8b9ab8aca/tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b", size = 14765, upload-time = "2026-10-07T12:23:36.875Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +]