refactor(installer): load t() from the shared translations module
This commit is contained in:
1 file changed
+12
-110
+12
-110
@@ -1,118 +1,20 @@
|
|||||||
# FWS — translations of the FWS parts of the installer.
|
# FWS — the installer screens' access to the FWS translations.
|
||||||
#
|
#
|
||||||
# Anaconda translates its own screens through gettext; the FWS screens are not
|
# The implementation lives in /usr/local/lib/fws/fws_i18n.py, shared with the
|
||||||
# in its catalogs. Their texts live in ONE TOML file (one table per message,
|
# FWS tools of the installed system, which must not depend on this folder: its
|
||||||
# one entry per language) and are looked up with t("key").
|
# path follows Python's version and Anaconda can be removed after installing.
|
||||||
#
|
|
||||||
# t() reads $LANG on every call: Anaconda stores the language picked on the
|
|
||||||
# first screen there (and clears LANGUAGE/LC_ALL/LC_MESSAGES). A screen that
|
|
||||||
# sets its texts each time it is shown therefore follows a language change made
|
|
||||||
# by going back to the first screen.
|
|
||||||
#
|
#
|
||||||
# Not a spoke: Anaconda imports every module of this folder while collecting
|
# Not a spoke: Anaconda imports every module of this folder while collecting
|
||||||
# spokes, and an empty __all__ keeps this one out of the collection.
|
# spokes, and an empty __all__ keeps this one out of the collection.
|
||||||
|
|
||||||
import os
|
import importlib.util
|
||||||
import tomllib
|
|
||||||
|
|
||||||
try:
|
_spec = importlib.util.spec_from_file_location("fws_i18n", "/usr/local/lib/fws/fws_i18n.py")
|
||||||
from pyanaconda.anaconda_loggers import get_module_logger
|
_module = importlib.util.module_from_spec(_spec)
|
||||||
log = get_module_logger(__name__)
|
_spec.loader.exec_module(_module)
|
||||||
except ImportError:
|
|
||||||
# Loaded by path from /usr/local/bin/fws-i18n, outside Anaconda.
|
t = _module.t
|
||||||
import logging
|
catalog = _module.catalog
|
||||||
log = logging.getLogger(__name__)
|
language_candidates = _module.language_candidates
|
||||||
|
|
||||||
__all__ = []
|
__all__ = []
|
||||||
|
|
||||||
TRANSLATIONS_FILE = "/usr/local/share/fws/installer-translations.toml"
|
|
||||||
FALLBACK_LANGUAGE = "en"
|
|
||||||
|
|
||||||
_cache = {"mtime": None, "messages": {}}
|
|
||||||
_reported = set()
|
|
||||||
|
|
||||||
|
|
||||||
def _flatten(table, prefix=""):
|
|
||||||
"""Yield (key, {language: text}) for every message of the TOML tree."""
|
|
||||||
texts = {name: value for name, value in table.items() if isinstance(value, str)}
|
|
||||||
if texts and prefix:
|
|
||||||
yield prefix, texts
|
|
||||||
for name, value in table.items():
|
|
||||||
if isinstance(value, dict):
|
|
||||||
yield from _flatten(value, f"{prefix}.{name}" if prefix else name)
|
|
||||||
|
|
||||||
|
|
||||||
def _messages():
|
|
||||||
try:
|
|
||||||
mtime = os.stat(TRANSLATIONS_FILE).st_mtime
|
|
||||||
except OSError:
|
|
||||||
return {}
|
|
||||||
if _cache["mtime"] != mtime:
|
|
||||||
try:
|
|
||||||
with open(TRANSLATIONS_FILE, "rb") as fh:
|
|
||||||
_cache["messages"] = dict(_flatten(tomllib.load(fh)))
|
|
||||||
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
||||||
# A broken file must not take the installer down: keys are shown
|
|
||||||
# instead of texts, which is visible but harmless.
|
|
||||||
log.error("FWS: unreadable translations file %s: %s", TRANSLATIONS_FILE, exc)
|
|
||||||
_cache["messages"] = {}
|
|
||||||
_cache["mtime"] = mtime
|
|
||||||
return _cache["messages"]
|
|
||||||
|
|
||||||
|
|
||||||
def language_candidates(locale_name=None):
|
|
||||||
"""Languages to try, most specific first, always ending with the fallback.
|
|
||||||
|
|
||||||
"sr_RS.UTF-8@latin" -> sr_RS@latin, sr@latin, sr_RS, sr, en
|
|
||||||
"fr_CH.UTF-8" -> fr_CH, fr, en
|
|
||||||
"""
|
|
||||||
if locale_name is None:
|
|
||||||
locale_name = os.environ.get("LANG", "")
|
|
||||||
base, _, modifier = locale_name.partition("@")
|
|
||||||
base = base.split(".", 1)[0]
|
|
||||||
language, _, territory = base.partition("_")
|
|
||||||
suffix = f"@{modifier}" if modifier else ""
|
|
||||||
candidates = []
|
|
||||||
if territory:
|
|
||||||
candidates.append(f"{language}_{territory}{suffix}")
|
|
||||||
candidates.append(f"{language}{suffix}")
|
|
||||||
if suffix:
|
|
||||||
if territory:
|
|
||||||
candidates.append(f"{language}_{territory}")
|
|
||||||
candidates.append(language)
|
|
||||||
candidates.append(FALLBACK_LANGUAGE)
|
|
||||||
return [c for c in dict.fromkeys(candidates) if c]
|
|
||||||
|
|
||||||
|
|
||||||
def t(key, **fields):
|
|
||||||
"""Text of `key` in the installer's current language.
|
|
||||||
|
|
||||||
Named `fields` fill the {placeholders} of the text. An unknown key is
|
|
||||||
returned as is, so a missing translation shows up on screen instead of
|
|
||||||
crashing the installer.
|
|
||||||
"""
|
|
||||||
texts = _messages().get(key)
|
|
||||||
text = None
|
|
||||||
if texts:
|
|
||||||
for language in language_candidates():
|
|
||||||
text = texts.get(language)
|
|
||||||
if text:
|
|
||||||
break
|
|
||||||
if not text:
|
|
||||||
if key not in _reported:
|
|
||||||
_reported.add(key)
|
|
||||||
log.warning("FWS: no translation for key %s", key)
|
|
||||||
return key
|
|
||||||
if not fields:
|
|
||||||
return text
|
|
||||||
try:
|
|
||||||
return text.format(**fields)
|
|
||||||
except (KeyError, IndexError, ValueError) as exc:
|
|
||||||
# A translation with a wrong placeholder: fall back to the reference
|
|
||||||
# text rather than showing nothing.
|
|
||||||
log.warning("FWS: bad placeholders in %s: %s", key, exc)
|
|
||||||
reference = texts.get(FALLBACK_LANGUAGE, key)
|
|
||||||
try:
|
|
||||||
return reference.format(**fields)
|
|
||||||
except (KeyError, IndexError, ValueError):
|
|
||||||
return reference
|
|
||||||
Reference in new issue
Block a user