Commit 80497dd2 authored by Erxleben, Fredo's avatar Erxleben, Fredo
Browse files

Resolve "Accept IETF language tags"

parent 1b21b523
Pipeline #87086 passed with stages
in 3 minutes and 13 seconds
......@@ -35,11 +35,16 @@ class Translated(YamlConstructable):
A wrapper around text instances with multiple translations.
Languages are identified by their ISO 693-1 two-letter codes.
Optionally an uppercase region identifier may be appended as well. Region
identifiers consist of a two or three letter code and must be separated by
a dash from the language identifier.
Examples for valid identifiers are `de`, `en-US` but not `frFR`.
"""
schema = Schema(
{
And(str, Regex("^[a-z]{2}$")): And(
And(str, Regex("^[a-z]{2}(-[A-Z]{2,3})?$")): And(
str,
lambda s: s,
error="Translation must neither be empty nor None",
......@@ -62,8 +67,8 @@ class Translated(YamlConstructable):
translations:
A mapping from the language code to the translation in the
respective language. The dictionary must not be empty.
Keys are expected to be two-letter codes, and values must
neither be None nor be empty.
Keys are expected to be two-letter codes with an optional
region code, and values must neither be None nor be empty.
"""
self._translations = Translated.schema.validate(translations)
......@@ -80,17 +85,33 @@ class Translated(YamlConstructable):
"""
Get the translation for a specific language.
If the passed in language code has a region specifier, and no
translation for this region is given, a translation with only the
language code will be looked up as a fallback.
Args:
language_code:
The ISO 693-1 two letter code for the language the text is
requested for.
requested for. Optionally a dash followed by an uppercase
two or three letter region code may be appended as well.
Returns:
The text in the requested language or None if no translation for
this language exists.
Raises:
KeyError:
If no translation for the requested language (with or
without region code) can be found.
"""
return self._translations.get(language_code, None)
# TODO: Decide whether it is better to raise an error if the language
# is not available
try:
return self._translations[language_code]
except KeyError:
pass
try:
return self._translations[language_code[0:1]]
except KeyError:
raise KeyError(
f"No translation for {language_code} in {self._translations}"
)
@staticmethod
def _from_yaml_dictionary(yaml: YamlDict, **kwargs) -> "Translated":
......@@ -103,7 +124,7 @@ class Translated(YamlConstructable):
Args:
yaml:
The YamlDict representing the translations.
Keys are expected to be two-letter codes for the language and
Keys are expected to be language and optional region codes and
values are supposed to be the appropriate translations.
Returns:
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment