Debian Codegraph @

babel/messages/catalog.py

raw
1 """
2 babel.messages.catalog
3 ~~~~~~~~~~~~~~~~~~~~~~
4
5 Data structures for message catalogs.
6
7 :copyright: (c) 2013-2026 by the Babel Team.
8 :license: BSD, see LICENSE for more details.
9 """
10
11 from __future__ import annotations
12
13 import datetime
14 import re
15 from collections.abc import Iterable, Iterator
16 from copy import copy
17 from difflib import SequenceMatcher
18 from email import message_from_string
19 from heapq import nlargest
20 from string import Formatter
21 from typing import TYPE_CHECKING
22
23 from babel import __version__ as VERSION
24 from babel.core import Locale, UnknownLocaleError
25 from babel.dates import format_datetime
26 from babel.messages.plurals import get_plural
27 from babel.util import LOCALTZ, _cmp
28
29 if TYPE_CHECKING:
30 from typing_extensions import TypeAlias
31
32 _MessageID: TypeAlias = str | tuple[str, ...] | list[str]
33
34 __all__ = [
35 'DEFAULT_HEADER',
36 'PYTHON_FORMAT',
37 'Catalog',
38 'Message',
39 'TranslationError',
40 ]
41
42
43 def get_close_matches(word, possibilities, n=3, cutoff=0.6):
44 """A modified version of ``difflib.get_close_matches``.
45
46 It just passes ``autojunk=False`` to the ``SequenceMatcher``, to work
47 around https://github.com/python/cpython/issues/90825.
48 """
49 if not n > 0: # pragma: no cover
50 raise ValueError(f"n must be > 0: {n!r}")
51 if not 0.0 <= cutoff <= 1.0: # pragma: no cover
52 raise ValueError(f"cutoff must be in [0.0, 1.0]: {cutoff!r}")
53 result = []
54 s = SequenceMatcher(autojunk=False) # only line changed from difflib.py
55 s.set_seq2(word)
56 for x in possibilities:
57 s.set_seq1(x)
58 if (
59 s.real_quick_ratio() >= cutoff
60 and s.quick_ratio() >= cutoff
61 and s.ratio() >= cutoff
62 ):
63 result.append((s.ratio(), x))
64
65 # Move the best scorers to head of list
66 result = nlargest(n, result)
67 # Strip scores for the best n matches
68 return [x for score, x in result]
69
70
71 PYTHON_FORMAT = re.compile(
72 r'''
73 \%
74 (?:\(([\w]*)\))?
75 (
76 [-#0\ +]?(?:\*|[\d]+)?
77 (?:\.(?:\*|[\d]+))?
78 [hlL]?
79 )
80 ([diouxXeEfFgGcrs%])
81 ''',
82 re.VERBOSE,
83 )
84
85
86 def _has_python_brace_format(string: str) -> bool:
87 if "{" not in string:
88 return False
89 fmt = Formatter()
90 try:
91 # `fmt.parse` returns 3-or-4-tuples of the form
92 # `(literal_text, field_name, format_spec, conversion)`;
93 # if `field_name` is set, this smells like brace format
94 field_name_seen = False
95 for t in fmt.parse(string):
96 if t[1] is not None:
97 field_name_seen = True
98 # We cannot break here, as we need to consume the whole string
99 # to ensure that it is a valid format string.
100 except ValueError:
101 return False
102 return field_name_seen
103
104
105 def _parse_datetime_header(value: str) -> datetime.datetime:
106 match = re.match(r'^(?P<datetime>.*?)(?P<tzoffset>[+-]\d{4})?$', value)
107
108 dt = datetime.datetime.strptime(match.group('datetime'), '%Y-%m-%d %H:%M')
109
110 # Separate the offset into a sign component, hours, and # minutes
111 tzoffset = match.group('tzoffset')
112 if tzoffset is not None:
113 plus_minus_s, rest = tzoffset[0], tzoffset[1:]
114 hours_offset_s, mins_offset_s = rest[:2], rest[2:]
115
116 # Make them all integers
117 plus_minus = int(f"{plus_minus_s}1")
118 hours_offset = int(hours_offset_s)
119 mins_offset = int(mins_offset_s)
120
121 # Calculate net offset
122 net_mins_offset = hours_offset * 60
123 net_mins_offset += mins_offset
124 net_mins_offset *= plus_minus
125
126 # Create an offset object
127 tzoffset = datetime.timezone(
128 offset=datetime.timedelta(minutes=net_mins_offset),
129 name=f'Etc/GMT{net_mins_offset:+d}',
130 )
131
132 # Store the offset in a datetime object
133 dt = dt.replace(tzinfo=tzoffset)
134
135 return dt
136
137
138 class Message:
139 """Representation of a single message in a catalog."""
140
141 def __init__(
142 self,
143 id: _MessageID,
144 string: _MessageID | None = '',
145 locations: Iterable[tuple[str, int]] = (),
146 flags: Iterable[str] = (),
147 auto_comments: Iterable[str] = (),
148 user_comments: Iterable[str] = (),
149 previous_id: _MessageID = (),
150 lineno: int | None = None,
151 context: str | None = None,
152 ) -> None:
153 """Create the message object.
154
155 :param id: the message ID, or a ``(singular, plural)`` tuple for
156 pluralizable messages
157 :param string: the translated message string, or a
158 ``(singular, plural)`` tuple for pluralizable messages
159 :param locations: a sequence of ``(filename, lineno)`` tuples
160 :param flags: a set or sequence of flags
161 :param auto_comments: a sequence of automatic comments for the message
162 :param user_comments: a sequence of user comments for the message
163 :param previous_id: the previous message ID, or a ``(singular, plural)``
164 tuple for pluralizable messages
165 :param lineno: the line number on which the msgid line was found in the
166 PO file, if any
167 :param context: the message context
168 """
169 self.id = id
170 if not string and self.pluralizable:
171 string = ('', '')
172 self.string = string
173 self.locations = list(dict.fromkeys(locations)) if locations else []
174 self.flags = set(flags)
175 if id and self.python_format:
176 self.flags.add('python-format')
177 else:
178 self.flags.discard('python-format')
179 if id and self.python_brace_format:
180 self.flags.add('python-brace-format')
181 else:
182 self.flags.discard('python-brace-format')
183 self.auto_comments = list(dict.fromkeys(auto_comments)) if auto_comments else []
184 self.user_comments = list(dict.fromkeys(user_comments)) if user_comments else []
185 if previous_id:
186 if isinstance(previous_id, str):
187 self.previous_id = [previous_id]
188 else:
189 self.previous_id = list(previous_id)
190 else:
191 self.previous_id = []
192 self.lineno = lineno
193 self.context = context
194
195 def __repr__(self) -> str:
196 return f"<{type(self).__name__} {self.id!r} (flags: {list(self.flags)!r})>"
197
198 def __cmp__(self, other: object) -> int:
199 """Compare Messages, taking into account plural ids"""
200
201 def values_to_compare(obj):
202 if isinstance(obj, Message) and obj.pluralizable:
203 return obj.id[0], obj.context or ''
204 return obj.id, obj.context or ''
205
206 return _cmp(values_to_compare(self), values_to_compare(other))
207
208 def __gt__(self, other: object) -> bool:
209 return self.__cmp__(other) > 0
210
211 def __lt__(self, other: object) -> bool:
212 return self.__cmp__(other) < 0
213
214 def __ge__(self, other: object) -> bool:
215 return self.__cmp__(other) >= 0
216
217 def __le__(self, other: object) -> bool:
218 return self.__cmp__(other) <= 0
219
220 def __eq__(self, other: object) -> bool:
221 return self.__cmp__(other) == 0
222
223 def __ne__(self, other: object) -> bool:
224 return self.__cmp__(other) != 0
225
226 def is_identical(self, other: Message) -> bool:
227 """Checks whether messages are identical, taking into account all
228 properties.
229 """
230 assert isinstance(other, Message)
231 return self.__dict__ == other.__dict__
232
233 def clone(self) -> Message:
234 return Message(
235 id=copy(self.id),
236 string=copy(self.string),
237 locations=copy(self.locations),
238 flags=copy(self.flags),
239 auto_comments=copy(self.auto_comments),
240 user_comments=copy(self.user_comments),
241 previous_id=copy(self.previous_id),
242 lineno=self.lineno, # immutable (str/None)
243 context=self.context, # immutable (str/None)
244 )
245
246 def check(self, catalog: Catalog | None = None) -> list[TranslationError]:
247 """Run various validation checks on the message. Some validations
248 are only performed if the catalog is provided. This method returns
249 a sequence of `TranslationError` objects.
250
251 :rtype: ``iterator``
252 :param catalog: A catalog instance that is passed to the checkers
253 :see: `Catalog.check` for a way to perform checks for all messages
254 in a catalog.
255 """
256 from babel.messages.checkers import checkers
257
258 errors: list[TranslationError] = []
259 for checker in checkers:
260 try:
261 checker(catalog, self)
262 except TranslationError as e:
263 errors.append(e)
264 return errors
265
266 @property
267 def fuzzy(self) -> bool:
268 """Whether the translation is fuzzy.
269
270 >>> Message('foo').fuzzy
271 False
272 >>> msg = Message('foo', 'foo', flags=['fuzzy'])
273 >>> msg.fuzzy
274 True
275 >>> msg
276 <Message 'foo' (flags: ['fuzzy'])>
277 """
278 return 'fuzzy' in self.flags
279
280 @property
281 def pluralizable(self) -> bool:
282 """Whether the message is plurizable.
283
284 >>> Message('foo').pluralizable
285 False
286 >>> Message(('foo', 'bar')).pluralizable
287 True
288 """
289 return isinstance(self.id, (list, tuple))
290
291 @property
292 def python_format(self) -> bool:
293 """Whether the message contains Python-style parameters.
294
295 >>> Message('foo %(name)s bar').python_format
296 True
297 >>> Message(('foo %(name)s', 'foo %(name)s')).python_format
298 True
299 """
300 ids = self.id
301 if isinstance(ids, (list, tuple)):
302 for id in ids: # Explicit loop for performance reasons.
303 if PYTHON_FORMAT.search(id):
304 return True
305 return False
306 return bool(PYTHON_FORMAT.search(ids))
307
308 @property
309 def python_brace_format(self) -> bool:
310 """Whether the message contains Python f-string parameters.
311
312 >>> Message('Hello, {name}!').python_brace_format
313 True
314 >>> Message(('One apple', '{count} apples')).python_brace_format
315 True
316 """
317 ids = self.id
318 if isinstance(ids, (list, tuple)):
319 for id in ids: # Explicit loop for performance reasons.
320 if _has_python_brace_format(id):
321 return True
322 return False
323 return _has_python_brace_format(ids)
324
325
326 class TranslationError(Exception):
327 """Exception thrown by translation checkers when invalid message
328 translations are encountered."""
329
330
331 DEFAULT_HEADER = """\
332 # Translations template for PROJECT.
333 # Copyright (C) YEAR ORGANIZATION
334 # This file is distributed under the same license as the PROJECT project.
335 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
336 #"""
337
338
339 def parse_separated_header(value: str) -> dict[str, str]:
340 # Adapted from https://peps.python.org/pep-0594/#cgi
341 from email.message import Message
342
343 m = Message()
344 m['content-type'] = value
345 return dict(m.get_params())
346
347
348 def _force_text(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> str:
349 if isinstance(s, str):
350 return s
351 if isinstance(s, bytes):
352 return s.decode(encoding, errors)
353 return str(s)
354
355
356 class Catalog:
357 """Representation of a message catalog."""
358
359 def __init__(
360 self,
361 locale: Locale | str | None = None,
362 domain: str | None = None,
363 header_comment: str | None = DEFAULT_HEADER,
364 project: str | None = None,
365 version: str | None = None,
366 copyright_holder: str | None = None,
367 msgid_bugs_address: str | None = None,
368 creation_date: datetime.datetime | str | None = None,
369 revision_date: datetime.datetime | datetime.time | float | str | None = None,
370 last_translator: str | None = None,
371 language_team: str | None = None,
372 charset: str | None = None,
373 fuzzy: bool = True,
374 ) -> None:
375 """Initialize the catalog object.
376
377 :param locale: the locale identifier or `Locale` object, or `None`
378 if the catalog is not bound to a locale (which basically
379 means it's a template)
380 :param domain: the message domain
381 :param header_comment: the header comment as string, or `None` for the
382 default header
383 :param project: the project's name
384 :param version: the project's version
385 :param copyright_holder: the copyright holder of the catalog
386 :param msgid_bugs_address: the email address or URL to submit bug
387 reports to
388 :param creation_date: the date the catalog was created
389 :param revision_date: the date the catalog was revised
390 :param last_translator: the name and email of the last translator
391 :param language_team: the name and email of the language team
392 :param charset: the encoding to use in the output (defaults to utf-8)
393 :param fuzzy: the fuzzy bit on the catalog header
394 """
395 self.domain = domain
396 self.locale = locale
397 self._header_comment = header_comment
398 self._messages: dict[str | tuple[str, str], Message] = {}
399
400 self.project = project or 'PROJECT'
401 self.version = version or 'VERSION'
402 self.copyright_holder = copyright_holder or 'ORGANIZATION'
403 self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS'
404
405 self.last_translator = last_translator or 'FULL NAME <EMAIL@ADDRESS>'
406 """Name and email address of the last translator."""
407 self.language_team = language_team or 'LANGUAGE <[email protected]>'
408 """Name and email address of the language team."""
409
410 self.charset = charset or 'utf-8'
411
412 if creation_date is None:
413 creation_date = datetime.datetime.now(LOCALTZ)
414 elif isinstance(creation_date, datetime.datetime) and not creation_date.tzinfo:
415 creation_date = creation_date.replace(tzinfo=LOCALTZ)
416 self.creation_date = creation_date
417 if revision_date is None:
418 revision_date = 'YEAR-MO-DA HO:MI+ZONE'
419 elif isinstance(revision_date, datetime.datetime) and not revision_date.tzinfo:
420 revision_date = revision_date.replace(tzinfo=LOCALTZ)
421 self.revision_date = revision_date
422 self.fuzzy = fuzzy
423
424 # Dictionary of obsolete messages
425 self.obsolete: dict[str | tuple[str, str], Message] = {}
426 self._num_plurals = None
427 self._plural_expr = None
428
429 def _set_locale(self, locale: Locale | str | None) -> None:
430 if locale is None:
431 self._locale_identifier = None
432 self._locale = None
433 return
434
435 if isinstance(locale, Locale):
436 self._locale_identifier = str(locale)
437 self._locale = locale
438 return
439
440 if isinstance(locale, str):
441 self._locale_identifier = str(locale)
442 try:
443 self._locale = Locale.parse(locale)
444 except UnknownLocaleError:
445 self._locale = None
446 return
447
448 raise TypeError(
449 f"`locale` must be a Locale, a locale identifier string, or None; got {locale!r}",
450 )
451
452 @property
453 def locale(self) -> Locale | None:
454 return self._locale
455
456 @locale.setter
457 def locale(self, locale: Locale | str | None) -> None:
458 self._set_locale(locale)
459
460 @property
461 def locale_identifier(self) -> str | None:
462 return self._locale_identifier
463
464 def _get_header_comment(self) -> str:
465 comment = self._header_comment
466 year = datetime.datetime.now(LOCALTZ).strftime('%Y')
467 if hasattr(self.revision_date, 'strftime'):
468 year = self.revision_date.strftime('%Y')
469 comment = (
470 comment.replace('PROJECT', self.project)
471 .replace('VERSION', self.version)
472 .replace('YEAR', year)
473 .replace('ORGANIZATION', self.copyright_holder)
474 )
475 locale_name = self.locale.english_name if self.locale else self.locale_identifier
476 if locale_name:
477 comment = comment.replace("Translations template", f"{locale_name} translations")
478 return comment
479
480 def _set_header_comment(self, string: str | None) -> None:
481 self._header_comment = string
482
483 @property
484 def header_comment(self) -> str:
485 """
486 The header comment for the catalog.
487
488 >>> catalog = Catalog(project='Foobar', version='1.0',
489 ... copyright_holder='Foo Company')
490 >>> print(catalog.header_comment) #doctest: +ELLIPSIS
491 # Translations template for Foobar.
492 # Copyright (C) ... Foo Company
493 # This file is distributed under the same license as the Foobar project.
494 # FIRST AUTHOR <EMAIL@ADDRESS>, ....
495 #
496
497 The header can also be set from a string. Any known upper-case variables
498 will be replaced when the header is retrieved again:
499
500 >>> catalog = Catalog(project='Foobar', version='1.0',
501 ... copyright_holder='Foo Company')
502 >>> catalog.header_comment = '''\\
503 ... # The POT for my really cool PROJECT project.
504 ... # Copyright (C) 1990-2003 ORGANIZATION
505 ... # This file is distributed under the same license as the PROJECT
506 ... # project.
507 ... #'''
508 >>> print(catalog.header_comment)
509 # The POT for my really cool Foobar project.
510 # Copyright (C) 1990-2003 Foo Company
511 # This file is distributed under the same license as the Foobar
512 # project.
513 #
514 """
515 return self._get_header_comment()
516
517 @header_comment.setter
518 def header_comment(self, value: str) -> None:
519 self._set_header_comment(value)
520
521 def _get_mime_headers(self) -> list[tuple[str, str]]:
522 if isinstance(self.revision_date, (datetime.datetime, datetime.time, int, float)):
523 revision_date = format_datetime(
524 self.revision_date,
525 'yyyy-MM-dd HH:mmZ',
526 locale='en',
527 )
528 else:
529 revision_date = self.revision_date
530
531 language_team = self.language_team
532 if self.locale_identifier and 'LANGUAGE' in language_team:
533 language_team = language_team.replace('LANGUAGE', str(self.locale_identifier))
534
535 headers: list[tuple[str, str]] = [
536 ("Project-Id-Version", f"{self.project} {self.version}"),
537 ('Report-Msgid-Bugs-To', self.msgid_bugs_address),
538 ('POT-Creation-Date', format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ', locale='en')),
539 ('PO-Revision-Date', revision_date),
540 ('Last-Translator', self.last_translator),
541 ] # fmt: skip
542 if self.locale_identifier:
543 headers.append(('Language', str(self.locale_identifier)))
544 headers.append(('Language-Team', language_team))
545 if self.locale is not None:
546 headers.append(('Plural-Forms', self.plural_forms))
547 headers += [
548 ('MIME-Version', '1.0'),
549 ("Content-Type", f"text/plain; charset={self.charset}"),
550 ('Content-Transfer-Encoding', '8bit'),
551 ("Generated-By", f"Babel {VERSION}\n"),
552 ]
553 return headers
554
555 def _set_mime_headers(self, headers: Iterable[tuple[str, str]]) -> None:
556 for name, value in headers:
557 name = _force_text(name.lower(), encoding=self.charset)
558 value = _force_text(value, encoding=self.charset)
559 if name == 'project-id-version':
560 parts = value.split(' ')
561 self.project = ' '.join(parts[:-1])
562 self.version = parts[-1]
563 elif name == 'report-msgid-bugs-to':
564 self.msgid_bugs_address = value
565 elif name == 'last-translator':
566 self.last_translator = value
567 elif name == 'language':
568 value = value.replace('-', '_')
569 # The `or None` makes sure that the locale is set to None
570 # if the header's value is an empty string, which is what
571 # some tools generate (instead of eliding the empty Language
572 # header altogether).
573 self._set_locale(value or None)
574 elif name == 'language-team':
575 self.language_team = value
576 elif name == 'content-type':
577 params = parse_separated_header(value)
578 if 'charset' in params:
579 self.charset = params['charset'].lower()
580 elif name == 'plural-forms':
581 params = parse_separated_header(f" ;{value}")
582 self._num_plurals = int(params.get('nplurals', 2))
583 self._plural_expr = params.get('plural', '(n != 1)')
584 elif name == 'pot-creation-date':
585 self.creation_date = _parse_datetime_header(value)
586 elif name == 'po-revision-date':
587 # Keep the value if it's not the default one
588 if 'YEAR' not in value:
589 self.revision_date = _parse_datetime_header(value)
590
591 @property
592 def mime_headers(self) -> list[tuple[str, str]]:
593 """
594 The MIME headers of the catalog, used for the special ``msgid ""`` entry.
595
596 The behavior of this property changes slightly depending on whether a locale
597 is set or not, the latter indicating that the catalog is actually a template
598 for actual translations.
599
600 Here's an example of the output for such a catalog template:
601
602 >>> from babel.dates import UTC
603 >>> from datetime import datetime
604 >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
605 >>> catalog = Catalog(project='Foobar', version='1.0',
606 ... creation_date=created)
607 >>> for name, value in catalog.mime_headers:
608 ... print('%s: %s' % (name, value))
609 Project-Id-Version: Foobar 1.0
610 Report-Msgid-Bugs-To: EMAIL@ADDRESS
611 POT-Creation-Date: 1990-04-01 15:30+0000
612 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
613 Last-Translator: FULL NAME <EMAIL@ADDRESS>
614 Language-Team: LANGUAGE <[email protected]>
615 MIME-Version: 1.0
616 Content-Type: text/plain; charset=utf-8
617 Content-Transfer-Encoding: 8bit
618 Generated-By: Babel ...
619
620 And here's an example of the output when the locale is set:
621
622 >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
623 >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
624 ... creation_date=created, revision_date=revised,
625 ... last_translator='John Doe <[email protected]>',
626 ... language_team='de_DE <[email protected]>')
627 >>> for name, value in catalog.mime_headers:
628 ... print('%s: %s' % (name, value))
629 Project-Id-Version: Foobar 1.0
630 Report-Msgid-Bugs-To: EMAIL@ADDRESS
631 POT-Creation-Date: 1990-04-01 15:30+0000
632 PO-Revision-Date: 1990-08-03 12:00+0000
633 Last-Translator: John Doe <[email protected]>
634 Language: de_DE
635 Language-Team: de_DE <[email protected]>
636 Plural-Forms: nplurals=2; plural=(n != 1);
637 MIME-Version: 1.0
638 Content-Type: text/plain; charset=utf-8
639 Content-Transfer-Encoding: 8bit
640 Generated-By: Babel ...
641 """
642 return self._get_mime_headers()
643
644 @mime_headers.setter
645 def mime_headers(self, value: Iterable[tuple[str, str]]) -> None:
646 self._set_mime_headers(value)
647
648 @property
649 def num_plurals(self) -> int:
650 """The number of plurals used by the catalog or locale.
651
652 >>> Catalog(locale='en').num_plurals
653 2
654 >>> Catalog(locale='ga').num_plurals
655 5
656 """
657 if self._num_plurals is None:
658 num = 2
659 if self.locale:
660 num = get_plural(self.locale)[0]
661 self._num_plurals = num
662 return self._num_plurals
663
664 @property
665 def plural_expr(self) -> str:
666 """The plural expression used by the catalog or locale.
667
668 >>> Catalog(locale='en').plural_expr
669 '(n != 1)'
670 >>> Catalog(locale='ga').plural_expr
671 '(n == 1 ? 0 : n == 2 ? 1 : n >= 3 && n <= 6 ? 2 : n >= 7 && n <= 10 ? 3 : 4)'
672 >>> Catalog(locale='ding').plural_expr # unknown locale
673 '(n != 1)'
674 """
675 if self._plural_expr is None:
676 expr = '(n != 1)'
677 if self.locale:
678 expr = get_plural(self.locale)[1]
679 self._plural_expr = expr
680 return self._plural_expr
681
682 @property
683 def plural_forms(self) -> str:
684 """Return the plural forms declaration for the locale.
685
686 >>> Catalog(locale='en').plural_forms
687 'nplurals=2; plural=(n != 1);'
688 >>> Catalog(locale='pt_BR').plural_forms
689 'nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;'
690 """
691 return f"nplurals={self.num_plurals}; plural={self.plural_expr};"
692
693 def __contains__(self, id: _MessageID) -> bool:
694 """Return whether the catalog has a message with the specified ID."""
695 return self._key_for(id) in self._messages
696
697 def __len__(self) -> int:
698 """The number of messages in the catalog.
699
700 This does not include the special ``msgid ""`` entry."""
701 return len(self._messages)
702
703 def __iter__(self) -> Iterator[Message]:
704 """Iterates through all the entries in the catalog, in the order they
705 were added, yielding a `Message` object for every entry.
706
707 :rtype: ``iterator``"""
708 buf = []
709 for name, value in self.mime_headers:
710 buf.append(f"{name}: {value}")
711 flags = set()
712 if self.fuzzy:
713 flags |= {'fuzzy'}
714 yield Message('', '\n'.join(buf), flags=flags)
715 for key in self._messages:
716 yield self._messages[key]
717
718 def __repr__(self) -> str:
719 locale = ''
720 if self.locale:
721 locale = f" {self.locale}"
722 return f"<{type(self).__name__} {self.domain!r}{locale}>"
723
724 def __delitem__(self, id: _MessageID) -> None:
725 """Delete the message with the specified ID."""
726 self.delete(id)
727
728 def __getitem__(self, id: _MessageID) -> Message:
729 """Return the message with the specified ID.
730
731 :param id: the message ID
732 """
733 return self.get(id)
734
735 def __setitem__(self, id: _MessageID, message: Message) -> None:
736 """Add or update the message with the specified ID.
737
738 >>> catalog = Catalog()
739 >>> catalog['foo'] = Message('foo')
740 >>> catalog['foo']
741 <Message 'foo' (flags: [])>
742
743 If a message with that ID is already in the catalog, it is updated
744 to include the locations and flags of the new message.
745
746 >>> catalog = Catalog()
747 >>> catalog['foo'] = Message('foo', locations=[('main.py', 1)])
748 >>> catalog['foo'].locations
749 [('main.py', 1)]
750 >>> catalog['foo'] = Message('foo', locations=[('utils.py', 5)])
751 >>> catalog['foo'].locations
752 [('main.py', 1), ('utils.py', 5)]
753
754 :param id: the message ID
755 :param message: the `Message` object
756 """
757 assert isinstance(message, Message), 'expected a Message object'
758 key = self._key_for(id, message.context)
759 current = self._messages.get(key)
760 if current:
761 if message.pluralizable and not current.pluralizable:
762 # The new message adds pluralization
763 current.id = message.id
764 current.string = message.string
765 current.locations = list(dict.fromkeys([*current.locations, *message.locations]))
766 current.auto_comments = list(dict.fromkeys([*current.auto_comments, *message.auto_comments])) # fmt:skip
767 current.user_comments = list(dict.fromkeys([*current.user_comments, *message.user_comments])) # fmt:skip
768 current.flags |= message.flags
769 elif id == '':
770 # special treatment for the header message
771 self.mime_headers = message_from_string(message.string).items()
772 self.header_comment = "\n".join(f"# {c}".rstrip() for c in message.user_comments)
773 self.fuzzy = message.fuzzy
774 else:
775 if isinstance(id, (list, tuple)):
776 assert isinstance(message.string, (list, tuple)), (
777 f"Expected sequence but got {type(message.string)}"
778 )
779 self._messages[key] = message
780
781 def add(
782 self,
783 id: _MessageID,
784 string: _MessageID | None = None,
785 locations: Iterable[tuple[str, int]] = (),
786 flags: Iterable[str] = (),
787 auto_comments: Iterable[str] = (),
788 user_comments: Iterable[str] = (),
789 previous_id: _MessageID = (),
790 lineno: int | None = None,
791 context: str | None = None,
792 ) -> Message:
793 """Add or update the message with the specified ID.
794
795 >>> catalog = Catalog()
796 >>> catalog.add('foo')
797 <Message ...>
798 >>> catalog['foo']
799 <Message 'foo' (flags: [])>
800
801 This method simply constructs a `Message` object with the given
802 arguments and invokes `__setitem__` with that object.
803
804 :param id: the message ID, or a ``(singular, plural)`` tuple for
805 pluralizable messages
806 :param string: the translated message string, or a
807 ``(singular, plural)`` tuple for pluralizable messages
808 :param locations: a sequence of ``(filename, lineno)`` tuples
809 :param flags: a set or sequence of flags
810 :param auto_comments: a sequence of automatic comments
811 :param user_comments: a sequence of user comments
812 :param previous_id: the previous message ID, or a ``(singular, plural)``
813 tuple for pluralizable messages
814 :param lineno: the line number on which the msgid line was found in the
815 PO file, if any
816 :param context: the message context
817 """
818 message = Message(
819 id,
820 string,
821 list(locations),
822 flags,
823 auto_comments,
824 user_comments,
825 previous_id,
826 lineno=lineno,
827 context=context,
828 )
829 self[id] = message
830 return message
831
832 def check(self) -> Iterable[tuple[Message, list[TranslationError]]]:
833 """Run various validation checks on the translations in the catalog.
834
835 For every message which fails validation, this method yield a
836 ``(message, errors)`` tuple, where ``message`` is the `Message` object
837 and ``errors`` is a sequence of `TranslationError` objects.
838
839 :rtype: ``generator`` of ``(message, errors)``
840 """
841 for message in self._messages.values():
842 errors = message.check(catalog=self)
843 if errors:
844 yield message, errors
845
846 def get(self, id: _MessageID, context: str | None = None) -> Message | None:
847 """Return the message with the specified ID and context.
848
849 :param id: the message ID
850 :param context: the message context, or ``None`` for no context
851 """
852 return self._messages.get(self._key_for(id, context))
853
854 def delete(self, id: _MessageID, context: str | None = None) -> None:
855 """Delete the message with the specified ID and context.
856
857 :param id: the message ID
858 :param context: the message context, or ``None`` for no context
859 """
860 key = self._key_for(id, context)
861 if key in self._messages:
862 del self._messages[key]
863
864 def update(
865 self,
866 template: Catalog,
867 no_fuzzy_matching: bool = False,
868 update_header_comment: bool = False,
869 keep_user_comments: bool = True,
870 update_creation_date: bool = True,
871 ) -> None:
872 """Update the catalog based on the given template catalog.
873
874 >>> from babel.messages import Catalog
875 >>> template = Catalog()
876 >>> template.add('green', locations=[('main.py', 99)])
877 <Message ...>
878 >>> template.add('blue', locations=[('main.py', 100)])
879 <Message ...>
880 >>> template.add(('salad', 'salads'), locations=[('util.py', 42)])
881 <Message ...>
882 >>> catalog = Catalog(locale='de_DE')
883 >>> catalog.add('blue', 'blau', locations=[('main.py', 98)])
884 <Message ...>
885 >>> catalog.add('head', 'Kopf', locations=[('util.py', 33)])
886 <Message ...>
887 >>> catalog.add(('salad', 'salads'), ('Salat', 'Salate'),
888 ... locations=[('util.py', 38)])
889 <Message ...>
890
891 >>> catalog.update(template)
892 >>> len(catalog)
893 3
894
895 >>> msg1 = catalog['green']
896 >>> msg1.string
897 >>> msg1.locations
898 [('main.py', 99)]
899
900 >>> msg2 = catalog['blue']
901 >>> msg2.string
902 'blau'
903 >>> msg2.locations
904 [('main.py', 100)]
905
906 >>> msg3 = catalog['salad']
907 >>> msg3.string
908 ('Salat', 'Salate')
909 >>> msg3.locations
910 [('util.py', 42)]
911
912 Messages that are in the catalog but not in the template are removed
913 from the main collection, but can still be accessed via the `obsolete`
914 member:
915
916 >>> 'head' in catalog
917 False
918 >>> list(catalog.obsolete.values())
919 [<Message 'head' (flags: [])>]
920
921 :param template: the reference catalog, usually read from a POT file
922 :param no_fuzzy_matching: whether to use fuzzy matching of message IDs
923 :param update_header_comment: whether to copy the header comment from the template
924 :param keep_user_comments: whether to keep user comments from the old catalog
925 :param update_creation_date: whether to copy the creation date from the template
926 """
927 messages = self._messages
928 remaining = messages.copy()
929 self._messages = {}
930
931 # Prepare for fuzzy matching
932 fuzzy_candidates = {}
933 if not no_fuzzy_matching:
934 for msgid in messages:
935 if msgid and messages[msgid].string:
936 key = self._key_for(msgid)
937 ctxt = messages[msgid].context
938 fuzzy_candidates[self._to_fuzzy_match_key(key)] = (key, ctxt)
939 fuzzy_matches = set()
940
941 def _merge(
942 message: Message,
943 oldkey: tuple[str, str] | str,
944 newkey: tuple[str, str] | str,
945 ) -> None:
946 message = message.clone()
947 fuzzy = False
948 if oldkey != newkey:
949 fuzzy = True
950 fuzzy_matches.add(oldkey)
951 oldmsg = messages.get(oldkey)
952 assert oldmsg is not None
953 if isinstance(oldmsg.id, str):
954 message.previous_id = [oldmsg.id]
955 else:
956 message.previous_id = list(oldmsg.id)
957 else:
958 oldmsg = remaining.pop(oldkey, None)
959 assert oldmsg is not None
960 message.string = oldmsg.string
961
962 if keep_user_comments and oldmsg.user_comments:
963 message.user_comments = list(dict.fromkeys(oldmsg.user_comments))
964
965 if isinstance(message.id, (list, tuple)):
966 if not isinstance(message.string, (list, tuple)):
967 fuzzy = True
968 message.string = tuple(
969 [message.string] + ([''] * (len(message.id) - 1)),
970 )
971 elif len(message.string) != self.num_plurals:
972 fuzzy = True
973 message.string = tuple(message.string[: len(oldmsg.string)])
974 elif isinstance(message.string, (list, tuple)):
975 fuzzy = True
976 message.string = message.string[0]
977 message.flags |= oldmsg.flags
978 if fuzzy:
979 message.flags |= {'fuzzy'}
980 self[message.id] = message
981
982 for message in template:
983 if message.id:
984 key = self._key_for(message.id, message.context)
985 if key in messages:
986 _merge(message, key, key)
987 else:
988 if not no_fuzzy_matching:
989 # do some fuzzy matching with difflib
990 matches = get_close_matches(
991 self._to_fuzzy_match_key(key),
992 fuzzy_candidates.keys(),
993 1,
994 )
995 if matches:
996 modified_key = matches[0]
997 newkey, newctxt = fuzzy_candidates[modified_key]
998 if newctxt is not None:
999 newkey = newkey, newctxt
1000 _merge(message, newkey, key)
1001 continue
1002
1003 self[message.id] = message
1004
1005 for msgid in remaining:
1006 if no_fuzzy_matching or msgid not in fuzzy_matches:
1007 self.obsolete[msgid] = remaining[msgid]
1008
1009 if update_header_comment:
1010 # Allow the updated catalog's header to be rewritten based on the
1011 # template's header
1012 self.header_comment = template.header_comment
1013
1014 # Make updated catalog's POT-Creation-Date equal to the template
1015 # used to update the catalog
1016 if update_creation_date:
1017 self.creation_date = template.creation_date
1018
1019 def _to_fuzzy_match_key(self, key: tuple[str, str] | str) -> str:
1020 """Converts a message key to a string suitable for fuzzy matching."""
1021 if isinstance(key, tuple):
1022 matchkey = key[0] # just the msgid, no context
1023 else:
1024 matchkey = key
1025 return matchkey.lower().strip()
1026
1027 def _key_for(
1028 self,
1029 id: _MessageID,
1030 context: str | None = None,
1031 ) -> tuple[str, str] | str:
1032 """The key for a message is just the singular ID even for pluralizable
1033 messages, but is a ``(msgid, msgctxt)`` tuple for context-specific
1034 messages.
1035 """
1036 key = id
1037 if isinstance(key, (list, tuple)):
1038 key = id[0]
1039 if context is not None:
1040 key = (key, context)
1041 return key
1042
1043 def is_identical(self, other: Catalog) -> bool:
1044 """Checks if catalogs are identical, taking into account messages and
1045 headers.
1046 """
1047 assert isinstance(other, Catalog)
1048 for key in self._messages.keys() | other._messages.keys():
1049 message_1 = self.get(key)
1050 message_2 = other.get(key)
1051 if message_1 is None or message_2 is None or not message_1.is_identical(message_2):
1052 return False
1053 return dict(self.mime_headers) == dict(other.mime_headers)