diff --git a/.gitattributes b/.gitattributes index 26ed1ec53ff3e65932276db417ac064110aca5c5..607ca9012c62c91c65405f1ab17f695466aff08b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -85,3 +85,4 @@ lib/python3.10/site-packages/av/error.cpython-310-x86_64-linux-gnu.so filter=lfs lib/python3.10/site-packages/av/dictionary.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/av/container/core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/av/container/pyio.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so b/lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..cf6276841743a7c025826ddb5f4c00d564477c5a --- /dev/null +++ b/lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d76c55337da2ca9a297456b0de0eacf4cce96faf4447eb4b6ccabab56b077a3d +size 864209 diff --git a/lib/python3.10/site-packages/babel/locale-data/ann.dat b/lib/python3.10/site-packages/babel/locale-data/ann.dat new file mode 100644 index 0000000000000000000000000000000000000000..cee6e2bb26f5cedef28b9e63de62244618bd8a72 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ann.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ar_LY.dat b/lib/python3.10/site-packages/babel/locale-data/ar_LY.dat new file mode 100644 index 0000000000000000000000000000000000000000..a870e157c8863cf1aa13c0598ae1b261a4fe1448 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ar_LY.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/en_JM.dat b/lib/python3.10/site-packages/babel/locale-data/en_JM.dat new file mode 100644 index 0000000000000000000000000000000000000000..8bb03e32671a6273b7afb7fd046e3268516761a2 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/en_JM.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/en_NZ.dat b/lib/python3.10/site-packages/babel/locale-data/en_NZ.dat new file mode 100644 index 0000000000000000000000000000000000000000..7220c4cc4431518836137a4a9a15b890580cdb67 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/en_NZ.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ff_Adlm_NG.dat b/lib/python3.10/site-packages/babel/locale-data/ff_Adlm_NG.dat new file mode 100644 index 0000000000000000000000000000000000000000..a17d85c57ae003b64b27da1698e55b537897c284 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ff_Adlm_NG.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/fr_CH.dat b/lib/python3.10/site-packages/babel/locale-data/fr_CH.dat new file mode 100644 index 0000000000000000000000000000000000000000..fa5b7b4771fdc94797ff2cc4b94d5e5a97df1ee0 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/fr_CH.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ha_Arab.dat b/lib/python3.10/site-packages/babel/locale-data/ha_Arab.dat new file mode 100644 index 0000000000000000000000000000000000000000..1395d9e02350c637398027e0190dc42ca4d27758 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ha_Arab.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/jbo_001.dat b/lib/python3.10/site-packages/babel/locale-data/jbo_001.dat new file mode 100644 index 0000000000000000000000000000000000000000..dcc98aef622315e30a1d2f3a9114132cd6a5b98d Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/jbo_001.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ltg.dat b/lib/python3.10/site-packages/babel/locale-data/ltg.dat new file mode 100644 index 0000000000000000000000000000000000000000..8937b94340aaec75a9952957c4e9596d66f02937 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ltg.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/nds_NL.dat b/lib/python3.10/site-packages/babel/locale-data/nds_NL.dat new file mode 100644 index 0000000000000000000000000000000000000000..14b9b12306790de2097804d28e8e9ea2ab92740e Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/nds_NL.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/nmg_CM.dat b/lib/python3.10/site-packages/babel/locale-data/nmg_CM.dat new file mode 100644 index 0000000000000000000000000000000000000000..f675485dbffb6757f2c4c527c9265c6f9d234b72 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/nmg_CM.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/pis_SB.dat b/lib/python3.10/site-packages/babel/locale-data/pis_SB.dat new file mode 100644 index 0000000000000000000000000000000000000000..3b1f17cde15d79277dcda75fd0c662b1f5d9c440 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/pis_SB.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/prg_PL.dat b/lib/python3.10/site-packages/babel/locale-data/prg_PL.dat new file mode 100644 index 0000000000000000000000000000000000000000..7b1970517c0e7eda3f412ab77eae5a628c6b080a Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/prg_PL.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/sah_RU.dat b/lib/python3.10/site-packages/babel/locale-data/sah_RU.dat new file mode 100644 index 0000000000000000000000000000000000000000..44075f9fa05087862b23d993c4cbb3feee664763 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/sah_RU.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/tn_BW.dat b/lib/python3.10/site-packages/babel/locale-data/tn_BW.dat new file mode 100644 index 0000000000000000000000000000000000000000..5da0cc5d97fb4fcaf4813eb8bdc51db7a65e04d4 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/tn_BW.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/vai_Latn.dat b/lib/python3.10/site-packages/babel/locale-data/vai_Latn.dat new file mode 100644 index 0000000000000000000000000000000000000000..849c491d409bfc38d82a5a7374be6ace9f82c641 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/vai_Latn.dat differ diff --git a/lib/python3.10/site-packages/babel/localtime/__init__.py b/lib/python3.10/site-packages/babel/localtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..854c07496a10277f5df1b8b6d3d39eb6e851689e --- /dev/null +++ b/lib/python3.10/site-packages/babel/localtime/__init__.py @@ -0,0 +1,43 @@ +""" + babel.localtime + ~~~~~~~~~~~~~~~ + + Babel specific fork of tzlocal to determine the local timezone + of the system. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" + +import datetime +import sys + +if sys.platform == 'win32': + from babel.localtime._win32 import _get_localzone +else: + from babel.localtime._unix import _get_localzone + + +# TODO(3.0): the offset constants are not part of the public API +# and should be removed +from babel.localtime._fallback import ( + DSTDIFF, # noqa: F401 + DSTOFFSET, # noqa: F401 + STDOFFSET, # noqa: F401 + ZERO, # noqa: F401 + _FallbackLocalTimezone, +) + + +def get_localzone() -> datetime.tzinfo: + """Returns the current underlying local timezone object. + Generally this function does not need to be used, it's a + better idea to use the :data:`LOCALTZ` singleton instead. + """ + return _get_localzone() + + +try: + LOCALTZ = get_localzone() +except LookupError: + LOCALTZ = _FallbackLocalTimezone() diff --git a/lib/python3.10/site-packages/babel/localtime/_fallback.py b/lib/python3.10/site-packages/babel/localtime/_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..fab6867c3c67f28e1c5a9d44e1ab9f4aee308d99 --- /dev/null +++ b/lib/python3.10/site-packages/babel/localtime/_fallback.py @@ -0,0 +1,44 @@ +""" + babel.localtime._fallback + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Emulated fallback local timezone when all else fails. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" + +import datetime +import time + +STDOFFSET = datetime.timedelta(seconds=-time.timezone) +DSTOFFSET = datetime.timedelta(seconds=-time.altzone) if time.daylight else STDOFFSET + +DSTDIFF = DSTOFFSET - STDOFFSET +ZERO = datetime.timedelta(0) + + +class _FallbackLocalTimezone(datetime.tzinfo): + + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: + if self._isdst(dt): + return DSTOFFSET + else: + return STDOFFSET + + def dst(self, dt: datetime.datetime) -> datetime.timedelta: + if self._isdst(dt): + return DSTDIFF + else: + return ZERO + + def tzname(self, dt: datetime.datetime) -> str: + return time.tzname[self._isdst(dt)] + + def _isdst(self, dt: datetime.datetime) -> bool: + tt = (dt.year, dt.month, dt.day, + dt.hour, dt.minute, dt.second, + dt.weekday(), 0, -1) + stamp = time.mktime(tt) + tt = time.localtime(stamp) + return tt.tm_isdst > 0 diff --git a/lib/python3.10/site-packages/babel/localtime/_helpers.py b/lib/python3.10/site-packages/babel/localtime/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e67052c1fbdb7e88761fd6e8f08e97d54cb54e --- /dev/null +++ b/lib/python3.10/site-packages/babel/localtime/_helpers.py @@ -0,0 +1,57 @@ +try: + import pytz +except ModuleNotFoundError: + pytz = None + +try: + import zoneinfo +except ModuleNotFoundError: + zoneinfo = None + + +def _get_tzinfo(tzenv: str): + """Get the tzinfo from `zoneinfo` or `pytz` + + :param tzenv: timezone in the form of Continent/City + :return: tzinfo object or None if not found + """ + if pytz: + try: + return pytz.timezone(tzenv) + except pytz.UnknownTimeZoneError: + pass + else: + try: + return zoneinfo.ZoneInfo(tzenv) + except ValueError as ve: + # This is somewhat hacky, but since _validate_tzfile_path() doesn't + # raise a specific error type, we'll need to check the message to be + # one we know to be from that function. + # If so, we pretend it meant that the TZ didn't exist, for the benefit + # of `babel.localtime` catching the `LookupError` raised by + # `_get_tzinfo_or_raise()`. + # See https://github.com/python-babel/babel/issues/1092 + if str(ve).startswith("ZoneInfo keys "): + return None + except zoneinfo.ZoneInfoNotFoundError: + pass + + return None + + +def _get_tzinfo_or_raise(tzenv: str): + tzinfo = _get_tzinfo(tzenv) + if tzinfo is None: + raise LookupError( + f"Can not find timezone {tzenv}. \n" + "Timezone names are generally in the form `Continent/City`.", + ) + return tzinfo + + +def _get_tzinfo_from_file(tzfilename: str): + with open(tzfilename, 'rb') as tzfile: + if pytz: + return pytz.tzfile.build_tzinfo('local', tzfile) + else: + return zoneinfo.ZoneInfo.from_file(tzfile) diff --git a/lib/python3.10/site-packages/babel/localtime/_unix.py b/lib/python3.10/site-packages/babel/localtime/_unix.py new file mode 100644 index 0000000000000000000000000000000000000000..782a7d246ce2ca8cf2bb70857f670e11aeeacee0 --- /dev/null +++ b/lib/python3.10/site-packages/babel/localtime/_unix.py @@ -0,0 +1,104 @@ +import datetime +import os +import re + +from babel.localtime._helpers import ( + _get_tzinfo, + _get_tzinfo_from_file, + _get_tzinfo_or_raise, +) + + +def _tz_from_env(tzenv: str) -> datetime.tzinfo: + if tzenv[0] == ':': + tzenv = tzenv[1:] + + # TZ specifies a file + if os.path.exists(tzenv): + return _get_tzinfo_from_file(tzenv) + + # TZ specifies a zoneinfo zone. + return _get_tzinfo_or_raise(tzenv) + + +def _get_localzone(_root: str = '/') -> datetime.tzinfo: + """Tries to find the local timezone configuration. + This method prefers finding the timezone name and passing that to + zoneinfo or pytz, over passing in the localtime file, as in the later + case the zoneinfo name is unknown. + The parameter _root makes the function look for files like /etc/localtime + beneath the _root directory. This is primarily used by the tests. + In normal usage you call the function without parameters. + """ + + tzenv = os.environ.get('TZ') + if tzenv: + return _tz_from_env(tzenv) + + # This is actually a pretty reliable way to test for the local time + # zone on operating systems like OS X. On OS X especially this is the + # only one that actually works. + try: + link_dst = os.readlink('/etc/localtime') + except OSError: + pass + else: + pos = link_dst.find('/zoneinfo/') + if pos >= 0: + # On occasion, the `/etc/localtime` symlink has a double slash, e.g. + # "/usr/share/zoneinfo//UTC", which would make `zoneinfo.ZoneInfo` + # complain (no absolute paths allowed), and we'd end up returning + # `None` (as a fix for #1092). + # Instead, let's just "fix" the double slash symlink by stripping + # leading slashes before passing the assumed zone name forward. + zone_name = link_dst[pos + 10:].lstrip("/") + tzinfo = _get_tzinfo(zone_name) + if tzinfo is not None: + return tzinfo + + # Now look for distribution specific configuration files + # that contain the timezone name. + tzpath = os.path.join(_root, 'etc/timezone') + if os.path.exists(tzpath): + with open(tzpath, 'rb') as tzfile: + data = tzfile.read() + + # Issue #3 in tzlocal was that /etc/timezone was a zoneinfo file. + # That's a misconfiguration, but we need to handle it gracefully: + if data[:5] != b'TZif2': + etctz = data.strip().decode() + # Get rid of host definitions and comments: + if ' ' in etctz: + etctz, dummy = etctz.split(' ', 1) + if '#' in etctz: + etctz, dummy = etctz.split('#', 1) + + return _get_tzinfo_or_raise(etctz.replace(' ', '_')) + + # CentOS has a ZONE setting in /etc/sysconfig/clock, + # OpenSUSE has a TIMEZONE setting in /etc/sysconfig/clock and + # Gentoo has a TIMEZONE setting in /etc/conf.d/clock + # We look through these files for a timezone: + timezone_re = re.compile(r'\s*(TIME)?ZONE\s*=\s*"(?P.+)"') + + for filename in ('etc/sysconfig/clock', 'etc/conf.d/clock'): + tzpath = os.path.join(_root, filename) + if not os.path.exists(tzpath): + continue + with open(tzpath) as tzfile: + for line in tzfile: + match = timezone_re.match(line) + if match is not None: + # We found a timezone + etctz = match.group("etctz") + return _get_tzinfo_or_raise(etctz.replace(' ', '_')) + + # No explicit setting existed. Use localtime + for filename in ('etc/localtime', 'usr/local/etc/localtime'): + tzpath = os.path.join(_root, filename) + + if not os.path.exists(tzpath): + continue + return _get_tzinfo_from_file(tzpath) + + raise LookupError('Can not find any timezone configuration') diff --git a/lib/python3.10/site-packages/babel/localtime/_win32.py b/lib/python3.10/site-packages/babel/localtime/_win32.py new file mode 100644 index 0000000000000000000000000000000000000000..1a52567bc44cf0f5688cccffa869673b72b8cde7 --- /dev/null +++ b/lib/python3.10/site-packages/babel/localtime/_win32.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +try: + import winreg +except ImportError: + winreg = None + +import datetime +from typing import Any, Dict, cast + +from babel.core import get_global +from babel.localtime._helpers import _get_tzinfo_or_raise + +# When building the cldr data on windows this module gets imported. +# Because at that point there is no global.dat yet this call will +# fail. We want to catch it down in that case then and just assume +# the mapping was empty. +try: + tz_names: dict[str, str] = cast(Dict[str, str], get_global('windows_zone_mapping')) +except RuntimeError: + tz_names = {} + + +def valuestodict(key) -> dict[str, Any]: + """Convert a registry key's values to a dictionary.""" + dict = {} + size = winreg.QueryInfoKey(key)[1] + for i in range(size): + data = winreg.EnumValue(key, i) + dict[data[0]] = data[1] + return dict + + +def get_localzone_name() -> str: + # Windows is special. It has unique time zone names (in several + # meanings of the word) available, but unfortunately, they can be + # translated to the language of the operating system, so we need to + # do a backwards lookup, by going through all time zones and see which + # one matches. + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + + TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' + localtz = winreg.OpenKey(handle, TZLOCALKEYNAME) + keyvalues = valuestodict(localtz) + localtz.Close() + if 'TimeZoneKeyName' in keyvalues: + # Windows 7 (and Vista?) + + # For some reason this returns a string with loads of NUL bytes at + # least on some systems. I don't know if this is a bug somewhere, I + # just work around it. + tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0] + else: + # Windows 2000 or XP + + # This is the localized name: + tzwin = keyvalues['StandardName'] + + # Open the list of timezones to look up the real name: + TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' + tzkey = winreg.OpenKey(handle, TZKEYNAME) + + # Now, match this value to Time Zone information + tzkeyname = None + for i in range(winreg.QueryInfoKey(tzkey)[0]): + subkey = winreg.EnumKey(tzkey, i) + sub = winreg.OpenKey(tzkey, subkey) + data = valuestodict(sub) + sub.Close() + if data.get('Std', None) == tzwin: + tzkeyname = subkey + break + + tzkey.Close() + handle.Close() + + if tzkeyname is None: + raise LookupError('Can not find Windows timezone configuration') + + timezone = tz_names.get(tzkeyname) + if timezone is None: + # Nope, that didn't work. Try adding 'Standard Time', + # it seems to work a lot of times: + timezone = tz_names.get(f"{tzkeyname} Standard Time") + + # Return what we have. + if timezone is None: + raise LookupError(f"Can not find timezone {tzkeyname}") + + return timezone + + +def _get_localzone() -> datetime.tzinfo: + if winreg is None: + raise LookupError( + 'Runtime support not available') + + return _get_tzinfo_or_raise(get_localzone_name()) diff --git a/lib/python3.10/site-packages/babel/messages/__init__.py b/lib/python3.10/site-packages/babel/messages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca83faa97dd7e54f6f3681bb5af245da8687a107 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/__init__.py @@ -0,0 +1,21 @@ +""" + babel.messages + ~~~~~~~~~~~~~~ + + Support for ``gettext`` message catalogs. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" + +from babel.messages.catalog import ( + Catalog, + Message, + TranslationError, +) + +__all__ = [ + "Catalog", + "Message", + "TranslationError", +] diff --git a/lib/python3.10/site-packages/babel/messages/_compat.py b/lib/python3.10/site-packages/babel/messages/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..319b545f0327962b145858e20a89ceb2b641fb67 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/_compat.py @@ -0,0 +1,34 @@ +import sys +from functools import partial + + +def find_entrypoints(group_name: str): + """ + Find entrypoints of a given group using either `importlib.metadata` or the + older `pkg_resources` mechanism. + + Yields tuples of the entrypoint name and a callable function that will + load the actual entrypoint. + """ + if sys.version_info >= (3, 10): + # "Changed in version 3.10: importlib.metadata is no longer provisional." + try: + from importlib.metadata import entry_points + except ImportError: + pass + else: + eps = entry_points(group=group_name) + # Only do this if this implementation of `importlib.metadata` is + # modern enough to not return a dict. + if not isinstance(eps, dict): + for entry_point in eps: + yield (entry_point.name, entry_point.load) + return + + try: + from pkg_resources import working_set + except ImportError: + pass + else: + for entry_point in working_set.iter_entry_points(group_name): + yield (entry_point.name, partial(entry_point.load, require=True)) diff --git a/lib/python3.10/site-packages/babel/messages/catalog.py b/lib/python3.10/site-packages/babel/messages/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..f84a5bd1b389ff2b1f4fff4202722103dab54bb7 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/catalog.py @@ -0,0 +1,1000 @@ +""" + babel.messages.catalog + ~~~~~~~~~~~~~~~~~~~~~~ + + Data structures for message catalogs. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" +from __future__ import annotations + +import datetime +import re +from collections.abc import Iterable, Iterator +from copy import copy +from difflib import SequenceMatcher +from email import message_from_string +from heapq import nlargest +from string import Formatter +from typing import TYPE_CHECKING + +from babel import __version__ as VERSION +from babel.core import Locale, UnknownLocaleError +from babel.dates import format_datetime +from babel.messages.plurals import get_plural +from babel.util import LOCALTZ, FixedOffsetTimezone, _cmp, distinct + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + + _MessageID: TypeAlias = str | tuple[str, ...] | list[str] + +__all__ = [ + 'DEFAULT_HEADER', + 'PYTHON_FORMAT', + 'Catalog', + 'Message', + 'TranslationError', +] + + +def get_close_matches(word, possibilities, n=3, cutoff=0.6): + """A modified version of ``difflib.get_close_matches``. + + It just passes ``autojunk=False`` to the ``SequenceMatcher``, to work + around https://github.com/python/cpython/issues/90825. + """ + if not n > 0: # pragma: no cover + raise ValueError(f"n must be > 0: {n!r}") + if not 0.0 <= cutoff <= 1.0: # pragma: no cover + raise ValueError(f"cutoff must be in [0.0, 1.0]: {cutoff!r}") + result = [] + s = SequenceMatcher(autojunk=False) # only line changed from difflib.py + s.set_seq2(word) + for x in possibilities: + s.set_seq1(x) + if s.real_quick_ratio() >= cutoff and \ + s.quick_ratio() >= cutoff and \ + s.ratio() >= cutoff: + result.append((s.ratio(), x)) + + # Move the best scorers to head of list + result = nlargest(n, result) + # Strip scores for the best n matches + return [x for score, x in result] + + +PYTHON_FORMAT = re.compile(r''' + \% + (?:\(([\w]*)\))? + ( + [-#0\ +]?(?:\*|[\d]+)? + (?:\.(?:\*|[\d]+))? + [hlL]? + ) + ([diouxXeEfFgGcrs%]) +''', re.VERBOSE) + + +def _has_python_brace_format(string: str) -> bool: + if "{" not in string: + return False + fmt = Formatter() + try: + # `fmt.parse` returns 3-or-4-tuples of the form + # `(literal_text, field_name, format_spec, conversion)`; + # if `field_name` is set, this smells like brace format + field_name_seen = False + for t in fmt.parse(string): + if t[1] is not None: + field_name_seen = True + # We cannot break here, as we need to consume the whole string + # to ensure that it is a valid format string. + except ValueError: + return False + return field_name_seen + + +def _parse_datetime_header(value: str) -> datetime.datetime: + match = re.match(r'^(?P.*?)(?P[+-]\d{4})?$', value) + + dt = datetime.datetime.strptime(match.group('datetime'), '%Y-%m-%d %H:%M') + + # Separate the offset into a sign component, hours, and # minutes + tzoffset = match.group('tzoffset') + if tzoffset is not None: + plus_minus_s, rest = tzoffset[0], tzoffset[1:] + hours_offset_s, mins_offset_s = rest[:2], rest[2:] + + # Make them all integers + plus_minus = int(f"{plus_minus_s}1") + hours_offset = int(hours_offset_s) + mins_offset = int(mins_offset_s) + + # Calculate net offset + net_mins_offset = hours_offset * 60 + net_mins_offset += mins_offset + net_mins_offset *= plus_minus + + # Create an offset object + tzoffset = FixedOffsetTimezone(net_mins_offset) + + # Store the offset in a datetime object + dt = dt.replace(tzinfo=tzoffset) + + return dt + + +class Message: + """Representation of a single message in a catalog.""" + + def __init__( + self, + id: _MessageID, + string: _MessageID | None = '', + locations: Iterable[tuple[str, int]] = (), + flags: Iterable[str] = (), + auto_comments: Iterable[str] = (), + user_comments: Iterable[str] = (), + previous_id: _MessageID = (), + lineno: int | None = None, + context: str | None = None, + ) -> None: + """Create the message object. + + :param id: the message ID, or a ``(singular, plural)`` tuple for + pluralizable messages + :param string: the translated message string, or a + ``(singular, plural)`` tuple for pluralizable messages + :param locations: a sequence of ``(filename, lineno)`` tuples + :param flags: a set or sequence of flags + :param auto_comments: a sequence of automatic comments for the message + :param user_comments: a sequence of user comments for the message + :param previous_id: the previous message ID, or a ``(singular, plural)`` + tuple for pluralizable messages + :param lineno: the line number on which the msgid line was found in the + PO file, if any + :param context: the message context + """ + self.id = id + if not string and self.pluralizable: + string = ('', '') + self.string = string + self.locations = list(distinct(locations)) + self.flags = set(flags) + if id and self.python_format: + self.flags.add('python-format') + else: + self.flags.discard('python-format') + if id and self.python_brace_format: + self.flags.add('python-brace-format') + else: + self.flags.discard('python-brace-format') + self.auto_comments = list(distinct(auto_comments)) + self.user_comments = list(distinct(user_comments)) + if isinstance(previous_id, str): + self.previous_id = [previous_id] + else: + self.previous_id = list(previous_id) + self.lineno = lineno + self.context = context + + def __repr__(self) -> str: + return f"<{type(self).__name__} {self.id!r} (flags: {list(self.flags)!r})>" + + def __cmp__(self, other: object) -> int: + """Compare Messages, taking into account plural ids""" + def values_to_compare(obj): + if isinstance(obj, Message) and obj.pluralizable: + return obj.id[0], obj.context or '' + return obj.id, obj.context or '' + return _cmp(values_to_compare(self), values_to_compare(other)) + + def __gt__(self, other: object) -> bool: + return self.__cmp__(other) > 0 + + def __lt__(self, other: object) -> bool: + return self.__cmp__(other) < 0 + + def __ge__(self, other: object) -> bool: + return self.__cmp__(other) >= 0 + + def __le__(self, other: object) -> bool: + return self.__cmp__(other) <= 0 + + def __eq__(self, other: object) -> bool: + return self.__cmp__(other) == 0 + + def __ne__(self, other: object) -> bool: + return self.__cmp__(other) != 0 + + def is_identical(self, other: Message) -> bool: + """Checks whether messages are identical, taking into account all + properties. + """ + assert isinstance(other, Message) + return self.__dict__ == other.__dict__ + + def clone(self) -> Message: + return Message(*map(copy, (self.id, self.string, self.locations, + self.flags, self.auto_comments, + self.user_comments, self.previous_id, + self.lineno, self.context))) + + def check(self, catalog: Catalog | None = None) -> list[TranslationError]: + """Run various validation checks on the message. Some validations + are only performed if the catalog is provided. This method returns + a sequence of `TranslationError` objects. + + :rtype: ``iterator`` + :param catalog: A catalog instance that is passed to the checkers + :see: `Catalog.check` for a way to perform checks for all messages + in a catalog. + """ + from babel.messages.checkers import checkers + errors: list[TranslationError] = [] + for checker in checkers: + try: + checker(catalog, self) + except TranslationError as e: + errors.append(e) + return errors + + @property + def fuzzy(self) -> bool: + """Whether the translation is fuzzy. + + >>> Message('foo').fuzzy + False + >>> msg = Message('foo', 'foo', flags=['fuzzy']) + >>> msg.fuzzy + True + >>> msg + + + :type: `bool`""" + return 'fuzzy' in self.flags + + @property + def pluralizable(self) -> bool: + """Whether the message is plurizable. + + >>> Message('foo').pluralizable + False + >>> Message(('foo', 'bar')).pluralizable + True + + :type: `bool`""" + return isinstance(self.id, (list, tuple)) + + @property + def python_format(self) -> bool: + """Whether the message contains Python-style parameters. + + >>> Message('foo %(name)s bar').python_format + True + >>> Message(('foo %(name)s', 'foo %(name)s')).python_format + True + + :type: `bool`""" + ids = self.id + if not isinstance(ids, (list, tuple)): + ids = [ids] + return any(PYTHON_FORMAT.search(id) for id in ids) + + @property + def python_brace_format(self) -> bool: + """Whether the message contains Python f-string parameters. + + >>> Message('Hello, {name}!').python_brace_format + True + >>> Message(('One apple', '{count} apples')).python_brace_format + True + + :type: `bool`""" + ids = self.id + if not isinstance(ids, (list, tuple)): + ids = [ids] + return any(_has_python_brace_format(id) for id in ids) + + +class TranslationError(Exception): + """Exception thrown by translation checkers when invalid message + translations are encountered.""" + + +DEFAULT_HEADER = """\ +# Translations template for PROJECT. +# Copyright (C) YEAR ORGANIZATION +# This file is distributed under the same license as the PROJECT project. +# FIRST AUTHOR , YEAR. +#""" + + +def parse_separated_header(value: str) -> dict[str, str]: + # Adapted from https://peps.python.org/pep-0594/#cgi + from email.message import Message + m = Message() + m['content-type'] = value + return dict(m.get_params()) + + +def _force_text(s: str | bytes, encoding: str = 'utf-8', errors: str = 'strict') -> str: + if isinstance(s, str): + return s + if isinstance(s, bytes): + return s.decode(encoding, errors) + return str(s) + + +class Catalog: + """Representation of a message catalog.""" + + def __init__( + self, + locale: Locale | str | None = None, + domain: str | None = None, + header_comment: str | None = DEFAULT_HEADER, + project: str | None = None, + version: str | None = None, + copyright_holder: str | None = None, + msgid_bugs_address: str | None = None, + creation_date: datetime.datetime | str | None = None, + revision_date: datetime.datetime | datetime.time | float | str | None = None, + last_translator: str | None = None, + language_team: str | None = None, + charset: str | None = None, + fuzzy: bool = True, + ) -> None: + """Initialize the catalog object. + + :param locale: the locale identifier or `Locale` object, or `None` + if the catalog is not bound to a locale (which basically + means it's a template) + :param domain: the message domain + :param header_comment: the header comment as string, or `None` for the + default header + :param project: the project's name + :param version: the project's version + :param copyright_holder: the copyright holder of the catalog + :param msgid_bugs_address: the email address or URL to submit bug + reports to + :param creation_date: the date the catalog was created + :param revision_date: the date the catalog was revised + :param last_translator: the name and email of the last translator + :param language_team: the name and email of the language team + :param charset: the encoding to use in the output (defaults to utf-8) + :param fuzzy: the fuzzy bit on the catalog header + """ + self.domain = domain + self.locale = locale + self._header_comment = header_comment + self._messages: dict[str | tuple[str, str], Message] = {} + + self.project = project or 'PROJECT' + self.version = version or 'VERSION' + self.copyright_holder = copyright_holder or 'ORGANIZATION' + self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS' + + self.last_translator = last_translator or 'FULL NAME ' + """Name and email address of the last translator.""" + self.language_team = language_team or 'LANGUAGE ' + """Name and email address of the language team.""" + + self.charset = charset or 'utf-8' + + if creation_date is None: + creation_date = datetime.datetime.now(LOCALTZ) + elif isinstance(creation_date, datetime.datetime) and not creation_date.tzinfo: + creation_date = creation_date.replace(tzinfo=LOCALTZ) + self.creation_date = creation_date + if revision_date is None: + revision_date = 'YEAR-MO-DA HO:MI+ZONE' + elif isinstance(revision_date, datetime.datetime) and not revision_date.tzinfo: + revision_date = revision_date.replace(tzinfo=LOCALTZ) + self.revision_date = revision_date + self.fuzzy = fuzzy + + # Dictionary of obsolete messages + self.obsolete: dict[str | tuple[str, str], Message] = {} + self._num_plurals = None + self._plural_expr = None + + def _set_locale(self, locale: Locale | str | None) -> None: + if locale is None: + self._locale_identifier = None + self._locale = None + return + + if isinstance(locale, Locale): + self._locale_identifier = str(locale) + self._locale = locale + return + + if isinstance(locale, str): + self._locale_identifier = str(locale) + try: + self._locale = Locale.parse(locale) + except UnknownLocaleError: + self._locale = None + return + + raise TypeError(f"`locale` must be a Locale, a locale identifier string, or None; got {locale!r}") + + def _get_locale(self) -> Locale | None: + return self._locale + + def _get_locale_identifier(self) -> str | None: + return self._locale_identifier + + locale = property(_get_locale, _set_locale) + locale_identifier = property(_get_locale_identifier) + + def _get_header_comment(self) -> str: + comment = self._header_comment + year = datetime.datetime.now(LOCALTZ).strftime('%Y') + if hasattr(self.revision_date, 'strftime'): + year = self.revision_date.strftime('%Y') + comment = comment.replace('PROJECT', self.project) \ + .replace('VERSION', self.version) \ + .replace('YEAR', year) \ + .replace('ORGANIZATION', self.copyright_holder) + locale_name = (self.locale.english_name if self.locale else self.locale_identifier) + if locale_name: + comment = comment.replace("Translations template", f"{locale_name} translations") + return comment + + def _set_header_comment(self, string: str | None) -> None: + self._header_comment = string + + header_comment = property(_get_header_comment, _set_header_comment, doc="""\ + The header comment for the catalog. + + >>> catalog = Catalog(project='Foobar', version='1.0', + ... copyright_holder='Foo Company') + >>> print(catalog.header_comment) #doctest: +ELLIPSIS + # Translations template for Foobar. + # Copyright (C) ... Foo Company + # This file is distributed under the same license as the Foobar project. + # FIRST AUTHOR , .... + # + + The header can also be set from a string. Any known upper-case variables + will be replaced when the header is retrieved again: + + >>> catalog = Catalog(project='Foobar', version='1.0', + ... copyright_holder='Foo Company') + >>> catalog.header_comment = '''\\ + ... # The POT for my really cool PROJECT project. + ... # Copyright (C) 1990-2003 ORGANIZATION + ... # This file is distributed under the same license as the PROJECT + ... # project. + ... #''' + >>> print(catalog.header_comment) + # The POT for my really cool Foobar project. + # Copyright (C) 1990-2003 Foo Company + # This file is distributed under the same license as the Foobar + # project. + # + + :type: `unicode` + """) + + def _get_mime_headers(self) -> list[tuple[str, str]]: + if isinstance(self.revision_date, (datetime.datetime, datetime.time, int, float)): + revision_date = format_datetime(self.revision_date, 'yyyy-MM-dd HH:mmZ', locale='en') + else: + revision_date = self.revision_date + + language_team = self.language_team + if self.locale_identifier and 'LANGUAGE' in language_team: + language_team = language_team.replace('LANGUAGE', str(self.locale_identifier)) + + headers: list[tuple[str, str]] = [ + ("Project-Id-Version", f"{self.project} {self.version}"), + ('Report-Msgid-Bugs-To', self.msgid_bugs_address), + ('POT-Creation-Date', format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ', locale='en')), + ('PO-Revision-Date', revision_date), + ('Last-Translator', self.last_translator), + ] + if self.locale_identifier: + headers.append(('Language', str(self.locale_identifier))) + headers.append(('Language-Team', language_team)) + if self.locale is not None: + headers.append(('Plural-Forms', self.plural_forms)) + headers += [ + ('MIME-Version', '1.0'), + ("Content-Type", f"text/plain; charset={self.charset}"), + ('Content-Transfer-Encoding', '8bit'), + ("Generated-By", f"Babel {VERSION}\n"), + ] + return headers + + def _set_mime_headers(self, headers: Iterable[tuple[str, str]]) -> None: + for name, value in headers: + name = _force_text(name.lower(), encoding=self.charset) + value = _force_text(value, encoding=self.charset) + if name == 'project-id-version': + parts = value.split(' ') + self.project = ' '.join(parts[:-1]) + self.version = parts[-1] + elif name == 'report-msgid-bugs-to': + self.msgid_bugs_address = value + elif name == 'last-translator': + self.last_translator = value + elif name == 'language': + value = value.replace('-', '_') + # The `or None` makes sure that the locale is set to None + # if the header's value is an empty string, which is what + # some tools generate (instead of eliding the empty Language + # header altogether). + self._set_locale(value or None) + elif name == 'language-team': + self.language_team = value + elif name == 'content-type': + params = parse_separated_header(value) + if 'charset' in params: + self.charset = params['charset'].lower() + elif name == 'plural-forms': + params = parse_separated_header(f" ;{value}") + self._num_plurals = int(params.get('nplurals', 2)) + self._plural_expr = params.get('plural', '(n != 1)') + elif name == 'pot-creation-date': + self.creation_date = _parse_datetime_header(value) + elif name == 'po-revision-date': + # Keep the value if it's not the default one + if 'YEAR' not in value: + self.revision_date = _parse_datetime_header(value) + + mime_headers = property(_get_mime_headers, _set_mime_headers, doc="""\ + The MIME headers of the catalog, used for the special ``msgid ""`` entry. + + The behavior of this property changes slightly depending on whether a locale + is set or not, the latter indicating that the catalog is actually a template + for actual translations. + + Here's an example of the output for such a catalog template: + + >>> from babel.dates import UTC + >>> from datetime import datetime + >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC) + >>> catalog = Catalog(project='Foobar', version='1.0', + ... creation_date=created) + >>> for name, value in catalog.mime_headers: + ... print('%s: %s' % (name, value)) + Project-Id-Version: Foobar 1.0 + Report-Msgid-Bugs-To: EMAIL@ADDRESS + POT-Creation-Date: 1990-04-01 15:30+0000 + PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE + Last-Translator: FULL NAME + Language-Team: LANGUAGE + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: 8bit + Generated-By: Babel ... + + And here's an example of the output when the locale is set: + + >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC) + >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0', + ... creation_date=created, revision_date=revised, + ... last_translator='John Doe ', + ... language_team='de_DE ') + >>> for name, value in catalog.mime_headers: + ... print('%s: %s' % (name, value)) + Project-Id-Version: Foobar 1.0 + Report-Msgid-Bugs-To: EMAIL@ADDRESS + POT-Creation-Date: 1990-04-01 15:30+0000 + PO-Revision-Date: 1990-08-03 12:00+0000 + Last-Translator: John Doe + Language: de_DE + Language-Team: de_DE + Plural-Forms: nplurals=2; plural=(n != 1); + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: 8bit + Generated-By: Babel ... + + :type: `list` + """) + + @property + def num_plurals(self) -> int: + """The number of plurals used by the catalog or locale. + + >>> Catalog(locale='en').num_plurals + 2 + >>> Catalog(locale='ga').num_plurals + 5 + + :type: `int`""" + if self._num_plurals is None: + num = 2 + if self.locale: + num = get_plural(self.locale)[0] + self._num_plurals = num + return self._num_plurals + + @property + def plural_expr(self) -> str: + """The plural expression used by the catalog or locale. + + >>> Catalog(locale='en').plural_expr + '(n != 1)' + >>> Catalog(locale='ga').plural_expr + '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)' + >>> Catalog(locale='ding').plural_expr # unknown locale + '(n != 1)' + + :type: `str`""" + if self._plural_expr is None: + expr = '(n != 1)' + if self.locale: + expr = get_plural(self.locale)[1] + self._plural_expr = expr + return self._plural_expr + + @property + def plural_forms(self) -> str: + """Return the plural forms declaration for the locale. + + >>> Catalog(locale='en').plural_forms + 'nplurals=2; plural=(n != 1);' + >>> Catalog(locale='pt_BR').plural_forms + 'nplurals=2; plural=(n > 1);' + + :type: `str`""" + return f"nplurals={self.num_plurals}; plural={self.plural_expr};" + + def __contains__(self, id: _MessageID) -> bool: + """Return whether the catalog has a message with the specified ID.""" + return self._key_for(id) in self._messages + + def __len__(self) -> int: + """The number of messages in the catalog. + + This does not include the special ``msgid ""`` entry.""" + return len(self._messages) + + def __iter__(self) -> Iterator[Message]: + """Iterates through all the entries in the catalog, in the order they + were added, yielding a `Message` object for every entry. + + :rtype: ``iterator``""" + buf = [] + for name, value in self.mime_headers: + buf.append(f"{name}: {value}") + flags = set() + if self.fuzzy: + flags |= {'fuzzy'} + yield Message('', '\n'.join(buf), flags=flags) + for key in self._messages: + yield self._messages[key] + + def __repr__(self) -> str: + locale = '' + if self.locale: + locale = f" {self.locale}" + return f"<{type(self).__name__} {self.domain!r}{locale}>" + + def __delitem__(self, id: _MessageID) -> None: + """Delete the message with the specified ID.""" + self.delete(id) + + def __getitem__(self, id: _MessageID) -> Message: + """Return the message with the specified ID. + + :param id: the message ID + """ + return self.get(id) + + def __setitem__(self, id: _MessageID, message: Message) -> None: + """Add or update the message with the specified ID. + + >>> catalog = Catalog() + >>> catalog[u'foo'] = Message(u'foo') + >>> catalog[u'foo'] + + + If a message with that ID is already in the catalog, it is updated + to include the locations and flags of the new message. + + >>> catalog = Catalog() + >>> catalog[u'foo'] = Message(u'foo', locations=[('main.py', 1)]) + >>> catalog[u'foo'].locations + [('main.py', 1)] + >>> catalog[u'foo'] = Message(u'foo', locations=[('utils.py', 5)]) + >>> catalog[u'foo'].locations + [('main.py', 1), ('utils.py', 5)] + + :param id: the message ID + :param message: the `Message` object + """ + assert isinstance(message, Message), 'expected a Message object' + key = self._key_for(id, message.context) + current = self._messages.get(key) + if current: + if message.pluralizable and not current.pluralizable: + # The new message adds pluralization + current.id = message.id + current.string = message.string + current.locations = list(distinct(current.locations + + message.locations)) + current.auto_comments = list(distinct(current.auto_comments + + message.auto_comments)) + current.user_comments = list(distinct(current.user_comments + + message.user_comments)) + current.flags |= message.flags + elif id == '': + # special treatment for the header message + self.mime_headers = message_from_string(message.string).items() + self.header_comment = "\n".join([f"# {c}".rstrip() for c in message.user_comments]) + self.fuzzy = message.fuzzy + else: + if isinstance(id, (list, tuple)): + assert isinstance(message.string, (list, tuple)), \ + f"Expected sequence but got {type(message.string)}" + self._messages[key] = message + + def add( + self, + id: _MessageID, + string: _MessageID | None = None, + locations: Iterable[tuple[str, int]] = (), + flags: Iterable[str] = (), + auto_comments: Iterable[str] = (), + user_comments: Iterable[str] = (), + previous_id: _MessageID = (), + lineno: int | None = None, + context: str | None = None, + ) -> Message: + """Add or update the message with the specified ID. + + >>> catalog = Catalog() + >>> catalog.add(u'foo') + + >>> catalog[u'foo'] + + + This method simply constructs a `Message` object with the given + arguments and invokes `__setitem__` with that object. + + :param id: the message ID, or a ``(singular, plural)`` tuple for + pluralizable messages + :param string: the translated message string, or a + ``(singular, plural)`` tuple for pluralizable messages + :param locations: a sequence of ``(filename, lineno)`` tuples + :param flags: a set or sequence of flags + :param auto_comments: a sequence of automatic comments + :param user_comments: a sequence of user comments + :param previous_id: the previous message ID, or a ``(singular, plural)`` + tuple for pluralizable messages + :param lineno: the line number on which the msgid line was found in the + PO file, if any + :param context: the message context + """ + message = Message(id, string, list(locations), flags, auto_comments, + user_comments, previous_id, lineno=lineno, + context=context) + self[id] = message + return message + + def check(self) -> Iterable[tuple[Message, list[TranslationError]]]: + """Run various validation checks on the translations in the catalog. + + For every message which fails validation, this method yield a + ``(message, errors)`` tuple, where ``message`` is the `Message` object + and ``errors`` is a sequence of `TranslationError` objects. + + :rtype: ``generator`` of ``(message, errors)`` + """ + for message in self._messages.values(): + errors = message.check(catalog=self) + if errors: + yield message, errors + + def get(self, id: _MessageID, context: str | None = None) -> Message | None: + """Return the message with the specified ID and context. + + :param id: the message ID + :param context: the message context, or ``None`` for no context + """ + return self._messages.get(self._key_for(id, context)) + + def delete(self, id: _MessageID, context: str | None = None) -> None: + """Delete the message with the specified ID and context. + + :param id: the message ID + :param context: the message context, or ``None`` for no context + """ + key = self._key_for(id, context) + if key in self._messages: + del self._messages[key] + + def update( + self, + template: Catalog, + no_fuzzy_matching: bool = False, + update_header_comment: bool = False, + keep_user_comments: bool = True, + update_creation_date: bool = True, + ) -> None: + """Update the catalog based on the given template catalog. + + >>> from babel.messages import Catalog + >>> template = Catalog() + >>> template.add('green', locations=[('main.py', 99)]) + + >>> template.add('blue', locations=[('main.py', 100)]) + + >>> template.add(('salad', 'salads'), locations=[('util.py', 42)]) + + >>> catalog = Catalog(locale='de_DE') + >>> catalog.add('blue', u'blau', locations=[('main.py', 98)]) + + >>> catalog.add('head', u'Kopf', locations=[('util.py', 33)]) + + >>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'), + ... locations=[('util.py', 38)]) + + + >>> catalog.update(template) + >>> len(catalog) + 3 + + >>> msg1 = catalog['green'] + >>> msg1.string + >>> msg1.locations + [('main.py', 99)] + + >>> msg2 = catalog['blue'] + >>> msg2.string + u'blau' + >>> msg2.locations + [('main.py', 100)] + + >>> msg3 = catalog['salad'] + >>> msg3.string + (u'Salat', u'Salate') + >>> msg3.locations + [('util.py', 42)] + + Messages that are in the catalog but not in the template are removed + from the main collection, but can still be accessed via the `obsolete` + member: + + >>> 'head' in catalog + False + >>> list(catalog.obsolete.values()) + [] + + :param template: the reference catalog, usually read from a POT file + :param no_fuzzy_matching: whether to use fuzzy matching of message IDs + :param update_header_comment: whether to copy the header comment from the template + :param keep_user_comments: whether to keep user comments from the old catalog + :param update_creation_date: whether to copy the creation date from the template + """ + messages = self._messages + remaining = messages.copy() + self._messages = {} + + # Prepare for fuzzy matching + fuzzy_candidates = {} + if not no_fuzzy_matching: + for msgid in messages: + if msgid and messages[msgid].string: + key = self._key_for(msgid) + ctxt = messages[msgid].context + fuzzy_candidates[self._to_fuzzy_match_key(key)] = (key, ctxt) + fuzzy_matches = set() + + def _merge(message: Message, oldkey: tuple[str, str] | str, newkey: tuple[str, str] | str) -> None: + message = message.clone() + fuzzy = False + if oldkey != newkey: + fuzzy = True + fuzzy_matches.add(oldkey) + oldmsg = messages.get(oldkey) + assert oldmsg is not None + if isinstance(oldmsg.id, str): + message.previous_id = [oldmsg.id] + else: + message.previous_id = list(oldmsg.id) + else: + oldmsg = remaining.pop(oldkey, None) + assert oldmsg is not None + message.string = oldmsg.string + + if keep_user_comments: + message.user_comments = list(distinct(oldmsg.user_comments)) + + if isinstance(message.id, (list, tuple)): + if not isinstance(message.string, (list, tuple)): + fuzzy = True + message.string = tuple( + [message.string] + ([''] * (len(message.id) - 1)), + ) + elif len(message.string) != self.num_plurals: + fuzzy = True + message.string = tuple(message.string[:len(oldmsg.string)]) + elif isinstance(message.string, (list, tuple)): + fuzzy = True + message.string = message.string[0] + message.flags |= oldmsg.flags + if fuzzy: + message.flags |= {'fuzzy'} + self[message.id] = message + + for message in template: + if message.id: + key = self._key_for(message.id, message.context) + if key in messages: + _merge(message, key, key) + else: + if not no_fuzzy_matching: + # do some fuzzy matching with difflib + matches = get_close_matches( + self._to_fuzzy_match_key(key), + fuzzy_candidates.keys(), + 1, + ) + if matches: + modified_key = matches[0] + newkey, newctxt = fuzzy_candidates[modified_key] + if newctxt is not None: + newkey = newkey, newctxt + _merge(message, newkey, key) + continue + + self[message.id] = message + + for msgid in remaining: + if no_fuzzy_matching or msgid not in fuzzy_matches: + self.obsolete[msgid] = remaining[msgid] + + if update_header_comment: + # Allow the updated catalog's header to be rewritten based on the + # template's header + self.header_comment = template.header_comment + + # Make updated catalog's POT-Creation-Date equal to the template + # used to update the catalog + if update_creation_date: + self.creation_date = template.creation_date + + def _to_fuzzy_match_key(self, key: tuple[str, str] | str) -> str: + """Converts a message key to a string suitable for fuzzy matching.""" + if isinstance(key, tuple): + matchkey = key[0] # just the msgid, no context + else: + matchkey = key + return matchkey.lower().strip() + + def _key_for(self, id: _MessageID, context: str | None = None) -> tuple[str, str] | str: + """The key for a message is just the singular ID even for pluralizable + messages, but is a ``(msgid, msgctxt)`` tuple for context-specific + messages. + """ + key = id + if isinstance(key, (list, tuple)): + key = id[0] + if context is not None: + key = (key, context) + return key + + def is_identical(self, other: Catalog) -> bool: + """Checks if catalogs are identical, taking into account messages and + headers. + """ + assert isinstance(other, Catalog) + for key in self._messages.keys() | other._messages.keys(): + message_1 = self.get(key) + message_2 = other.get(key) + if ( + message_1 is None + or message_2 is None + or not message_1.is_identical(message_2) + ): + return False + return dict(self.mime_headers) == dict(other.mime_headers) diff --git a/lib/python3.10/site-packages/babel/messages/checkers.py b/lib/python3.10/site-packages/babel/messages/checkers.py new file mode 100644 index 0000000000000000000000000000000000000000..df7c3ca73bcbdf160c7e7aeb186dcc28e43eb154 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/checkers.py @@ -0,0 +1,168 @@ +""" + babel.messages.checkers + ~~~~~~~~~~~~~~~~~~~~~~~ + + Various routines that help with validation of translations. + + :since: version 0.9 + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" +from __future__ import annotations + +from collections.abc import Callable + +from babel.messages.catalog import PYTHON_FORMAT, Catalog, Message, TranslationError + +#: list of format chars that are compatible to each other +_string_format_compatibilities = [ + {'i', 'd', 'u'}, + {'x', 'X'}, + {'f', 'F', 'g', 'G'}, +] + + +def num_plurals(catalog: Catalog | None, message: Message) -> None: + """Verify the number of plurals in the translation.""" + if not message.pluralizable: + if not isinstance(message.string, str): + raise TranslationError("Found plural forms for non-pluralizable " + "message") + return + + # skip further tests if no catalog is provided. + elif catalog is None: + return + + msgstrs = message.string + if not isinstance(msgstrs, (list, tuple)): + msgstrs = (msgstrs,) + if len(msgstrs) != catalog.num_plurals: + raise TranslationError("Wrong number of plural forms (expected %d)" % + catalog.num_plurals) + + +def python_format(catalog: Catalog | None, message: Message) -> None: + """Verify the format string placeholders in the translation.""" + if 'python-format' not in message.flags: + return + msgids = message.id + if not isinstance(msgids, (list, tuple)): + msgids = (msgids,) + msgstrs = message.string + if not isinstance(msgstrs, (list, tuple)): + msgstrs = (msgstrs,) + + for msgid, msgstr in zip(msgids, msgstrs): + if msgstr: + _validate_format(msgid, msgstr) + + +def _validate_format(format: str, alternative: str) -> None: + """Test format string `alternative` against `format`. `format` can be the + msgid of a message and `alternative` one of the `msgstr`\\s. The two + arguments are not interchangeable as `alternative` may contain less + placeholders if `format` uses named placeholders. + + If the string formatting of `alternative` is compatible to `format` the + function returns `None`, otherwise a `TranslationError` is raised. + + Examples for compatible format strings: + + >>> _validate_format('Hello %s!', 'Hallo %s!') + >>> _validate_format('Hello %i!', 'Hallo %d!') + + Example for an incompatible format strings: + + >>> _validate_format('Hello %(name)s!', 'Hallo %s!') + Traceback (most recent call last): + ... + TranslationError: the format strings are of different kinds + + This function is used by the `python_format` checker. + + :param format: The original format string + :param alternative: The alternative format string that should be checked + against format + :raises TranslationError: on formatting errors + """ + + def _parse(string: str) -> list[tuple[str, str]]: + result: list[tuple[str, str]] = [] + for match in PYTHON_FORMAT.finditer(string): + name, format, typechar = match.groups() + if typechar == '%' and name is None: + continue + result.append((name, str(typechar))) + return result + + def _compatible(a: str, b: str) -> bool: + if a == b: + return True + for set in _string_format_compatibilities: + if a in set and b in set: + return True + return False + + def _check_positional(results: list[tuple[str, str]]) -> bool: + positional = None + for name, _char in results: + if positional is None: + positional = name is None + else: + if (name is None) != positional: + raise TranslationError('format string mixes positional ' + 'and named placeholders') + return bool(positional) + + a, b = map(_parse, (format, alternative)) + + if not a: + return + + # now check if both strings are positional or named + a_positional, b_positional = map(_check_positional, (a, b)) + if a_positional and not b_positional and not b: + raise TranslationError('placeholders are incompatible') + elif a_positional != b_positional: + raise TranslationError('the format strings are of different kinds') + + # if we are operating on positional strings both must have the + # same number of format chars and those must be compatible + if a_positional: + if len(a) != len(b): + raise TranslationError('positional format placeholders are ' + 'unbalanced') + for idx, ((_, first), (_, second)) in enumerate(zip(a, b)): + if not _compatible(first, second): + raise TranslationError('incompatible format for placeholder ' + '%d: %r and %r are not compatible' % + (idx + 1, first, second)) + + # otherwise the second string must not have names the first one + # doesn't have and the types of those included must be compatible + else: + type_map = dict(a) + for name, typechar in b: + if name not in type_map: + raise TranslationError(f'unknown named placeholder {name!r}') + elif not _compatible(typechar, type_map[name]): + raise TranslationError( + f'incompatible format for placeholder {name!r}: ' + f'{typechar!r} and {type_map[name]!r} are not compatible', + ) + + +def _find_checkers() -> list[Callable[[Catalog | None, Message], object]]: + from babel.messages._compat import find_entrypoints + checkers: list[Callable[[Catalog | None, Message], object]] = [] + checkers.extend(load() for (name, load) in find_entrypoints('babel.checkers')) + if len(checkers) == 0: + # if entrypoints are not available or no usable egg-info was found + # (see #230), just resort to hard-coded checkers + return [num_plurals, python_format] + return checkers + + +checkers: list[Callable[[Catalog | None, Message], object]] = _find_checkers() diff --git a/lib/python3.10/site-packages/babel/messages/extract.py b/lib/python3.10/site-packages/babel/messages/extract.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4230f617b7951e8efc11291b85e7ef7be143b4 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/extract.py @@ -0,0 +1,852 @@ +""" + babel.messages.extract + ~~~~~~~~~~~~~~~~~~~~~~ + + Basic infrastructure for extracting localizable messages from source files. + + This module defines an extensible system for collecting localizable message + strings from a variety of sources. A native extractor for Python source + files is builtin, extractors for other sources can be added using very + simple plugins. + + The main entry points into the extraction functionality are the functions + `extract_from_dir` and `extract_from_file`. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" +from __future__ import annotations + +import ast +import io +import os +import sys +import tokenize +from collections.abc import ( + Callable, + Collection, + Generator, + Iterable, + Mapping, + MutableSequence, +) +from functools import lru_cache +from os.path import relpath +from textwrap import dedent +from tokenize import COMMENT, NAME, NL, OP, STRING, generate_tokens +from typing import TYPE_CHECKING, Any, TypedDict + +from babel.messages._compat import find_entrypoints +from babel.util import parse_encoding, parse_future_flags, pathmatch + +if TYPE_CHECKING: + from typing import IO, Final, Protocol + + from _typeshed import SupportsItems, SupportsRead, SupportsReadline + from typing_extensions import TypeAlias + + class _PyOptions(TypedDict, total=False): + encoding: str + + class _JSOptions(TypedDict, total=False): + encoding: str + jsx: bool + template_string: bool + parse_template_string: bool + + class _FileObj(SupportsRead[bytes], SupportsReadline[bytes], Protocol): + def seek(self, __offset: int, __whence: int = ...) -> int: ... + def tell(self) -> int: ... + + _SimpleKeyword: TypeAlias = tuple[int | tuple[int, int] | tuple[int, str], ...] | None + _Keyword: TypeAlias = dict[int | None, _SimpleKeyword] | _SimpleKeyword + + # 5-tuple of (filename, lineno, messages, comments, context) + _FileExtractionResult: TypeAlias = tuple[str, int, str | tuple[str, ...], list[str], str | None] + + # 4-tuple of (lineno, message, comments, context) + _ExtractionResult: TypeAlias = tuple[int, str | tuple[str, ...], list[str], str | None] + + # Required arguments: fileobj, keywords, comment_tags, options + # Return value: Iterable of (lineno, message, comments, context) + _CallableExtractionMethod: TypeAlias = Callable[ + [_FileObj | IO[bytes], Mapping[str, _Keyword], Collection[str], Mapping[str, Any]], + Iterable[_ExtractionResult], + ] + + _ExtractionMethod: TypeAlias = _CallableExtractionMethod | str + +GROUP_NAME: Final[str] = 'babel.extractors' + +DEFAULT_KEYWORDS: dict[str, _Keyword] = { + '_': None, + 'gettext': None, + 'ngettext': (1, 2), + 'ugettext': None, + 'ungettext': (1, 2), + 'dgettext': (2,), + 'dngettext': (2, 3), + 'N_': None, + 'pgettext': ((1, 'c'), 2), + 'npgettext': ((1, 'c'), 2, 3), +} + +DEFAULT_MAPPING: list[tuple[str, str]] = [('**.py', 'python')] + +# New tokens in Python 3.12, or None on older versions +FSTRING_START = getattr(tokenize, "FSTRING_START", None) +FSTRING_MIDDLE = getattr(tokenize, "FSTRING_MIDDLE", None) +FSTRING_END = getattr(tokenize, "FSTRING_END", None) + + +def _strip_comment_tags(comments: MutableSequence[str], tags: Iterable[str]): + """Helper function for `extract` that strips comment tags from strings + in a list of comment lines. This functions operates in-place. + """ + def _strip(line: str): + for tag in tags: + if line.startswith(tag): + return line[len(tag):].strip() + return line + comments[:] = map(_strip, comments) + + +def default_directory_filter(dirpath: str | os.PathLike[str]) -> bool: + subdir = os.path.basename(dirpath) + # Legacy default behavior: ignore dot and underscore directories + return not (subdir.startswith('.') or subdir.startswith('_')) + + +def extract_from_dir( + dirname: str | os.PathLike[str] | None = None, + method_map: Iterable[tuple[str, str]] = DEFAULT_MAPPING, + options_map: SupportsItems[str, dict[str, Any]] | None = None, + keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS, + comment_tags: Collection[str] = (), + callback: Callable[[str, str, dict[str, Any]], object] | None = None, + strip_comment_tags: bool = False, + directory_filter: Callable[[str], bool] | None = None, +) -> Generator[_FileExtractionResult, None, None]: + """Extract messages from any source files found in the given directory. + + This function generates tuples of the form ``(filename, lineno, message, + comments, context)``. + + Which extraction method is used per file is determined by the `method_map` + parameter, which maps extended glob patterns to extraction method names. + For example, the following is the default mapping: + + >>> method_map = [ + ... ('**.py', 'python') + ... ] + + This basically says that files with the filename extension ".py" at any + level inside the directory should be processed by the "python" extraction + method. Files that don't match any of the mapping patterns are ignored. See + the documentation of the `pathmatch` function for details on the pattern + syntax. + + The following extended mapping would also use the "genshi" extraction + method on any file in "templates" subdirectory: + + >>> method_map = [ + ... ('**/templates/**.*', 'genshi'), + ... ('**.py', 'python') + ... ] + + The dictionary provided by the optional `options_map` parameter augments + these mappings. It uses extended glob patterns as keys, and the values are + dictionaries mapping options names to option values (both strings). + + The glob patterns of the `options_map` do not necessarily need to be the + same as those used in the method mapping. For example, while all files in + the ``templates`` folders in an application may be Genshi applications, the + options for those files may differ based on extension: + + >>> options_map = { + ... '**/templates/**.txt': { + ... 'template_class': 'genshi.template:TextTemplate', + ... 'encoding': 'latin-1' + ... }, + ... '**/templates/**.html': { + ... 'include_attrs': '' + ... } + ... } + + :param dirname: the path to the directory to extract messages from. If + not given the current working directory is used. + :param method_map: a list of ``(pattern, method)`` tuples that maps of + extraction method names to extended glob patterns + :param options_map: a dictionary of additional options (optional) + :param keywords: a dictionary mapping keywords (i.e. names of functions + that should be recognized as translation functions) to + tuples that specify which of their arguments contain + localizable strings + :param comment_tags: a list of tags of translator comments to search for + and include in the results + :param callback: a function that is called for every file that message are + extracted from, just before the extraction itself is + performed; the function is passed the filename, the name + of the extraction method and and the options dictionary as + positional arguments, in that order + :param strip_comment_tags: a flag that if set to `True` causes all comment + tags to be removed from the collected comments. + :param directory_filter: a callback to determine whether a directory should + be recursed into. Receives the full directory path; + should return True if the directory is valid. + :see: `pathmatch` + """ + if dirname is None: + dirname = os.getcwd() + if options_map is None: + options_map = {} + if directory_filter is None: + directory_filter = default_directory_filter + + absname = os.path.abspath(dirname) + for root, dirnames, filenames in os.walk(absname): + dirnames[:] = [ + subdir for subdir in dirnames + if directory_filter(os.path.join(root, subdir)) + ] + dirnames.sort() + filenames.sort() + for filename in filenames: + filepath = os.path.join(root, filename).replace(os.sep, '/') + + yield from check_and_call_extract_file( + filepath, + method_map, + options_map, + callback, + keywords, + comment_tags, + strip_comment_tags, + dirpath=absname, + ) + + +def check_and_call_extract_file( + filepath: str | os.PathLike[str], + method_map: Iterable[tuple[str, str]], + options_map: SupportsItems[str, dict[str, Any]], + callback: Callable[[str, str, dict[str, Any]], object] | None, + keywords: Mapping[str, _Keyword], + comment_tags: Collection[str], + strip_comment_tags: bool, + dirpath: str | os.PathLike[str] | None = None, +) -> Generator[_FileExtractionResult, None, None]: + """Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file. + + Note that the extraction method mappings are based relative to dirpath. + So, given an absolute path to a file `filepath`, we want to check using + just the relative path from `dirpath` to `filepath`. + + Yields 5-tuples (filename, lineno, messages, comments, context). + + :param filepath: An absolute path to a file that exists. + :param method_map: a list of ``(pattern, method)`` tuples that maps of + extraction method names to extended glob patterns + :param options_map: a dictionary of additional options (optional) + :param callback: a function that is called for every file that message are + extracted from, just before the extraction itself is + performed; the function is passed the filename, the name + of the extraction method and and the options dictionary as + positional arguments, in that order + :param keywords: a dictionary mapping keywords (i.e. names of functions + that should be recognized as translation functions) to + tuples that specify which of their arguments contain + localizable strings + :param comment_tags: a list of tags of translator comments to search for + and include in the results + :param strip_comment_tags: a flag that if set to `True` causes all comment + tags to be removed from the collected comments. + :param dirpath: the path to the directory to extract messages from. + :return: iterable of 5-tuples (filename, lineno, messages, comments, context) + :rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None] + """ + # filename is the relative path from dirpath to the actual file + filename = relpath(filepath, dirpath) + + for pattern, method in method_map: + if not pathmatch(pattern, filename): + continue + + options = {} + for opattern, odict in options_map.items(): + if pathmatch(opattern, filename): + options = odict + break + if callback: + callback(filename, method, options) + for message_tuple in extract_from_file( + method, filepath, + keywords=keywords, + comment_tags=comment_tags, + options=options, + strip_comment_tags=strip_comment_tags, + ): + yield (filename, *message_tuple) + + break + + +def extract_from_file( + method: _ExtractionMethod, + filename: str | os.PathLike[str], + keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS, + comment_tags: Collection[str] = (), + options: Mapping[str, Any] | None = None, + strip_comment_tags: bool = False, +) -> list[_ExtractionResult]: + """Extract messages from a specific file. + + This function returns a list of tuples of the form ``(lineno, message, comments, context)``. + + :param filename: the path to the file to extract messages from + :param method: a string specifying the extraction method (.e.g. "python") + :param keywords: a dictionary mapping keywords (i.e. names of functions + that should be recognized as translation functions) to + tuples that specify which of their arguments contain + localizable strings + :param comment_tags: a list of translator tags to search for and include + in the results + :param strip_comment_tags: a flag that if set to `True` causes all comment + tags to be removed from the collected comments. + :param options: a dictionary of additional options (optional) + :returns: list of tuples of the form ``(lineno, message, comments, context)`` + :rtype: list[tuple[int, str|tuple[str], list[str], str|None] + """ + if method == 'ignore': + return [] + + with open(filename, 'rb') as fileobj: + return list(extract(method, fileobj, keywords, comment_tags, + options, strip_comment_tags)) + + +def _match_messages_against_spec( + lineno: int, + messages: list[str | None], + comments: list[str], + fileobj: _FileObj, + spec: tuple[int | tuple[int, str], ...], +): + translatable = [] + context = None + + # last_index is 1 based like the keyword spec + last_index = len(messages) + for index in spec: + if isinstance(index, tuple): # (n, 'c') + context = messages[index[0] - 1] + continue + if last_index < index: + # Not enough arguments + return + message = messages[index - 1] + if message is None: + return + translatable.append(message) + + # keyword spec indexes are 1 based, therefore '-1' + if isinstance(spec[0], tuple): + # context-aware *gettext method + first_msg_index = spec[1] - 1 + else: + first_msg_index = spec[0] - 1 + # An empty string msgid isn't valid, emit a warning + if not messages[first_msg_index]: + filename = (getattr(fileobj, "name", None) or "(unknown)") + sys.stderr.write( + f"{filename}:{lineno}: warning: Empty msgid. It is reserved by GNU gettext: gettext(\"\") " + f"returns the header entry with meta information, not the empty string.\n", + ) + return + + translatable = tuple(translatable) + if len(translatable) == 1: + translatable = translatable[0] + + return lineno, translatable, comments, context + + +@lru_cache(maxsize=None) +def _find_extractor(name: str): + for ep_name, load in find_entrypoints(GROUP_NAME): + if ep_name == name: + return load() + return None + + +def extract( + method: _ExtractionMethod, + fileobj: _FileObj, + keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS, + comment_tags: Collection[str] = (), + options: Mapping[str, Any] | None = None, + strip_comment_tags: bool = False, +) -> Generator[_ExtractionResult, None, None]: + """Extract messages from the given file-like object using the specified + extraction method. + + This function returns tuples of the form ``(lineno, message, comments, context)``. + + The implementation dispatches the actual extraction to plugins, based on the + value of the ``method`` parameter. + + >>> source = b'''# foo module + ... def run(argv): + ... print(_('Hello, world!')) + ... ''' + + >>> from io import BytesIO + >>> for message in extract('python', BytesIO(source)): + ... print(message) + (3, u'Hello, world!', [], None) + + :param method: an extraction method (a callable), or + a string specifying the extraction method (.e.g. "python"); + if this is a simple name, the extraction function will be + looked up by entry point; if it is an explicit reference + to a function (of the form ``package.module:funcname`` or + ``package.module.funcname``), the corresponding function + will be imported and used + :param fileobj: the file-like object the messages should be extracted from + :param keywords: a dictionary mapping keywords (i.e. names of functions + that should be recognized as translation functions) to + tuples that specify which of their arguments contain + localizable strings + :param comment_tags: a list of translator tags to search for and include + in the results + :param options: a dictionary of additional options (optional) + :param strip_comment_tags: a flag that if set to `True` causes all comment + tags to be removed from the collected comments. + :raise ValueError: if the extraction method is not registered + :returns: iterable of tuples of the form ``(lineno, message, comments, context)`` + :rtype: Iterable[tuple[int, str|tuple[str], list[str], str|None] + """ + if callable(method): + func = method + elif ':' in method or '.' in method: + if ':' not in method: + lastdot = method.rfind('.') + module, attrname = method[:lastdot], method[lastdot + 1:] + else: + module, attrname = method.split(':', 1) + func = getattr(__import__(module, {}, {}, [attrname]), attrname) + else: + func = _find_extractor(method) + if func is None: + # if no named entry point was found, + # we resort to looking up a builtin extractor + func = _BUILTIN_EXTRACTORS.get(method) + + if func is None: + raise ValueError(f"Unknown extraction method {method!r}") + + results = func(fileobj, keywords.keys(), comment_tags, + options=options or {}) + + for lineno, funcname, messages, comments in results: + if not isinstance(messages, (list, tuple)): + messages = [messages] + if not messages: + continue + + specs = keywords[funcname] or None if funcname else None + # {None: x} may be collapsed into x for backwards compatibility. + if not isinstance(specs, dict): + specs = {None: specs} + + if strip_comment_tags: + _strip_comment_tags(comments, comment_tags) + + # None matches all arities. + for arity in (None, len(messages)): + try: + spec = specs[arity] + except KeyError: + continue + if spec is None: + spec = (1,) + result = _match_messages_against_spec(lineno, messages, comments, fileobj, spec) + if result is not None: + yield result + + +def extract_nothing( + fileobj: _FileObj, + keywords: Mapping[str, _Keyword], + comment_tags: Collection[str], + options: Mapping[str, Any], +) -> list[_ExtractionResult]: + """Pseudo extractor that does not actually extract anything, but simply + returns an empty list. + """ + return [] + + +def extract_python( + fileobj: IO[bytes], + keywords: Mapping[str, _Keyword], + comment_tags: Collection[str], + options: _PyOptions, +) -> Generator[_ExtractionResult, None, None]: + """Extract messages from Python source code. + + It returns an iterator yielding tuples in the following form ``(lineno, + funcname, message, comments)``. + + :param fileobj: the seekable, file-like object the messages should be + extracted from + :param keywords: a list of keywords (i.e. function names) that should be + recognized as translation functions + :param comment_tags: a list of translator tags to search for and include + in the results + :param options: a dictionary of additional options (optional) + :rtype: ``iterator`` + """ + funcname = lineno = message_lineno = None + call_stack = -1 + buf = [] + messages = [] + translator_comments = [] + in_def = in_translator_comments = False + comment_tag = None + + encoding = parse_encoding(fileobj) or options.get('encoding', 'UTF-8') + future_flags = parse_future_flags(fileobj, encoding) + next_line = lambda: fileobj.readline().decode(encoding) + + tokens = generate_tokens(next_line) + + # Current prefix of a Python 3.12 (PEP 701) f-string, or None if we're not + # currently parsing one. + current_fstring_start = None + + for tok, value, (lineno, _), _, _ in tokens: + if call_stack == -1 and tok == NAME and value in ('def', 'class'): + in_def = True + elif tok == OP and value == '(': + if in_def: + # Avoid false positives for declarations such as: + # def gettext(arg='message'): + in_def = False + continue + if funcname: + call_stack += 1 + elif in_def and tok == OP and value == ':': + # End of a class definition without parens + in_def = False + continue + elif call_stack == -1 and tok == COMMENT: + # Strip the comment token from the line + value = value[1:].strip() + if in_translator_comments and \ + translator_comments[-1][0] == lineno - 1: + # We're already inside a translator comment, continue appending + translator_comments.append((lineno, value)) + continue + # If execution reaches this point, let's see if comment line + # starts with one of the comment tags + for comment_tag in comment_tags: + if value.startswith(comment_tag): + in_translator_comments = True + translator_comments.append((lineno, value)) + break + elif funcname and call_stack == 0: + nested = (tok == NAME and value in keywords) + if (tok == OP and value == ')') or nested: + if buf: + messages.append(''.join(buf)) + del buf[:] + else: + messages.append(None) + + messages = tuple(messages) if len(messages) > 1 else messages[0] + # Comments don't apply unless they immediately + # precede the message + if translator_comments and \ + translator_comments[-1][0] < message_lineno - 1: + translator_comments = [] + + yield (message_lineno, funcname, messages, + [comment[1] for comment in translator_comments]) + + funcname = lineno = message_lineno = None + call_stack = -1 + messages = [] + translator_comments = [] + in_translator_comments = False + if nested: + funcname = value + elif tok == STRING: + val = _parse_python_string(value, encoding, future_flags) + if val is not None: + if not message_lineno: + message_lineno = lineno + buf.append(val) + + # Python 3.12+, see https://peps.python.org/pep-0701/#new-tokens + elif tok == FSTRING_START: + current_fstring_start = value + if not message_lineno: + message_lineno = lineno + elif tok == FSTRING_MIDDLE: + if current_fstring_start is not None: + current_fstring_start += value + elif tok == FSTRING_END: + if current_fstring_start is not None: + fstring = current_fstring_start + value + val = _parse_python_string(fstring, encoding, future_flags) + if val is not None: + buf.append(val) + + elif tok == OP and value == ',': + if buf: + messages.append(''.join(buf)) + del buf[:] + else: + messages.append(None) + if translator_comments: + # We have translator comments, and since we're on a + # comma(,) user is allowed to break into a new line + # Let's increase the last comment's lineno in order + # for the comment to still be a valid one + old_lineno, old_comment = translator_comments.pop() + translator_comments.append((old_lineno + 1, old_comment)) + + elif tok != NL and not message_lineno: + message_lineno = lineno + elif call_stack > 0 and tok == OP and value == ')': + call_stack -= 1 + elif funcname and call_stack == -1: + funcname = None + elif tok == NAME and value in keywords: + funcname = value + + if current_fstring_start is not None and tok not in {FSTRING_START, FSTRING_MIDDLE}: + # In Python 3.12, tokens other than FSTRING_* mean the + # f-string is dynamic, so we don't wan't to extract it. + # And if it's FSTRING_END, we've already handled it above. + # Let's forget that we're in an f-string. + current_fstring_start = None + + +def _parse_python_string(value: str, encoding: str, future_flags: int) -> str | None: + # Unwrap quotes in a safe manner, maintaining the string's encoding + # https://sourceforge.net/tracker/?func=detail&atid=355470&aid=617979&group_id=5470 + code = compile( + f'# coding={str(encoding)}\n{value}', + '', + 'eval', + ast.PyCF_ONLY_AST | future_flags, + ) + if isinstance(code, ast.Expression): + body = code.body + if isinstance(body, ast.Constant): + return body.value + if isinstance(body, ast.JoinedStr): # f-string + if all(isinstance(node, ast.Constant) for node in body.values): + return ''.join(node.value for node in body.values) + # TODO: we could raise an error or warning when not all nodes are constants + return None + + +def extract_javascript( + fileobj: _FileObj, + keywords: Mapping[str, _Keyword], + comment_tags: Collection[str], + options: _JSOptions, + lineno: int = 1, +) -> Generator[_ExtractionResult, None, None]: + """Extract messages from JavaScript source code. + + :param fileobj: the seekable, file-like object the messages should be + extracted from + :param keywords: a list of keywords (i.e. function names) that should be + recognized as translation functions + :param comment_tags: a list of translator tags to search for and include + in the results + :param options: a dictionary of additional options (optional) + Supported options are: + * `jsx` -- set to false to disable JSX/E4X support. + * `template_string` -- if `True`, supports gettext(`key`) + * `parse_template_string` -- if `True` will parse the + contents of javascript + template strings. + :param lineno: line number offset (for parsing embedded fragments) + """ + from babel.messages.jslexer import Token, tokenize, unquote_string + funcname = message_lineno = None + messages = [] + last_argument = None + translator_comments = [] + concatenate_next = False + encoding = options.get('encoding', 'utf-8') + last_token = None + call_stack = -1 + dotted = any('.' in kw for kw in keywords) + for token in tokenize( + fileobj.read().decode(encoding), + jsx=options.get("jsx", True), + template_string=options.get("template_string", True), + dotted=dotted, + lineno=lineno, + ): + if ( # Turn keyword`foo` expressions into keyword("foo") calls: + funcname and # have a keyword... + (last_token and last_token.type == 'name') and # we've seen nothing after the keyword... + token.type == 'template_string' # this is a template string + ): + message_lineno = token.lineno + messages = [unquote_string(token.value)] + call_stack = 0 + token = Token('operator', ')', token.lineno) + + if options.get('parse_template_string') and not funcname and token.type == 'template_string': + yield from parse_template_string(token.value, keywords, comment_tags, options, token.lineno) + + elif token.type == 'operator' and token.value == '(': + if funcname: + message_lineno = token.lineno + call_stack += 1 + + elif call_stack == -1 and token.type == 'linecomment': + value = token.value[2:].strip() + if translator_comments and \ + translator_comments[-1][0] == token.lineno - 1: + translator_comments.append((token.lineno, value)) + continue + + for comment_tag in comment_tags: + if value.startswith(comment_tag): + translator_comments.append((token.lineno, value.strip())) + break + + elif token.type == 'multilinecomment': + # only one multi-line comment may precede a translation + translator_comments = [] + value = token.value[2:-2].strip() + for comment_tag in comment_tags: + if value.startswith(comment_tag): + lines = value.splitlines() + if lines: + lines[0] = lines[0].strip() + lines[1:] = dedent('\n'.join(lines[1:])).splitlines() + for offset, line in enumerate(lines): + translator_comments.append((token.lineno + offset, + line)) + break + + elif funcname and call_stack == 0: + if token.type == 'operator' and token.value == ')': + if last_argument is not None: + messages.append(last_argument) + if len(messages) > 1: + messages = tuple(messages) + elif messages: + messages = messages[0] + else: + messages = None + + # Comments don't apply unless they immediately precede the + # message + if translator_comments and \ + translator_comments[-1][0] < message_lineno - 1: + translator_comments = [] + + if messages is not None: + yield (message_lineno, funcname, messages, + [comment[1] for comment in translator_comments]) + + funcname = message_lineno = last_argument = None + concatenate_next = False + translator_comments = [] + messages = [] + call_stack = -1 + + elif token.type in ('string', 'template_string'): + new_value = unquote_string(token.value) + if concatenate_next: + last_argument = (last_argument or '') + new_value + concatenate_next = False + else: + last_argument = new_value + + elif token.type == 'operator': + if token.value == ',': + if last_argument is not None: + messages.append(last_argument) + last_argument = None + else: + messages.append(None) + concatenate_next = False + elif token.value == '+': + concatenate_next = True + + elif call_stack > 0 and token.type == 'operator' \ + and token.value == ')': + call_stack -= 1 + + elif funcname and call_stack == -1: + funcname = None + + elif call_stack == -1 and token.type == 'name' and \ + token.value in keywords and \ + (last_token is None or last_token.type != 'name' or + last_token.value != 'function'): + funcname = token.value + + last_token = token + + +def parse_template_string( + template_string: str, + keywords: Mapping[str, _Keyword], + comment_tags: Collection[str], + options: _JSOptions, + lineno: int = 1, +) -> Generator[_ExtractionResult, None, None]: + """Parse JavaScript template string. + + :param template_string: the template string to be parsed + :param keywords: a list of keywords (i.e. function names) that should be + recognized as translation functions + :param comment_tags: a list of translator tags to search for and include + in the results + :param options: a dictionary of additional options (optional) + :param lineno: starting line number (optional) + """ + from babel.messages.jslexer import line_re + prev_character = None + level = 0 + inside_str = False + expression_contents = '' + for character in template_string[1:-1]: + if not inside_str and character in ('"', "'", '`'): + inside_str = character + elif inside_str == character and prev_character != r'\\': + inside_str = False + if level: + expression_contents += character + if not inside_str: + if character == '{' and prev_character == '$': + level += 1 + elif level and character == '}': + level -= 1 + if level == 0 and expression_contents: + expression_contents = expression_contents[0:-1] + fake_file_obj = io.BytesIO(expression_contents.encode()) + yield from extract_javascript(fake_file_obj, keywords, comment_tags, options, lineno) + lineno += len(line_re.findall(expression_contents)) + expression_contents = '' + prev_character = character + + +_BUILTIN_EXTRACTORS = { + 'ignore': extract_nothing, + 'python': extract_python, + 'javascript': extract_javascript, +} diff --git a/lib/python3.10/site-packages/babel/messages/frontend.py b/lib/python3.10/site-packages/babel/messages/frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..29e5a2aa24a7358bbbed61f04230b7804841470a --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/frontend.py @@ -0,0 +1,1202 @@ +""" + babel.messages.frontend + ~~~~~~~~~~~~~~~~~~~~~~~ + + Frontends for the message extraction functionality. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" + +from __future__ import annotations + +import datetime +import fnmatch +import logging +import optparse +import os +import re +import shutil +import sys +import tempfile +import warnings +from configparser import RawConfigParser +from io import StringIO +from typing import BinaryIO, Iterable, Literal + +from babel import Locale, localedata +from babel import __version__ as VERSION +from babel.core import UnknownLocaleError +from babel.messages.catalog import DEFAULT_HEADER, Catalog +from babel.messages.extract import ( + DEFAULT_KEYWORDS, + DEFAULT_MAPPING, + check_and_call_extract_file, + extract_from_dir, +) +from babel.messages.mofile import write_mo +from babel.messages.pofile import read_po, write_po +from babel.util import LOCALTZ + +log = logging.getLogger('babel') + + +class BaseError(Exception): + pass + + +class OptionError(BaseError): + pass + + +class SetupError(BaseError): + pass + + +class ConfigurationError(BaseError): + """ + Raised for errors in configuration files. + """ + + +def listify_value(arg, split=None): + """ + Make a list out of an argument. + + Values from `distutils` argument parsing are always single strings; + values from `optparse` parsing may be lists of strings that may need + to be further split. + + No matter the input, this function returns a flat list of whitespace-trimmed + strings, with `None` values filtered out. + + >>> listify_value("foo bar") + ['foo', 'bar'] + >>> listify_value(["foo bar"]) + ['foo', 'bar'] + >>> listify_value([["foo"], "bar"]) + ['foo', 'bar'] + >>> listify_value([["foo"], ["bar", None, "foo"]]) + ['foo', 'bar', 'foo'] + >>> listify_value("foo, bar, quux", ",") + ['foo', 'bar', 'quux'] + + :param arg: A string or a list of strings + :param split: The argument to pass to `str.split()`. + :return: + """ + out = [] + + if not isinstance(arg, (list, tuple)): + arg = [arg] + + for val in arg: + if val is None: + continue + if isinstance(val, (list, tuple)): + out.extend(listify_value(val, split=split)) + continue + out.extend(s.strip() for s in str(val).split(split)) + assert all(isinstance(val, str) for val in out) + return out + + +class CommandMixin: + # This class is a small shim between Distutils commands and + # optparse option parsing in the frontend command line. + + #: Option name to be input as `args` on the script command line. + as_args = None + + #: Options which allow multiple values. + #: This is used by the `optparse` transmogrification code. + multiple_value_options = () + + #: Options which are booleans. + #: This is used by the `optparse` transmogrification code. + # (This is actually used by distutils code too, but is never + # declared in the base class.) + boolean_options = () + + #: Option aliases, to retain standalone command compatibility. + #: Distutils does not support option aliases, but optparse does. + #: This maps the distutils argument name to an iterable of aliases + #: that are usable with optparse. + option_aliases = {} + + #: Choices for options that needed to be restricted to specific + #: list of choices. + option_choices = {} + + #: Log object. To allow replacement in the script command line runner. + log = log + + def __init__(self, dist=None): + # A less strict version of distutils' `__init__`. + self.distribution = dist + self.initialize_options() + self._dry_run = None + self.verbose = False + self.force = None + self.help = 0 + self.finalized = 0 + + def initialize_options(self): + pass + + def ensure_finalized(self): + if not self.finalized: + self.finalize_options() + self.finalized = 1 + + def finalize_options(self): + raise RuntimeError( + f"abstract method -- subclass {self.__class__} must override", + ) + + +class CompileCatalog(CommandMixin): + description = 'compile message catalogs to binary MO files' + user_options = [ + ('domain=', 'D', + "domains of PO files (space separated list, default 'messages')"), + ('directory=', 'd', + 'path to base directory containing the catalogs'), + ('input-file=', 'i', + 'name of the input file'), + ('output-file=', 'o', + "name of the output file (default " + "'//LC_MESSAGES/.mo')"), + ('locale=', 'l', + 'locale of the catalog to compile'), + ('use-fuzzy', 'f', + 'also include fuzzy translations'), + ('statistics', None, + 'print statistics about translations'), + ] + boolean_options = ['use-fuzzy', 'statistics'] + + def initialize_options(self): + self.domain = 'messages' + self.directory = None + self.input_file = None + self.output_file = None + self.locale = None + self.use_fuzzy = False + self.statistics = False + + def finalize_options(self): + self.domain = listify_value(self.domain) + if not self.input_file and not self.directory: + raise OptionError('you must specify either the input file or the base directory') + if not self.output_file and not self.directory: + raise OptionError('you must specify either the output file or the base directory') + + def run(self): + n_errors = 0 + for domain in self.domain: + for errors in self._run_domain(domain).values(): + n_errors += len(errors) + if n_errors: + self.log.error('%d errors encountered.', n_errors) + return (1 if n_errors else 0) + + def _run_domain(self, domain): + po_files = [] + mo_files = [] + + if not self.input_file: + if self.locale: + po_files.append((self.locale, + os.path.join(self.directory, self.locale, + 'LC_MESSAGES', + f"{domain}.po"))) + mo_files.append(os.path.join(self.directory, self.locale, + 'LC_MESSAGES', + f"{domain}.mo")) + else: + for locale in os.listdir(self.directory): + po_file = os.path.join(self.directory, locale, + 'LC_MESSAGES', f"{domain}.po") + if os.path.exists(po_file): + po_files.append((locale, po_file)) + mo_files.append(os.path.join(self.directory, locale, + 'LC_MESSAGES', + f"{domain}.mo")) + else: + po_files.append((self.locale, self.input_file)) + if self.output_file: + mo_files.append(self.output_file) + else: + mo_files.append(os.path.join(self.directory, self.locale, + 'LC_MESSAGES', + f"{domain}.mo")) + + if not po_files: + raise OptionError('no message catalogs found') + + catalogs_and_errors = {} + + for idx, (locale, po_file) in enumerate(po_files): + mo_file = mo_files[idx] + with open(po_file, 'rb') as infile: + catalog = read_po(infile, locale) + + if self.statistics: + translated = 0 + for message in list(catalog)[1:]: + if message.string: + translated += 1 + percentage = 0 + if len(catalog): + percentage = translated * 100 // len(catalog) + self.log.info( + '%d of %d messages (%d%%) translated in %s', + translated, len(catalog), percentage, po_file, + ) + + if catalog.fuzzy and not self.use_fuzzy: + self.log.info('catalog %s is marked as fuzzy, skipping', po_file) + continue + + catalogs_and_errors[catalog] = catalog_errors = list(catalog.check()) + for message, errors in catalog_errors: + for error in errors: + self.log.error( + 'error: %s:%d: %s', po_file, message.lineno, error, + ) + + self.log.info('compiling catalog %s to %s', po_file, mo_file) + + with open(mo_file, 'wb') as outfile: + write_mo(outfile, catalog, use_fuzzy=self.use_fuzzy) + + return catalogs_and_errors + + +def _make_directory_filter(ignore_patterns): + """ + Build a directory_filter function based on a list of ignore patterns. + """ + + def cli_directory_filter(dirname): + basename = os.path.basename(dirname) + return not any( + fnmatch.fnmatch(basename, ignore_pattern) + for ignore_pattern + in ignore_patterns + ) + + return cli_directory_filter + + +class ExtractMessages(CommandMixin): + description = 'extract localizable strings from the project code' + user_options = [ + ('charset=', None, + 'charset to use in the output file (default "utf-8")'), + ('keywords=', 'k', + 'space-separated list of keywords to look for in addition to the ' + 'defaults (may be repeated multiple times)'), + ('no-default-keywords', None, + 'do not include the default keywords'), + ('mapping-file=', 'F', + 'path to the mapping configuration file'), + ('no-location', None, + 'do not include location comments with filename and line number'), + ('add-location=', None, + 'location lines format. If it is not given or "full", it generates ' + 'the lines with both file name and line number. If it is "file", ' + 'the line number part is omitted. If it is "never", it completely ' + 'suppresses the lines (same as --no-location).'), + ('omit-header', None, + 'do not include msgid "" entry in header'), + ('output-file=', 'o', + 'name of the output file'), + ('width=', 'w', + 'set output line width (default 76)'), + ('no-wrap', None, + 'do not break long message lines, longer than the output line width, ' + 'into several lines'), + ('sort-output', None, + 'generate sorted output (default False)'), + ('sort-by-file', None, + 'sort output by file location (default False)'), + ('msgid-bugs-address=', None, + 'set report address for msgid'), + ('copyright-holder=', None, + 'set copyright holder in output'), + ('project=', None, + 'set project name in output'), + ('version=', None, + 'set project version in output'), + ('add-comments=', 'c', + 'place comment block with TAG (or those preceding keyword lines) in ' + 'output file. Separate multiple TAGs with commas(,)'), # TODO: Support repetition of this argument + ('strip-comments', 's', + 'strip the comment TAGs from the comments.'), + ('input-paths=', None, + 'files or directories that should be scanned for messages. Separate multiple ' + 'files or directories with commas(,)'), # TODO: Support repetition of this argument + ('input-dirs=', None, # TODO (3.x): Remove me. + 'alias for input-paths (does allow files as well as directories).'), + ('ignore-dirs=', None, + 'Patterns for directories to ignore when scanning for messages. ' + 'Separate multiple patterns with spaces (default ".* ._")'), + ('header-comment=', None, + 'header comment for the catalog'), + ('last-translator=', None, + 'set the name and email of the last translator in output'), + ] + boolean_options = [ + 'no-default-keywords', 'no-location', 'omit-header', 'no-wrap', + 'sort-output', 'sort-by-file', 'strip-comments', + ] + as_args = 'input-paths' + multiple_value_options = ( + 'add-comments', + 'keywords', + 'ignore-dirs', + ) + option_aliases = { + 'keywords': ('--keyword',), + 'mapping-file': ('--mapping',), + 'output-file': ('--output',), + 'strip-comments': ('--strip-comment-tags',), + 'last-translator': ('--last-translator',), + } + option_choices = { + 'add-location': ('full', 'file', 'never'), + } + + def initialize_options(self): + self.charset = 'utf-8' + self.keywords = None + self.no_default_keywords = False + self.mapping_file = None + self.no_location = False + self.add_location = None + self.omit_header = False + self.output_file = None + self.input_dirs = None + self.input_paths = None + self.width = None + self.no_wrap = False + self.sort_output = False + self.sort_by_file = False + self.msgid_bugs_address = None + self.copyright_holder = None + self.project = None + self.version = None + self.add_comments = None + self.strip_comments = False + self.include_lineno = True + self.ignore_dirs = None + self.header_comment = None + self.last_translator = None + + def finalize_options(self): + if self.input_dirs: + if not self.input_paths: + self.input_paths = self.input_dirs + else: + raise OptionError( + 'input-dirs and input-paths are mutually exclusive', + ) + + keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy() + + keywords.update(parse_keywords(listify_value(self.keywords))) + + self.keywords = keywords + + if not self.keywords: + raise OptionError( + 'you must specify new keywords if you disable the default ones', + ) + + if not self.output_file: + raise OptionError('no output file specified') + if self.no_wrap and self.width: + raise OptionError( + "'--no-wrap' and '--width' are mutually exclusive", + ) + if not self.no_wrap and not self.width: + self.width = 76 + elif self.width is not None: + self.width = int(self.width) + + if self.sort_output and self.sort_by_file: + raise OptionError( + "'--sort-output' and '--sort-by-file' are mutually exclusive", + ) + + if self.input_paths: + if isinstance(self.input_paths, str): + self.input_paths = re.split(r',\s*', self.input_paths) + elif self.distribution is not None: + self.input_paths = dict.fromkeys([ + k.split('.', 1)[0] + for k in (self.distribution.packages or ()) + ]).keys() + else: + self.input_paths = [] + + if not self.input_paths: + raise OptionError("no input files or directories specified") + + for path in self.input_paths: + if not os.path.exists(path): + raise OptionError(f"Input path: {path} does not exist") + + self.add_comments = listify_value(self.add_comments or (), ",") + + if self.distribution: + if not self.project: + self.project = self.distribution.get_name() + if not self.version: + self.version = self.distribution.get_version() + + if self.add_location == 'never': + self.no_location = True + elif self.add_location == 'file': + self.include_lineno = False + + ignore_dirs = listify_value(self.ignore_dirs) + if ignore_dirs: + self.directory_filter = _make_directory_filter(ignore_dirs) + else: + self.directory_filter = None + + def _build_callback(self, path: str): + def callback(filename: str, method: str, options: dict): + if method == 'ignore': + return + + # If we explicitly provide a full filepath, just use that. + # Otherwise, path will be the directory path and filename + # is the relative path from that dir to the file. + # So we can join those to get the full filepath. + if os.path.isfile(path): + filepath = path + else: + filepath = os.path.normpath(os.path.join(path, filename)) + + optstr = '' + if options: + opt_values = ", ".join(f'{k}="{v}"' for k, v in options.items()) + optstr = f" ({opt_values})" + self.log.info('extracting messages from %s%s', filepath, optstr) + + return callback + + def run(self): + mappings = self._get_mappings() + with open(self.output_file, 'wb') as outfile: + catalog = Catalog(project=self.project, + version=self.version, + msgid_bugs_address=self.msgid_bugs_address, + copyright_holder=self.copyright_holder, + charset=self.charset, + header_comment=(self.header_comment or DEFAULT_HEADER), + last_translator=self.last_translator) + + for path, method_map, options_map in mappings: + callback = self._build_callback(path) + if os.path.isfile(path): + current_dir = os.getcwd() + extracted = check_and_call_extract_file( + path, method_map, options_map, + callback, self.keywords, self.add_comments, + self.strip_comments, current_dir, + ) + else: + extracted = extract_from_dir( + path, method_map, options_map, + keywords=self.keywords, + comment_tags=self.add_comments, + callback=callback, + strip_comment_tags=self.strip_comments, + directory_filter=self.directory_filter, + ) + for filename, lineno, message, comments, context in extracted: + if os.path.isfile(path): + filepath = filename # already normalized + else: + filepath = os.path.normpath(os.path.join(path, filename)) + + catalog.add(message, None, [(filepath, lineno)], + auto_comments=comments, context=context) + + self.log.info('writing PO template file to %s', self.output_file) + write_po(outfile, catalog, width=self.width, + no_location=self.no_location, + omit_header=self.omit_header, + sort_output=self.sort_output, + sort_by_file=self.sort_by_file, + include_lineno=self.include_lineno) + + def _get_mappings(self): + mappings = [] + + if self.mapping_file: + if self.mapping_file.endswith(".toml"): + with open(self.mapping_file, "rb") as fileobj: + file_style = ( + "pyproject.toml" + if os.path.basename(self.mapping_file) == "pyproject.toml" + else "standalone" + ) + method_map, options_map = _parse_mapping_toml( + fileobj, + filename=self.mapping_file, + style=file_style, + ) + else: + with open(self.mapping_file) as fileobj: + method_map, options_map = parse_mapping_cfg(fileobj, filename=self.mapping_file) + for path in self.input_paths: + mappings.append((path, method_map, options_map)) + + elif getattr(self.distribution, 'message_extractors', None): + message_extractors = self.distribution.message_extractors + for path, mapping in message_extractors.items(): + if isinstance(mapping, str): + method_map, options_map = parse_mapping_cfg(StringIO(mapping)) + else: + method_map, options_map = [], {} + for pattern, method, options in mapping: + method_map.append((pattern, method)) + options_map[pattern] = options or {} + mappings.append((path, method_map, options_map)) + + else: + for path in self.input_paths: + mappings.append((path, DEFAULT_MAPPING, {})) + + return mappings + + +class InitCatalog(CommandMixin): + description = 'create a new catalog based on a POT file' + user_options = [ + ('domain=', 'D', + "domain of PO file (default 'messages')"), + ('input-file=', 'i', + 'name of the input file'), + ('output-dir=', 'd', + 'path to output directory'), + ('output-file=', 'o', + "name of the output file (default " + "'//LC_MESSAGES/.po')"), + ('locale=', 'l', + 'locale for the new localized catalog'), + ('width=', 'w', + 'set output line width (default 76)'), + ('no-wrap', None, + 'do not break long message lines, longer than the output line width, ' + 'into several lines'), + ] + boolean_options = ['no-wrap'] + + def initialize_options(self): + self.output_dir = None + self.output_file = None + self.input_file = None + self.locale = None + self.domain = 'messages' + self.no_wrap = False + self.width = None + + def finalize_options(self): + if not self.input_file: + raise OptionError('you must specify the input file') + + if not self.locale: + raise OptionError('you must provide a locale for the new catalog') + try: + self._locale = Locale.parse(self.locale) + except UnknownLocaleError as e: + raise OptionError(e) from e + + if not self.output_file and not self.output_dir: + raise OptionError('you must specify the output directory') + if not self.output_file: + self.output_file = os.path.join(self.output_dir, self.locale, + 'LC_MESSAGES', f"{self.domain}.po") + + if not os.path.exists(os.path.dirname(self.output_file)): + os.makedirs(os.path.dirname(self.output_file)) + if self.no_wrap and self.width: + raise OptionError("'--no-wrap' and '--width' are mutually exclusive") + if not self.no_wrap and not self.width: + self.width = 76 + elif self.width is not None: + self.width = int(self.width) + + def run(self): + self.log.info( + 'creating catalog %s based on %s', self.output_file, self.input_file, + ) + + with open(self.input_file, 'rb') as infile: + # Although reading from the catalog template, read_po must be fed + # the locale in order to correctly calculate plurals + catalog = read_po(infile, locale=self.locale) + + catalog.locale = self._locale + catalog.revision_date = datetime.datetime.now(LOCALTZ) + catalog.fuzzy = False + + with open(self.output_file, 'wb') as outfile: + write_po(outfile, catalog, width=self.width) + + +class UpdateCatalog(CommandMixin): + description = 'update message catalogs from a POT file' + user_options = [ + ('domain=', 'D', + "domain of PO file (default 'messages')"), + ('input-file=', 'i', + 'name of the input file'), + ('output-dir=', 'd', + 'path to base directory containing the catalogs'), + ('output-file=', 'o', + "name of the output file (default " + "'//LC_MESSAGES/.po')"), + ('omit-header', None, + "do not include msgid "" entry in header"), + ('locale=', 'l', + 'locale of the catalog to compile'), + ('width=', 'w', + 'set output line width (default 76)'), + ('no-wrap', None, + 'do not break long message lines, longer than the output line width, ' + 'into several lines'), + ('ignore-obsolete=', None, + 'whether to omit obsolete messages from the output'), + ('init-missing=', None, + 'if any output files are missing, initialize them first'), + ('no-fuzzy-matching', 'N', + 'do not use fuzzy matching'), + ('update-header-comment', None, + 'update target header comment'), + ('previous', None, + 'keep previous msgids of translated messages'), + ('check=', None, + 'don\'t update the catalog, just return the status. Return code 0 ' + 'means nothing would change. Return code 1 means that the catalog ' + 'would be updated'), + ('ignore-pot-creation-date=', None, + 'ignore changes to POT-Creation-Date when updating or checking'), + ] + boolean_options = [ + 'omit-header', 'no-wrap', 'ignore-obsolete', 'init-missing', + 'no-fuzzy-matching', 'previous', 'update-header-comment', + 'check', 'ignore-pot-creation-date', + ] + + def initialize_options(self): + self.domain = 'messages' + self.input_file = None + self.output_dir = None + self.output_file = None + self.omit_header = False + self.locale = None + self.width = None + self.no_wrap = False + self.ignore_obsolete = False + self.init_missing = False + self.no_fuzzy_matching = False + self.update_header_comment = False + self.previous = False + self.check = False + self.ignore_pot_creation_date = False + + def finalize_options(self): + if not self.input_file: + raise OptionError('you must specify the input file') + if not self.output_file and not self.output_dir: + raise OptionError('you must specify the output file or directory') + if self.output_file and not self.locale: + raise OptionError('you must specify the locale') + + if self.init_missing: + if not self.locale: + raise OptionError( + 'you must specify the locale for ' + 'the init-missing option to work', + ) + + try: + self._locale = Locale.parse(self.locale) + except UnknownLocaleError as e: + raise OptionError(e) from e + else: + self._locale = None + + if self.no_wrap and self.width: + raise OptionError("'--no-wrap' and '--width' are mutually exclusive") + if not self.no_wrap and not self.width: + self.width = 76 + elif self.width is not None: + self.width = int(self.width) + if self.no_fuzzy_matching and self.previous: + self.previous = False + + def run(self): + check_status = {} + po_files = [] + if not self.output_file: + if self.locale: + po_files.append((self.locale, + os.path.join(self.output_dir, self.locale, + 'LC_MESSAGES', + f"{self.domain}.po"))) + else: + for locale in os.listdir(self.output_dir): + po_file = os.path.join(self.output_dir, locale, + 'LC_MESSAGES', + f"{self.domain}.po") + if os.path.exists(po_file): + po_files.append((locale, po_file)) + else: + po_files.append((self.locale, self.output_file)) + + if not po_files: + raise OptionError('no message catalogs found') + + domain = self.domain + if not domain: + domain = os.path.splitext(os.path.basename(self.input_file))[0] + + with open(self.input_file, 'rb') as infile: + template = read_po(infile) + + for locale, filename in po_files: + if self.init_missing and not os.path.exists(filename): + if self.check: + check_status[filename] = False + continue + self.log.info( + 'creating catalog %s based on %s', filename, self.input_file, + ) + + with open(self.input_file, 'rb') as infile: + # Although reading from the catalog template, read_po must + # be fed the locale in order to correctly calculate plurals + catalog = read_po(infile, locale=self.locale) + + catalog.locale = self._locale + catalog.revision_date = datetime.datetime.now(LOCALTZ) + catalog.fuzzy = False + + with open(filename, 'wb') as outfile: + write_po(outfile, catalog) + + self.log.info('updating catalog %s based on %s', filename, self.input_file) + with open(filename, 'rb') as infile: + catalog = read_po(infile, locale=locale, domain=domain) + + catalog.update( + template, self.no_fuzzy_matching, + update_header_comment=self.update_header_comment, + update_creation_date=not self.ignore_pot_creation_date, + ) + + tmpname = os.path.join(os.path.dirname(filename), + tempfile.gettempprefix() + + os.path.basename(filename)) + try: + with open(tmpname, 'wb') as tmpfile: + write_po(tmpfile, catalog, + omit_header=self.omit_header, + ignore_obsolete=self.ignore_obsolete, + include_previous=self.previous, width=self.width) + except Exception: + os.remove(tmpname) + raise + + if self.check: + with open(filename, "rb") as origfile: + original_catalog = read_po(origfile) + with open(tmpname, "rb") as newfile: + updated_catalog = read_po(newfile) + updated_catalog.revision_date = original_catalog.revision_date + check_status[filename] = updated_catalog.is_identical(original_catalog) + os.remove(tmpname) + continue + + try: + os.rename(tmpname, filename) + except OSError: + # We're probably on Windows, which doesn't support atomic + # renames, at least not through Python + # If the error is in fact due to a permissions problem, that + # same error is going to be raised from one of the following + # operations + os.remove(filename) + shutil.copy(tmpname, filename) + os.remove(tmpname) + + if self.check: + for filename, up_to_date in check_status.items(): + if up_to_date: + self.log.info('Catalog %s is up to date.', filename) + else: + self.log.warning('Catalog %s is out of date.', filename) + if not all(check_status.values()): + raise BaseError("Some catalogs are out of date.") + else: + self.log.info("All the catalogs are up-to-date.") + return + + +class CommandLineInterface: + """Command-line interface. + + This class provides a simple command-line interface to the message + extraction and PO file generation functionality. + """ + + usage = '%%prog %s [options] %s' + version = f'%prog {VERSION}' + commands = { + 'compile': 'compile message catalogs to MO files', + 'extract': 'extract messages from source files and generate a POT file', + 'init': 'create new message catalogs from a POT file', + 'update': 'update existing message catalogs from a POT file', + } + + command_classes = { + 'compile': CompileCatalog, + 'extract': ExtractMessages, + 'init': InitCatalog, + 'update': UpdateCatalog, + } + + log = None # Replaced on instance level + + def run(self, argv=None): + """Main entry point of the command-line interface. + + :param argv: list of arguments passed on the command-line + """ + + if argv is None: + argv = sys.argv + + self.parser = optparse.OptionParser(usage=self.usage % ('command', '[args]'), + version=self.version) + self.parser.disable_interspersed_args() + self.parser.print_help = self._help + self.parser.add_option('--list-locales', dest='list_locales', + action='store_true', + help="print all known locales and exit") + self.parser.add_option('-v', '--verbose', action='store_const', + dest='loglevel', const=logging.DEBUG, + help='print as much as possible') + self.parser.add_option('-q', '--quiet', action='store_const', + dest='loglevel', const=logging.ERROR, + help='print as little as possible') + self.parser.set_defaults(list_locales=False, loglevel=logging.INFO) + + options, args = self.parser.parse_args(argv[1:]) + + self._configure_logging(options.loglevel) + if options.list_locales: + identifiers = localedata.locale_identifiers() + id_width = max(len(identifier) for identifier in identifiers) + 1 + for identifier in sorted(identifiers): + locale = Locale.parse(identifier) + print(f"{identifier:<{id_width}} {locale.english_name}") + return 0 + + if not args: + self.parser.error('no valid command or option passed. ' + 'Try the -h/--help option for more information.') + + cmdname = args[0] + if cmdname not in self.commands: + self.parser.error(f'unknown command "{cmdname}"') + + cmdinst = self._configure_command(cmdname, args[1:]) + return cmdinst.run() + + def _configure_logging(self, loglevel): + self.log = log + self.log.setLevel(loglevel) + # Don't add a new handler for every instance initialization (#227), this + # would cause duplicated output when the CommandLineInterface as an + # normal Python class. + if self.log.handlers: + handler = self.log.handlers[0] + else: + handler = logging.StreamHandler() + self.log.addHandler(handler) + handler.setLevel(loglevel) + formatter = logging.Formatter('%(message)s') + handler.setFormatter(formatter) + + def _help(self): + print(self.parser.format_help()) + print("commands:") + cmd_width = max(8, max(len(command) for command in self.commands) + 1) + for name, description in sorted(self.commands.items()): + print(f" {name:<{cmd_width}} {description}") + + def _configure_command(self, cmdname, argv): + """ + :type cmdname: str + :type argv: list[str] + """ + cmdclass = self.command_classes[cmdname] + cmdinst = cmdclass() + if self.log: + cmdinst.log = self.log # Use our logger, not distutils'. + assert isinstance(cmdinst, CommandMixin) + cmdinst.initialize_options() + + parser = optparse.OptionParser( + usage=self.usage % (cmdname, ''), + description=self.commands[cmdname], + ) + as_args: str | None = getattr(cmdclass, "as_args", None) + for long, short, help in cmdclass.user_options: + name = long.strip("=") + default = getattr(cmdinst, name.replace("-", "_")) + strs = [f"--{name}"] + if short: + strs.append(f"-{short}") + strs.extend(cmdclass.option_aliases.get(name, ())) + choices = cmdclass.option_choices.get(name, None) + if name == as_args: + parser.usage += f"<{name}>" + elif name in cmdclass.boolean_options: + parser.add_option(*strs, action="store_true", help=help) + elif name in cmdclass.multiple_value_options: + parser.add_option(*strs, action="append", help=help, choices=choices) + else: + parser.add_option(*strs, help=help, default=default, choices=choices) + options, args = parser.parse_args(argv) + + if as_args: + setattr(options, as_args.replace('-', '_'), args) + + for key, value in vars(options).items(): + setattr(cmdinst, key, value) + + try: + cmdinst.ensure_finalized() + except OptionError as err: + parser.error(str(err)) + + return cmdinst + + +def main(): + return CommandLineInterface().run(sys.argv) + + +def parse_mapping(fileobj, filename=None): + warnings.warn( + "parse_mapping is deprecated, use parse_mapping_cfg instead", + DeprecationWarning, + stacklevel=2, + ) + return parse_mapping_cfg(fileobj, filename) + + +def parse_mapping_cfg(fileobj, filename=None): + """Parse an extraction method mapping from a file-like object. + + :param fileobj: a readable file-like object containing the configuration + text to parse + :param filename: the name of the file being parsed, for error messages + """ + extractors = {} + method_map = [] + options_map = {} + + parser = RawConfigParser() + parser.read_file(fileobj, filename) + + for section in parser.sections(): + if section == 'extractors': + extractors = dict(parser.items(section)) + else: + method, pattern = (part.strip() for part in section.split(':', 1)) + method_map.append((pattern, method)) + options_map[pattern] = dict(parser.items(section)) + + if extractors: + for idx, (pattern, method) in enumerate(method_map): + if method in extractors: + method = extractors[method] + method_map[idx] = (pattern, method) + + return method_map, options_map + + +def _parse_config_object(config: dict, *, filename="(unknown)"): + extractors = {} + method_map = [] + options_map = {} + + extractors_read = config.get("extractors", {}) + if not isinstance(extractors_read, dict): + raise ConfigurationError(f"{filename}: extractors: Expected a dictionary, got {type(extractors_read)!r}") + for method, callable_spec in extractors_read.items(): + if not isinstance(method, str): + # Impossible via TOML, but could happen with a custom object. + raise ConfigurationError(f"{filename}: extractors: Extraction method must be a string, got {method!r}") + if not isinstance(callable_spec, str): + raise ConfigurationError(f"{filename}: extractors: Callable specification must be a string, got {callable_spec!r}") + extractors[method] = callable_spec + + if "mapping" in config: + raise ConfigurationError(f"{filename}: 'mapping' is not a valid key, did you mean 'mappings'?") + + mappings_read = config.get("mappings", []) + if not isinstance(mappings_read, list): + raise ConfigurationError(f"{filename}: mappings: Expected a list, got {type(mappings_read)!r}") + for idx, entry in enumerate(mappings_read): + if not isinstance(entry, dict): + raise ConfigurationError(f"{filename}: mappings[{idx}]: Expected a dictionary, got {type(entry)!r}") + entry = entry.copy() + + method = entry.pop("method", None) + if not isinstance(method, str): + raise ConfigurationError(f"{filename}: mappings[{idx}]: 'method' must be a string, got {method!r}") + method = extractors.get(method, method) # Map the extractor name to the callable now + + pattern = entry.pop("pattern", None) + if not isinstance(pattern, (list, str)): + raise ConfigurationError(f"{filename}: mappings[{idx}]: 'pattern' must be a list or a string, got {pattern!r}") + if not isinstance(pattern, list): + pattern = [pattern] + + for pat in pattern: + if not isinstance(pat, str): + raise ConfigurationError(f"{filename}: mappings[{idx}]: 'pattern' elements must be strings, got {pat!r}") + method_map.append((pat, method)) + options_map[pat] = entry + + return method_map, options_map + + +def _parse_mapping_toml( + fileobj: BinaryIO, + filename: str = "(unknown)", + style: Literal["standalone", "pyproject.toml"] = "standalone", +): + """Parse an extraction method mapping from a binary file-like object. + + .. warning: As of this version of Babel, this is a private API subject to changes. + + :param fileobj: a readable binary file-like object containing the configuration TOML to parse + :param filename: the name of the file being parsed, for error messages + :param style: whether the file is in the style of a `pyproject.toml` file, i.e. whether to look for `tool.babel`. + """ + try: + import tomllib + except ImportError: + try: + import tomli as tomllib + except ImportError as ie: # pragma: no cover + raise ImportError("tomli or tomllib is required to parse TOML files") from ie + + try: + parsed_data = tomllib.load(fileobj) + except tomllib.TOMLDecodeError as e: + raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e + + if style == "pyproject.toml": + try: + babel_data = parsed_data["tool"]["babel"] + except (TypeError, KeyError) as e: + raise ConfigurationError(f"{filename}: No 'tool.babel' section found in file") from e + elif style == "standalone": + babel_data = parsed_data + if "babel" in babel_data: + raise ConfigurationError(f"{filename}: 'babel' should not be present in a stand-alone configuration file") + else: # pragma: no cover + raise ValueError(f"Unknown TOML style {style!r}") + + return _parse_config_object(babel_data, filename=filename) + + +def _parse_spec(s: str) -> tuple[int | None, tuple[int | tuple[int, str], ...]]: + inds = [] + number = None + for x in s.split(','): + if x[-1] == 't': + number = int(x[:-1]) + elif x[-1] == 'c': + inds.append((int(x[:-1]), 'c')) + else: + inds.append(int(x)) + return number, tuple(inds) + + +def parse_keywords(strings: Iterable[str] = ()): + """Parse keywords specifications from the given list of strings. + + >>> import pprint + >>> keywords = ['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2', + ... 'polymorphic:1', 'polymorphic:2,2t', 'polymorphic:3c,3t'] + >>> pprint.pprint(parse_keywords(keywords)) + {'_': None, + 'dgettext': (2,), + 'dngettext': (2, 3), + 'pgettext': ((1, 'c'), 2), + 'polymorphic': {None: (1,), 2: (2,), 3: ((3, 'c'),)}} + + The input keywords are in GNU Gettext style; see :doc:`cmdline` for details. + + The output is a dictionary mapping keyword names to a dictionary of specifications. + Keys in this dictionary are numbers of arguments, where ``None`` means that all numbers + of arguments are matched, and a number means only calls with that number of arguments + are matched (which happens when using the "t" specifier). However, as a special + case for backwards compatibility, if the dictionary of specifications would + be ``{None: x}``, i.e., there is only one specification and it matches all argument + counts, then it is collapsed into just ``x``. + + A specification is either a tuple or None. If a tuple, each element can be either a number + ``n``, meaning that the nth argument should be extracted as a message, or the tuple + ``(n, 'c')``, meaning that the nth argument should be extracted as context for the + messages. A ``None`` specification is equivalent to ``(1,)``, extracting the first + argument. + """ + keywords = {} + for string in strings: + if ':' in string: + funcname, spec_str = string.split(':') + number, spec = _parse_spec(spec_str) + else: + funcname = string + number = None + spec = None + keywords.setdefault(funcname, {})[number] = spec + + # For best backwards compatibility, collapse {None: x} into x. + for k, v in keywords.items(): + if set(v) == {None}: + keywords[k] = v[None] + + return keywords + + +def __getattr__(name: str): + # Re-exports for backwards compatibility; + # `setuptools_frontend` is the canonical import location. + if name in {'check_message_extractors', 'compile_catalog', 'extract_messages', 'init_catalog', 'update_catalog'}: + from babel.messages import setuptools_frontend + + return getattr(setuptools_frontend, name) + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +if __name__ == '__main__': + main() diff --git a/lib/python3.10/site-packages/babel/messages/jslexer.py b/lib/python3.10/site-packages/babel/messages/jslexer.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc4956fd8c9219f3c5e9dafd377d69c63d749c6 --- /dev/null +++ b/lib/python3.10/site-packages/babel/messages/jslexer.py @@ -0,0 +1,204 @@ +""" + babel.messages.jslexer + ~~~~~~~~~~~~~~~~~~~~~~ + + A simple JavaScript 1.5 lexer which is used for the JavaScript + extractor. + + :copyright: (c) 2013-2025 by the Babel Team. + :license: BSD, see LICENSE for more details. +""" +from __future__ import annotations + +import re +from collections.abc import Generator +from typing import NamedTuple + +operators: list[str] = sorted([ + '+', '-', '*', '%', '!=', '==', '<', '>', '<=', '>=', '=', + '+=', '-=', '*=', '%=', '<<', '>>', '>>>', '<<=', '>>=', + '>>>=', '&', '&=', '|', '|=', '&&', '||', '^', '^=', '(', ')', + '[', ']', '{', '}', '!', '--', '++', '~', ',', ';', '.', ':', +], key=len, reverse=True) + +escapes: dict[str, str] = {'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t'} + +name_re = re.compile(r'[\w$_][\w\d$_]*', re.UNICODE) +dotted_name_re = re.compile(r'[\w$_][\w\d$_.]*[\w\d$_.]', re.UNICODE) +division_re = re.compile(r'/=?') +regex_re = re.compile(r'/(?:[^/\\]*(?:\\.[^/\\]*)*)/[a-zA-Z]*', re.DOTALL) +line_re = re.compile(r'(\r\n|\n|\r)') +line_join_re = re.compile(r'\\' + line_re.pattern) +uni_escape_re = re.compile(r'[a-fA-F0-9]{1,4}') +hex_escape_re = re.compile(r'[a-fA-F0-9]{1,2}') + + +class Token(NamedTuple): + type: str + value: str + lineno: int + + +_rules: list[tuple[str | None, re.Pattern[str]]] = [ + (None, re.compile(r'\s+', re.UNICODE)), + (None, re.compile(r'