squirrel-battle/squirrelbattle/translations.py

83 lines
3.0 KiB
Python
Raw Normal View History

2020-11-27 19:32:40 +00:00
# Copyright (C) 2020 by ÿnérant, eichhornchen, nicomarg, charlse
# SPDX-License-Identifier: GPL-3.0-or-later
2020-11-28 00:59:52 +00:00
import gettext as gt
2020-11-28 02:21:20 +00:00
import os
import subprocess
2020-11-28 02:04:28 +00:00
from pathlib import Path
2020-11-28 00:59:52 +00:00
from typing import Any, List
class Translator:
"""
This module uses gettext to translate strings.
Translator.setlocale defines the language of the strings,
then gettext() translates the message.
"""
SUPPORTED_LOCALES: List[str] = ["en", "fr"]
locale: str = "en"
translators: dict = {}
for language in SUPPORTED_LOCALES:
2020-11-28 02:21:20 +00:00
dir = Path(__file__).parent / "locale" / language / "LC_MESSAGES"
dir.mkdir(parents=True) if not dir.is_dir() else None
if os.path.isfile(dir / "squirrelbattle.mo"):
translators[language] = gt.translation(
"squirrelbattle",
localedir=Path(__file__).parent / "locale",
languages=[language],
)
2020-11-28 00:59:52 +00:00
@classmethod
def setlocale(cls, lang: str) -> None:
"""
Define the language used to translate the game.
The language must be supported, otherwise nothing is done.
"""
lang = lang[:2]
if lang in cls.SUPPORTED_LOCALES:
cls.locale = lang
@classmethod
def get_translator(cls) -> Any:
return cls.translators.get(cls.locale)
2020-11-27 19:32:40 +00:00
@classmethod
2020-11-28 02:04:28 +00:00
def makemessages(cls) -> None: # pragma: no cover
for language in cls.SUPPORTED_LOCALES:
2020-11-28 02:21:20 +00:00
file_name = Path(__file__).parent / "locale" / language \
/ "LC_MESSAGES" / "squirrelbattle.po"
2020-11-28 02:04:28 +00:00
args = ["find", "squirrelbattle", "-iname", "*.py"]
find = subprocess.Popen(args, cwd=Path(__file__).parent.parent,
stdout=subprocess.PIPE)
args = ["xargs", "xgettext", "--from-code", "utf-8",
"--add-comments",
"--package-name=squirrelbattle",
"--package-version=3.14.1",
"--copyright-holder=ÿnérant, eichhornchen, "
"nicomarg, charlse",
"--msgid-bugs-address=squirrel-battle@crans.org",
2020-11-28 02:21:20 +00:00
"-o", file_name]
if file_name.is_file():
args.append("--join-existing")
print(f"Make {language} messages...")
subprocess.Popen(args, stdin=find.stdout)
@classmethod
2020-11-28 02:04:28 +00:00
def compilemessages(cls) -> None: # pragma: no cover
for language in cls.SUPPORTED_LOCALES:
args = ["msgfmt", "--check-format",
2020-11-28 02:04:28 +00:00
"-o", Path(__file__).parent / "locale" / language
/ "LC_MESSAGES" / "squirrelbattle.mo",
Path(__file__).parent / "locale" / language
/ "LC_MESSAGES" / "squirrelbattle.po"]
print(f"Compiling {language} messages...")
subprocess.Popen(args)
2020-11-27 19:32:40 +00:00
def gettext(message: str) -> str:
2020-11-28 00:59:52 +00:00
"""
Translate a message.
"""
return Translator.get_translator().gettext(message)