feat(i18n): let fws-i18n export catalogs to Bash and render config files

waybar, polybar and i3 cannot look texts up themselves: --render writes
the texts into their configuration in the language chosen at install.
This commit is contained in:
nocode committed 2026-11-26 18:18:25 +01:00
1 parent 6e0eb8f6fc
commit 0bd81a28a9
1 file changed
+77 -26
@@ -1,40 +1,91 @@
#!/usr/bin/env python3
"""Print an FWS installer text in the language of $LANG.
"""Print FWS texts in the language of the environment.
Usage: fws-i18n <key> [name=value ...]
Usage:
fws-i18n [--catalog NAME] <key> [name=value ...]
fws-i18n --catalog NAME --shell <namespace>...
fws-i18n --catalog NAME --render <file>
Shell side of the installer translations: the live session (/root/.xinitrc)
shows dialogs after the installer has closed, in the language picked on its
first screen. Same file and same lookup as the installer screens, so a key is
translated once for both.
The first form prints one text: the live session (/root/.xinitrc) uses it for
the dialogs shown after the installer has closed. The catalog defaults to
"installer"; "system" holds the texts of the FWS tools.
--shell prints Bash assignments of every text of the given namespaces into the
associative array FWS_T, placeholders left in: /usr/local/lib/fws/i18n.sh loads
them once per script instead of starting Python for every message.
--render prints <file> with each {{t:key}} replaced by its text. The installer
uses it on the desktop configuration files it copies into the home folders.
Texts are escaped for JSON in a .json file; elsewhere their straight quotes are
made typographic, since these files embed them in quoted shell arguments.
"""
import glob
import importlib.util
import json
import re
import shlex
import sys
sys.path.insert(0, "/usr/local/lib/fws")
def main():
if len(sys.argv) < 2:
MARKER = re.compile(r"\{\{t:([a-z0-9_]+(?:\.[a-z0-9_]+)+)\}\}")
TYPOGRAPHIC_QUOTES = str.maketrans({"'": "’", '"': "”"})
def shell_assignments(catalog, namespaces):
lines = ["declare -gA FWS_T"]
for key in sorted(catalog.messages()):
if key.split(".", 1)[0] in namespaces:
text = catalog.text(key)
if text is not None:
lines.append(f"FWS_T[{key}]={shlex.quote(text)}")
return "\n".join(lines)
def render(catalog, path):
with open(path, encoding="utf-8") as fh:
content = fh.read()
as_json = path.endswith(".json")
def replace(match):
text = catalog.t(match.group(1))
if as_json:
return json.dumps(text, ensure_ascii=False)[1:-1]
return text.translate(TYPOGRAPHIC_QUOTES)
return MARKER.sub(replace, content)
def main(argv):
name = "installer"
if len(argv) >= 2 and argv[0] == "--catalog":
name, argv = argv[1], argv[2:]
if not argv:
print(__doc__.strip().splitlines()[2], file=sys.stderr)
return 2
key = sys.argv[1]
fields = dict(arg.split("=", 1) for arg in sys.argv[2:] if "=" in arg)
text = key
# The module sits in Anaconda's folder, whose path follows Python's version.
for path in glob.glob("/usr/lib/python3*/site-packages/pyanaconda/ui/gui/spokes/fws_i18n.py"):
try:
spec = importlib.util.spec_from_file_location("fws_i18n", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
text = module.t(key, **fields)
except Exception: # pylint: disable=broad-except
# A dialog with the key in it beats no dialog at all.
pass
break
print(text)
try:
import fws_i18n
catalog = fws_i18n.catalog(name)
except Exception as exc: # pylint: disable=broad-except
print(f"fws-i18n: {exc}", file=sys.stderr)
catalog = None
if argv[0] == "--shell":
# An empty array still lets the scripts run: they show keys then.
print(shell_assignments(catalog, set(argv[1:])) if catalog
else "declare -gA FWS_T")
return 0
if argv[0] == "--render":
if len(argv) != 2 or catalog is None:
return 2
sys.stdout.write(render(catalog, argv[1]))
return 0
key = argv[0]
fields = dict(arg.split("=", 1) for arg in argv[1:] if "=" in arg)
# A dialog with the key in it beats no dialog at all.
print(catalog.t(key, **fields) if catalog else key)
return 0
if __name__ == "__main__":
sys.exit(main())
sys.exit(main(sys.argv[1:]))