|
| 1 | +import babel |
| 2 | +import babel.numbers |
| 3 | +import babel.plural |
| 4 | +from typing import Any, Callable, Dict, List, TYPE_CHECKING, Tuple, Union, cast |
| 5 | +from typing_extensions import Literal |
| 6 | + |
| 7 | +from fluent.syntax import ast as FTL |
| 8 | + |
| 9 | +from .builtins import BUILTINS |
| 10 | +from .prepare import Compiler |
| 11 | +from .resolver import CurrentEnvironment, Message, Pattern, ResolverEnvironment |
| 12 | +from .utils import native_to_fluent |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from .types import FluentNone, FluentType |
| 16 | + |
| 17 | +PluralCategory = Literal['zero', 'one', 'two', 'few', 'many', 'other'] |
| 18 | + |
| 19 | + |
| 20 | +class FluentBundle: |
| 21 | + """ |
| 22 | + Bundles are single-language stores of translations. They are |
| 23 | + aggregate parsed Fluent resources in the Fluent syntax and can |
| 24 | + format translation units (entities) to strings. |
| 25 | +
|
| 26 | + Always use `FluentBundle.get_message` to retrieve translation units from |
| 27 | + a bundle. Generate the localized string by using `format_pattern` on |
| 28 | + `message.value` or `message.attributes['attr']`. |
| 29 | + Translations can contain references to other entities or |
| 30 | + external arguments, conditional logic in form of select expressions, traits |
| 31 | + which describe their grammatical features, and can use Fluent builtins. |
| 32 | + See the documentation of the Fluent syntax for more information. |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__(self, |
| 36 | + locales: List[str], |
| 37 | + functions: Union[Dict[str, Callable[[Any], 'FluentType']], None] = None, |
| 38 | + use_isolating: bool = True): |
| 39 | + self.locales = locales |
| 40 | + self._functions = {**BUILTINS, **(functions or {})} |
| 41 | + self.use_isolating = use_isolating |
| 42 | + self._messages: Dict[str, Union[FTL.Message, FTL.Term]] = {} |
| 43 | + self._terms: Dict[str, Union[FTL.Message, FTL.Term]] = {} |
| 44 | + self._compiled: Dict[str, Message] = {} |
| 45 | + # The compiler is not typed, and this cast is only valid for the public API |
| 46 | + self._compiler = cast(Callable[[Union[FTL.Message, FTL.Term]], Message], Compiler()) |
| 47 | + self._babel_locale = self._get_babel_locale() |
| 48 | + self._plural_form = cast(Callable[[Any], Callable[[Union[int, float]], PluralCategory]], |
| 49 | + babel.plural.to_python)(self._babel_locale.plural_form) |
| 50 | + |
| 51 | + def add_resource(self, resource: FTL.Resource, allow_overrides: bool = False) -> None: |
| 52 | + # TODO - warn/error about duplicates |
| 53 | + for item in resource.body: |
| 54 | + if not isinstance(item, (FTL.Message, FTL.Term)): |
| 55 | + continue |
| 56 | + map_ = self._messages if isinstance(item, FTL.Message) else self._terms |
| 57 | + full_id = item.id.name |
| 58 | + if full_id not in map_ or allow_overrides: |
| 59 | + map_[full_id] = item |
| 60 | + |
| 61 | + def has_message(self, message_id: str) -> bool: |
| 62 | + return message_id in self._messages |
| 63 | + |
| 64 | + def get_message(self, message_id: str) -> Message: |
| 65 | + return self._lookup(message_id) |
| 66 | + |
| 67 | + def _lookup(self, entry_id: str, term: bool = False) -> Message: |
| 68 | + if term: |
| 69 | + compiled_id = '-' + entry_id |
| 70 | + else: |
| 71 | + compiled_id = entry_id |
| 72 | + try: |
| 73 | + return self._compiled[compiled_id] |
| 74 | + except LookupError: |
| 75 | + pass |
| 76 | + entry = self._terms[entry_id] if term else self._messages[entry_id] |
| 77 | + self._compiled[compiled_id] = self._compiler(entry) |
| 78 | + return self._compiled[compiled_id] |
| 79 | + |
| 80 | + def format_pattern(self, |
| 81 | + pattern: Pattern, |
| 82 | + args: Union[Dict[str, Any], None] = None |
| 83 | + ) -> Tuple[Union[str, 'FluentNone'], List[Exception]]: |
| 84 | + if args is not None: |
| 85 | + fluent_args = { |
| 86 | + argname: native_to_fluent(argvalue) |
| 87 | + for argname, argvalue in args.items() |
| 88 | + } |
| 89 | + else: |
| 90 | + fluent_args = {} |
| 91 | + |
| 92 | + errors: List[Exception] = [] |
| 93 | + env = ResolverEnvironment(context=self, |
| 94 | + current=CurrentEnvironment(args=fluent_args), |
| 95 | + errors=errors) |
| 96 | + try: |
| 97 | + result = pattern(env) |
| 98 | + except ValueError as e: |
| 99 | + errors.append(e) |
| 100 | + result = '{???}' |
| 101 | + return (result, errors) |
| 102 | + |
| 103 | + def _get_babel_locale(self) -> babel.Locale: |
| 104 | + for lc in self.locales: |
| 105 | + try: |
| 106 | + return babel.Locale.parse(lc.replace('-', '_')) |
| 107 | + except babel.UnknownLocaleError: |
| 108 | + continue |
| 109 | + # TODO - log error |
| 110 | + return babel.Locale.default() |
0 commit comments