|
| 1 | +from __future__ import absolute_import, unicode_literals |
| 2 | + |
| 3 | +import six |
| 4 | + |
| 5 | +from .syntax import FluentParser |
| 6 | +from .syntax.ast import Message, Term |
| 7 | + |
| 8 | + |
| 9 | +class MessageContext(object): |
| 10 | + """ |
| 11 | + Message contexts are single-language stores of translations. They are |
| 12 | + responsible for parsing translation resources in the Fluent syntax and can |
| 13 | + format translation units (entities) to strings. |
| 14 | +
|
| 15 | + Always use `MessageContext.format` to retrieve translation units from |
| 16 | + a context. Translations can contain references to other entities or |
| 17 | + external arguments, conditional logic in form of select expressions, traits |
| 18 | + which describe their grammatical features, and can use Fluent builtins. |
| 19 | + See the documentation of the Fluent syntax for more information. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, locales, functions=None, use_isolating=True): |
| 23 | + self.locales = locales |
| 24 | + self._functions = functions or {} |
| 25 | + self._use_isolating = use_isolating |
| 26 | + self._messages = {} |
| 27 | + self._terms = {} |
| 28 | + |
| 29 | + def add_messages(self, source): |
| 30 | + parser = FluentParser() |
| 31 | + resource = parser.parse(source) |
| 32 | + # TODO - warn if items get overwritten |
| 33 | + for item in resource.body: |
| 34 | + if isinstance(item, Message): |
| 35 | + self._messages[item.id.name] = item |
| 36 | + elif isinstance(item, Term): |
| 37 | + self._terms[item.id.name] = item |
| 38 | + |
| 39 | + def has_message(self, message_id): |
| 40 | + return message_id in self._messages |
| 41 | + |
| 42 | + def messages(self): |
| 43 | + """ |
| 44 | + Returns iterable of (id, message) for the messages in this context |
| 45 | + """ |
| 46 | + return six.iteritems(self._messages) |
0 commit comments