feat(i18n): share the translations module with the installed system

The FWS tools of the installed system need the same lookup as the
installer screens, but must not depend on Anaconda's folder: its path
follows Python's version and Anaconda can be removed after installing.
The language now follows gettext's order of variables, and
/etc/locale.conf for the tools started through sudo.
This commit is contained in:
nocode committed 2026-11-26 18:18:24 +01:00
1 parent 47fd8340a0
commit 9722d03e82
1 file changed
+176
@@ -0,0 +1,176 @@
# FWS — translations of the FWS installer screens and of the FWS tools.
#
# Anaconda, the desktops and their applications translate themselves through
# gettext; the FWS parts are in none of their catalogs. Their texts live in TOML
# catalogs (one table per message, one entry per language) and are looked up by
# key:
#
# installer-translations.toml the FWS installer screens and live dialogs
# system-translations.toml the FWS tools of the installed system
#
# The language is read from the environment on every call, in gettext's order
# ($LANGUAGE, $LC_ALL, $LC_MESSAGES, $LANG). Anaconda keeps only $LANG, set to
# the language picked on its first screen, so a screen that sets its texts each
# time it is shown follows a language change made by going back to that screen;
# on the installed system the tools follow the desktop's language setting.
#
# This file sits outside Python's versioned site-packages so that the tools
# keep working when Python is upgraded or Anaconda removed.
import os
import tomllib
try:
from pyanaconda.anaconda_loggers import get_module_logger
log = get_module_logger(__name__)
except ImportError:
import logging
log = logging.getLogger(__name__)
TRANSLATIONS_DIR = "/usr/local/share/fws"
FALLBACK_LANGUAGE = "en"
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 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
Without an argument, every locale of the environment is expanded in turn.
"""
names = _environment_locales() if locale_name is None else [locale_name]
candidates = []
for name in names:
base, _, modifier = name.partition("@")
base = base.split(".", 1)[0]
language, _, territory = base.partition("_")
if not language:
continue
suffix = f"@{modifier}" if modifier else ""
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 list(dict.fromkeys(candidates))
def _environment_locales():
"""Message locales of the environment, in gettext's order.
$LANGUAGE is a priority list (de_CH:de:en) that gettext ignores when the
locale itself is C, so it is ignored here too.
"""
env = os.environ
locale_name = env.get("LC_ALL") or env.get("LC_MESSAGES") or env.get("LANG")
if not locale_name:
# sudo can drop the locale variables: a tool run as root then speaks
# the system's language, as systemd services do.
locale_name = _system_locale()
if locale_name.split(".", 1)[0] in ("", "C", "POSIX"):
return []
return [name for name in env.get("LANGUAGE", "").split(":") if name] + [locale_name]
def _system_locale():
try:
with open("/etc/locale.conf", encoding="utf-8") as fh:
for line in fh:
name, _, value = line.strip().partition("=")
if name == "LANG":
return value.strip().strip("\"'")
except OSError:
pass
return ""
class Catalog:
"""One translations file, reloaded when it changes on disk."""
def __init__(self, name):
self.path = os.path.join(TRANSLATIONS_DIR, f"{name}-translations.toml")
self._mtime = None
self._messages = {}
self._reported = set()
def messages(self):
"""{key: {language: text}}; empty when the file is missing or broken."""
try:
mtime = os.stat(self.path).st_mtime
except OSError:
return {}
if self._mtime != mtime:
try:
with open(self.path, "rb") as fh:
self._messages = dict(_flatten(tomllib.load(fh)))
except (OSError, tomllib.TOMLDecodeError) as exc:
# A broken file must not take the program down: keys are shown
# instead of texts, which is visible but harmless.
log.error("FWS: unreadable translations file %s: %s", self.path, exc)
self._messages = {}
self._mtime = mtime
return self._messages
def text(self, key, languages=None):
"""Raw text of `key` (placeholders left in), or None."""
texts = self.messages().get(key)
if texts:
for language in languages or language_candidates():
if texts.get(language):
return texts[language]
return None
def t(self, key, **fields):
"""Text of `key` in the current language.
Named `fields` fill the {placeholders} of the text; fields the text
does not use are ignored. An unknown key is returned as is, so a
missing translation shows up on screen instead of crashing.
"""
text = self.text(key)
if text is None:
if key not in self._reported:
self._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 = self.text(key, [FALLBACK_LANGUAGE]) or key
try:
return reference.format(**fields)
except (KeyError, IndexError, ValueError):
return reference
_catalogs = {}
def catalog(name):
"""The catalog `name` ("installer" or "system"), loaded once per process."""
if name not in _catalogs:
_catalogs[name] = Catalog(name)
return _catalogs[name]
def t(key, **fields):
"""Text of an installer message (see Catalog.t)."""
return catalog("installer").t(key, **fields)