Debian Codegraph @

babel/messages/checkers.py

raw
1 """
2 babel.messages.checkers
3 ~~~~~~~~~~~~~~~~~~~~~~~
4
5 Various routines that help with validation of translations.
6
7 :since: version 0.9
8
9 :copyright: (c) 2013-2026 by the Babel Team.
10 :license: BSD, see LICENSE for more details.
11 """
12
13 from __future__ import annotations
14
15 from collections.abc import Callable
16
17 from babel.messages.catalog import PYTHON_FORMAT, Catalog, Message, TranslationError
18
19 #: list of format chars that are compatible to each other
20 _string_format_compatibilities = [
21 {'i', 'd', 'u'},
22 {'x', 'X'},
23 {'f', 'F', 'g', 'G'},
24 ]
25
26
27 def num_plurals(catalog: Catalog | None, message: Message) -> None:
28 """Verify the number of plurals in the translation."""
29 if not message.pluralizable:
30 if not isinstance(message.string, str):
31 raise TranslationError("Found plural forms for non-pluralizable message")
32 return
33
34 # skip further tests if no catalog is provided.
35 elif catalog is None:
36 return
37
38 msgstrs = message.string
39 if not isinstance(msgstrs, (list, tuple)):
40 msgstrs = (msgstrs,)
41 if len(msgstrs) != catalog.num_plurals:
42 raise TranslationError(
43 f"Wrong number of plural forms (expected {catalog.num_plurals})",
44 )
45
46
47 def python_format(catalog: Catalog | None, message: Message) -> None:
48 """Verify the format string placeholders in the translation."""
49 if 'python-format' not in message.flags:
50 return
51 msgids = message.id
52 if not isinstance(msgids, (list, tuple)):
53 msgids = (msgids,)
54 msgstrs = message.string
55 if not isinstance(msgstrs, (list, tuple)):
56 msgstrs = (msgstrs,)
57
58 if msgstrs[0]:
59 _validate_format(msgids[0], msgstrs[0])
60 if message.pluralizable:
61 for msgstr in msgstrs[1:]:
62 if msgstr:
63 _validate_format(msgids[1], msgstr)
64
65
66 def _validate_format(format: str, alternative: str) -> None:
67 """Test format string `alternative` against `format`. `format` can be the
68 msgid of a message and `alternative` one of the `msgstr`\\s. The two
69 arguments are not interchangeable as `alternative` may contain less
70 placeholders if `format` uses named placeholders.
71
72 If the string formatting of `alternative` is compatible to `format` the
73 function returns `None`, otherwise a `TranslationError` is raised.
74
75 Examples for compatible format strings:
76
77 >>> _validate_format('Hello %s!', 'Hallo %s!')
78 >>> _validate_format('Hello %i!', 'Hallo %d!')
79
80 Example for an incompatible format strings:
81
82 >>> _validate_format('Hello %(name)s!', 'Hallo %s!')
83 Traceback (most recent call last):
84 ...
85 TranslationError: the format strings are of different kinds
86
87 This function is used by the `python_format` checker.
88
89 :param format: The original format string
90 :param alternative: The alternative format string that should be checked
91 against format
92 :raises TranslationError: on formatting errors
93 """
94
95 def _parse(string: str) -> list[tuple[str, str]]:
96 result: list[tuple[str, str]] = []
97 for match in PYTHON_FORMAT.finditer(string):
98 name, format, typechar = match.groups()
99 if typechar == '%' and name is None:
100 continue
101 result.append((name, str(typechar)))
102 return result
103
104 def _compatible(a: str, b: str) -> bool:
105 if a == b:
106 return True
107 for set in _string_format_compatibilities:
108 if a in set and b in set:
109 return True
110 return False
111
112 def _check_positional(results: list[tuple[str, str]]) -> bool:
113 positional = None
114 for name, _char in results:
115 if positional is None:
116 positional = name is None
117 else:
118 if (name is None) != positional:
119 raise TranslationError(
120 'format string mixes positional and named placeholders',
121 )
122 return bool(positional)
123
124 a = _parse(format)
125 b = _parse(alternative)
126
127 if not a:
128 return
129
130 # now check if both strings are positional or named
131 a_positional = _check_positional(a)
132 b_positional = _check_positional(b)
133 if a_positional and not b_positional and not b:
134 raise TranslationError('placeholders are incompatible')
135 elif a_positional != b_positional:
136 raise TranslationError('the format strings are of different kinds')
137
138 # if we are operating on positional strings both must have the
139 # same number of format chars and those must be compatible
140 if a_positional:
141 if len(a) != len(b):
142 raise TranslationError('positional format placeholders are unbalanced')
143 for idx, ((_, first), (_, second)) in enumerate(zip(a, b)):
144 if not _compatible(first, second):
145 raise TranslationError(
146 f'incompatible format for placeholder {idx + 1:d}: '
147 f'{first!r} and {second!r} are not compatible',
148 )
149
150 # otherwise the second string must not have names the first one
151 # doesn't have and the types of those included must be compatible
152 else:
153 type_map = dict(a)
154 for name, typechar in b:
155 if name not in type_map:
156 raise TranslationError(f'unknown named placeholder {name!r}')
157 elif not _compatible(typechar, type_map[name]):
158 raise TranslationError(
159 f'incompatible format for placeholder {name!r}: '
160 f'{typechar!r} and {type_map[name]!r} are not compatible',
161 )
162
163
164 def _find_checkers() -> list[Callable[[Catalog | None, Message], object]]:
165 from babel.messages._compat import find_entrypoints
166
167 checkers: list[Callable[[Catalog | None, Message], object]] = []
168 checkers.extend(load() for (name, load) in find_entrypoints('babel.checkers'))
169 if len(checkers) == 0:
170 # if entrypoints are not available or no usable egg-info was found
171 # (see #230), just resort to hard-coded checkers
172 return [num_plurals, python_format]
173 return checkers
174
175
176 checkers: list[Callable[[Catalog | None, Message], object]] = _find_checkers()