Debian Codegraph @

lib-python/3/gettext.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 """Internationalization and localization support.
2
3 This module provides internationalization (I18N) and localization (L10N)
4 support for your Python programs by providing an interface to the GNU gettext
5 message catalog library.
6
7 I18N refers to the operation by which a program is made aware of multiple
8 languages. L10N refers to the adaptation of your program, once
9 internationalized, to the local language and cultural habits.
10
11 """
12
13 # This module represents the integration of work, contributions, feedback, and
14 # suggestions from the following people:
15 #
16 # Martin von Loewis, who wrote the initial implementation of the underlying
17 # C-based libintlmodule (later renamed _gettext), along with a skeletal
18 # gettext.py implementation.
19 #
20 # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
21 # which also included a pure-Python implementation to read .mo files if
22 # intlmodule wasn't available.
23 #
24 # James Henstridge, who also wrote a gettext.py module, which has some
25 # interesting, but currently unsupported experimental features: the notion of
26 # a Catalog class and instances, and the ability to add to a catalog file via
27 # a Python API.
28 #
29 # Barry Warsaw integrated these modules, wrote the .install() API and code,
30 # and conformed all C and Python code to Python's coding standards.
31 #
32 # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
33 # module.
34 #
35 # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
36 #
37 # TODO:
38 # - Lazy loading of .mo files. Currently the entire catalog is loaded into
39 # memory, but that's probably bad for large translated programs. Instead,
40 # the lexical sort of original strings in GNU .mo files should be exploited
41 # to do binary searches and lazy initializations. Or you might want to use
42 # the undocumented double-hash algorithm for .mo files with hash tables, but
43 # you'll need to study the GNU gettext code to do this.
44 #
45 # - Support Solaris .mo file formats. Unfortunately, we've been unable to
46 # find this format documented anywhere.
47
48
49 import operator
50 import os
51 import re
52 import sys
53
54
55 __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
56 'bindtextdomain', 'find', 'translation', 'install',
57 'textdomain', 'dgettext', 'dngettext', 'gettext',
58 'ngettext', 'pgettext', 'dpgettext', 'npgettext',
59 'dnpgettext'
60 ]
61
62 try:
63 _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
64 except AttributeError:
65 pass # pypy: sys.base_prefix is not set if pypy3-c is issuing
66 # "Library path not found, using compiled-in sys.path"
67
68 # Expression parsing for plural form selection.
69 #
70 # The gettext library supports a small subset of C syntax. The only
71 # incompatible difference is that integer literals starting with zero are
72 # decimal.
73 #
74 # https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
75 # http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
76
77 _token_pattern = re.compile(r"""
78 (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
79 (?P<NUMBER>[0-9]+\b) | # decimal integer
80 (?P<NAME>n\b) | # only n is allowed
81 (?P<PARENTHESIS>[()]) |
82 (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
83 # <=, >=, ==, !=, &&, ||,
84 # ? :
85 # unary and bitwise ops
86 # not allowed
87 (?P<INVALID>\w+|.) # invalid token
88 """, re.VERBOSE|re.DOTALL)
89
90
91 def _tokenize(plural):
92 for mo in re.finditer(_token_pattern, plural):
93 kind = mo.lastgroup
94 if kind == 'WHITESPACES':
95 continue
96 value = mo.group(kind)
97 if kind == 'INVALID':
98 raise ValueError('invalid token in plural form: %s' % value)
99 yield value
100 yield ''
101
102
103 def _error(value):
104 if value:
105 return ValueError('unexpected token in plural form: %s' % value)
106 else:
107 return ValueError('unexpected end of plural form')
108
109
110 _binary_ops = (
111 ('||',),
112 ('&&',),
113 ('==', '!='),
114 ('<', '>', '<=', '>='),
115 ('+', '-'),
116 ('*', '/', '%'),
117 )
118 _binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
119 _c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
120
121
122 def _parse(tokens, priority=-1):
123 result = ''
124 nexttok = next(tokens)
125 while nexttok == '!':
126 result += 'not '
127 nexttok = next(tokens)
128
129 if nexttok == '(':
130 sub, nexttok = _parse(tokens)
131 result = '%s(%s)' % (result, sub)
132 if nexttok != ')':
133 raise ValueError('unbalanced parenthesis in plural form')
134 elif nexttok == 'n':
135 result = '%s%s' % (result, nexttok)
136 else:
137 try:
138 value = int(nexttok, 10)
139 except ValueError:
140 raise _error(nexttok) from None
141 result = '%s%d' % (result, value)
142 nexttok = next(tokens)
143
144 j = 100
145 while nexttok in _binary_ops:
146 i = _binary_ops[nexttok]
147 if i < priority:
148 break
149 # Break chained comparisons
150 if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
151 result = '(%s)' % result
152 # Replace some C operators by their Python equivalents
153 op = _c2py_ops.get(nexttok, nexttok)
154 right, nexttok = _parse(tokens, i + 1)
155 result = '%s %s %s' % (result, op, right)
156 j = i
157 if j == priority == 4: # '<', '>', '<=', '>='
158 result = '(%s)' % result
159
160 if nexttok == '?' and priority <= 0:
161 if_true, nexttok = _parse(tokens, 0)
162 if nexttok != ':':
163 raise _error(nexttok)
164 if_false, nexttok = _parse(tokens)
165 result = '%s if %s else %s' % (if_true, result, if_false)
166 if priority == 0:
167 result = '(%s)' % result
168
169 return result, nexttok
170
171
172 def _as_int(n):
173 try:
174 round(n)
175 except TypeError:
176 raise TypeError('Plural value must be an integer, got %s' %
177 (n.__class__.__name__,)) from None
178
179 import warnings
180 frame = sys._getframe(1)
181 stacklevel = 2
182 while frame.f_back is not None and frame.f_globals.get('__name__') == __name__:
183 stacklevel += 1
184 frame = frame.f_back
185 warnings.warn('Plural value must be an integer, got %s' %
186 (n.__class__.__name__,),
187 DeprecationWarning,
188 stacklevel)
189 return n
190
191
192 def c2py(plural):
193 """Gets a C expression as used in PO files for plural forms and returns a
194 Python function that implements an equivalent expression.
195 """
196
197 if len(plural) > 1000:
198 raise ValueError('plural form expression is too long')
199 try:
200 result, nexttok = _parse(_tokenize(plural))
201 if nexttok:
202 raise _error(nexttok)
203
204 depth = 0
205 for c in result:
206 if c == '(':
207 depth += 1
208 if depth > 20:
209 # Python compiler limit is about 90.
210 # The most complex example has 2.
211 raise ValueError('plural form expression is too complex')
212 elif c == ')':
213 depth -= 1
214
215 ns = {'_as_int': _as_int, '__name__': __name__}
216 exec('''if True:
217 def func(n):
218 if not isinstance(n, int):
219 n = _as_int(n)
220 return int(%s)
221 ''' % result, ns)
222 return ns['func']
223 except RecursionError:
224 # Recursion error can be raised in _parse() or exec().
225 raise ValueError('plural form expression is too complex')
226
227
228 def _expand_lang(loc):
229 import locale
230 loc = locale.normalize(loc)
231 COMPONENT_CODESET = 1 << 0
232 COMPONENT_TERRITORY = 1 << 1
233 COMPONENT_MODIFIER = 1 << 2
234 # split up the locale into its base components
235 mask = 0
236 pos = loc.find('@')
237 if pos >= 0:
238 modifier = loc[pos:]
239 loc = loc[:pos]
240 mask |= COMPONENT_MODIFIER
241 else:
242 modifier = ''
243 pos = loc.find('.')
244 if pos >= 0:
245 codeset = loc[pos:]
246 loc = loc[:pos]
247 mask |= COMPONENT_CODESET
248 else:
249 codeset = ''
250 pos = loc.find('_')
251 if pos >= 0:
252 territory = loc[pos:]
253 loc = loc[:pos]
254 mask |= COMPONENT_TERRITORY
255 else:
256 territory = ''
257 language = loc
258 ret = []
259 for i in range(mask+1):
260 if not (i & ~mask): # if all components for this combo exist ...
261 val = language
262 if i & COMPONENT_TERRITORY: val += territory
263 if i & COMPONENT_CODESET: val += codeset
264 if i & COMPONENT_MODIFIER: val += modifier
265 ret.append(val)
266 ret.reverse()
267 return ret
268
269
270 class NullTranslations:
271 def __init__(self, fp=None):
272 self._info = {}
273 self._charset = None
274 self._fallback = None
275 if fp is not None:
276 self._parse(fp)
277
278 def _parse(self, fp):
279 pass
280
281 def add_fallback(self, fallback):
282 if self._fallback:
283 self._fallback.add_fallback(fallback)
284 else:
285 self._fallback = fallback
286
287 def gettext(self, message):
288 if self._fallback:
289 return self._fallback.gettext(message)
290 return message
291
292 def ngettext(self, msgid1, msgid2, n):
293 if self._fallback:
294 return self._fallback.ngettext(msgid1, msgid2, n)
295 if n == 1:
296 return msgid1
297 else:
298 return msgid2
299
300 def pgettext(self, context, message):
301 if self._fallback:
302 return self._fallback.pgettext(context, message)
303 return message
304
305 def npgettext(self, context, msgid1, msgid2, n):
306 if self._fallback:
307 return self._fallback.npgettext(context, msgid1, msgid2, n)
308 if n == 1:
309 return msgid1
310 else:
311 return msgid2
312
313 def info(self):
314 return self._info
315
316 def charset(self):
317 return self._charset
318
319 def install(self, names=None):
320 import builtins
321 builtins.__dict__['_'] = self.gettext
322 if names is not None:
323 allowed = {'gettext', 'ngettext', 'npgettext', 'pgettext'}
324 for name in allowed & set(names):
325 builtins.__dict__[name] = getattr(self, name)
326
327
328 class GNUTranslations(NullTranslations):
329 # Magic number of .mo files
330 LE_MAGIC = 0x950412de
331 BE_MAGIC = 0xde120495
332
333 # The encoding of a msgctxt and a msgid in a .mo file is
334 # msgctxt + "\x04" + msgid (gettext version >= 0.15)
335 CONTEXT = "%s\x04%s"
336
337 # Acceptable .mo versions
338 VERSIONS = (0, 1)
339
340 def _get_versions(self, version):
341 """Returns a tuple of major version, minor version"""
342 return (version >> 16, version & 0xffff)
343
344 def _parse(self, fp):
345 """Override this method to support alternative .mo formats."""
346 # Delay struct import for speeding up gettext import when .mo files
347 # are not used.
348 from struct import unpack
349 filename = getattr(fp, 'name', '')
350 # Parse the .mo file header, which consists of 5 little endian 32
351 # bit words.
352 self._catalog = catalog = {}
353 self.plural = lambda n: int(n != 1) # germanic plural by default
354 buf = fp.read()
355 buflen = len(buf)
356 # Are we big endian or little endian?
357 magic = unpack('<I', buf[:4])[0]
358 if magic == self.LE_MAGIC:
359 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
360 ii = '<II'
361 elif magic == self.BE_MAGIC:
362 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
363 ii = '>II'
364 else:
365 raise OSError(0, 'Bad magic number', filename)
366
367 major_version, minor_version = self._get_versions(version)
368
369 if major_version not in self.VERSIONS:
370 raise OSError(0, 'Bad version number ' + str(major_version), filename)
371
372 # Now put all messages from the .mo file buffer into the catalog
373 # dictionary.
374 for i in range(0, msgcount):
375 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
376 mend = moff + mlen
377 tlen, toff = unpack(ii, buf[transidx:transidx+8])
378 tend = toff + tlen
379 if mend < buflen and tend < buflen:
380 msg = buf[moff:mend]
381 tmsg = buf[toff:tend]
382 else:
383 raise OSError(0, 'File is corrupt', filename)
384 # See if we're looking at GNU .mo conventions for metadata
385 if mlen == 0:
386 # Catalog description
387 lastk = None
388 for b_item in tmsg.split(b'\n'):
389 item = b_item.decode().strip()
390 if not item:
391 continue
392 # Skip over comment lines:
393 if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
394 continue
395 k = v = None
396 if ':' in item:
397 k, v = item.split(':', 1)
398 k = k.strip().lower()
399 v = v.strip()
400 self._info[k] = v
401 lastk = k
402 elif lastk:
403 self._info[lastk] += '\n' + item
404 if k == 'content-type':
405 self._charset = v.split('charset=')[1]
406 elif k == 'plural-forms':
407 v = v.split(';')
408 plural = v[1].split('plural=')[1]
409 self.plural = c2py(plural)
410 # Note: we unconditionally convert both msgids and msgstrs to
411 # Unicode using the character encoding specified in the charset
412 # parameter of the Content-Type header. The gettext documentation
413 # strongly encourages msgids to be us-ascii, but some applications
414 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
415 # traditional gettext applications, the msgid conversion will
416 # cause no problems since us-ascii should always be a subset of
417 # the charset encoding. We may want to fall back to 8-bit msgids
418 # if the Unicode conversion fails.
419 charset = self._charset or 'ascii'
420 if b'\x00' in msg:
421 # Plural forms
422 msgid1, msgid2 = msg.split(b'\x00')
423 tmsg = tmsg.split(b'\x00')
424 msgid1 = str(msgid1, charset)
425 for i, x in enumerate(tmsg):
426 catalog[(msgid1, i)] = str(x, charset)
427 else:
428 catalog[str(msg, charset)] = str(tmsg, charset)
429 # advance to next entry in the seek tables
430 masteridx += 8
431 transidx += 8
432
433 def gettext(self, message):
434 missing = object()
435 tmsg = self._catalog.get(message, missing)
436 if tmsg is missing:
437 tmsg = self._catalog.get((message, self.plural(1)), missing)
438 if tmsg is not missing:
439 return tmsg
440 if self._fallback:
441 return self._fallback.gettext(message)
442 return message
443
444 def ngettext(self, msgid1, msgid2, n):
445 try:
446 tmsg = self._catalog[(msgid1, self.plural(n))]
447 except KeyError:
448 if self._fallback:
449 return self._fallback.ngettext(msgid1, msgid2, n)
450 if n == 1:
451 tmsg = msgid1
452 else:
453 tmsg = msgid2
454 return tmsg
455
456 def pgettext(self, context, message):
457 ctxt_msg_id = self.CONTEXT % (context, message)
458 missing = object()
459 tmsg = self._catalog.get(ctxt_msg_id, missing)
460 if tmsg is missing:
461 tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing)
462 if tmsg is not missing:
463 return tmsg
464 if self._fallback:
465 return self._fallback.pgettext(context, message)
466 return message
467
468 def npgettext(self, context, msgid1, msgid2, n):
469 ctxt_msg_id = self.CONTEXT % (context, msgid1)
470 try:
471 tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
472 except KeyError:
473 if self._fallback:
474 return self._fallback.npgettext(context, msgid1, msgid2, n)
475 if n == 1:
476 tmsg = msgid1
477 else:
478 tmsg = msgid2
479 return tmsg
480
481
482 # Locate a .mo file using the gettext strategy
483 def find(domain, localedir=None, languages=None, all=False):
484 # Get some reasonable defaults for arguments that were not supplied
485 if localedir is None:
486 localedir = _default_localedir
487 if languages is None:
488 languages = []
489 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
490 val = os.environ.get(envar)
491 if val:
492 languages = val.split(':')
493 break
494 if 'C' not in languages:
495 languages.append('C')
496 # now normalize and expand the languages
497 nelangs = []
498 for lang in languages:
499 for nelang in _expand_lang(lang):
500 if nelang not in nelangs:
501 nelangs.append(nelang)
502 # select a language
503 if all:
504 result = []
505 else:
506 result = None
507 for lang in nelangs:
508 if lang == 'C':
509 break
510 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
•511 mofile_lp = os.path.join("/usr/share/locale-langpack", lang,
512 'LC_MESSAGES', '%s.mo' % domain)
513
514 # first look into the standard locale dir, then into the
515 # langpack locale dir
516
517 # standard mo file
518 if os.path.exists(mofile):
519 if all:
520 result.append(mofile)
521 else:
522 return mofile
•523
524 # langpack mofile -> use it
525 if os.path.exists(mofile_lp):
526 if all:
527 result.append(mofile_lp)
528 else:
529 return mofile_lp
530
531 return result
532
533
534 # a mapping between absolute .mo file path and Translation object
535 _translations = {}
536
537
538 def translation(domain, localedir=None, languages=None,
539 class_=None, fallback=False):
540 if class_ is None:
541 class_ = GNUTranslations
542 mofiles = find(domain, localedir, languages, all=True)
543 if not mofiles:
544 if fallback:
545 return NullTranslations()
546 from errno import ENOENT
547 raise FileNotFoundError(ENOENT,
548 'No translation file found for domain', domain)
549 # Avoid opening, reading, and parsing the .mo file after it's been done
550 # once.
551 result = None
552 for mofile in mofiles:
553 key = (class_, os.path.abspath(mofile))
554 t = _translations.get(key)
555 if t is None:
556 with open(mofile, 'rb') as fp:
557 t = _translations.setdefault(key, class_(fp))
558 # Copy the translation object to allow setting fallbacks and
559 # output charset. All other instance data is shared with the
560 # cached object.
561 # Delay copy import for speeding up gettext import when .mo files
562 # are not used.
563 import copy
564 t = copy.copy(t)
565 if result is None:
566 result = t
567 else:
568 result.add_fallback(t)
569 return result
570
571
572 def install(domain, localedir=None, *, names=None):
573 t = translation(domain, localedir, fallback=True)
574 t.install(names)
575
576
577 # a mapping b/w domains and locale directories
578 _localedirs = {}
579 # current global domain, `messages' used for compatibility w/ GNU gettext
580 _current_domain = 'messages'
581
582
583 def textdomain(domain=None):
584 global _current_domain
585 if domain is not None:
586 _current_domain = domain
587 return _current_domain
588
589
590 def bindtextdomain(domain, localedir=None):
591 global _localedirs
592 if localedir is not None:
593 _localedirs[domain] = localedir
594 return _localedirs.get(domain, _default_localedir)
595
596
597 def dgettext(domain, message):
598 try:
599 t = translation(domain, _localedirs.get(domain, None))
600 except OSError:
601 return message
602 return t.gettext(message)
603
604
605 def dngettext(domain, msgid1, msgid2, n):
606 try:
607 t = translation(domain, _localedirs.get(domain, None))
608 except OSError:
609 if n == 1:
610 return msgid1
611 else:
612 return msgid2
613 return t.ngettext(msgid1, msgid2, n)
614
615
616 def dpgettext(domain, context, message):
617 try:
618 t = translation(domain, _localedirs.get(domain, None))
619 except OSError:
620 return message
621 return t.pgettext(context, message)
622
623
624 def dnpgettext(domain, context, msgid1, msgid2, n):
625 try:
626 t = translation(domain, _localedirs.get(domain, None))
627 except OSError:
628 if n == 1:
629 return msgid1
630 else:
631 return msgid2
632 return t.npgettext(context, msgid1, msgid2, n)
633
634
635 def gettext(message):
636 return dgettext(_current_domain, message)
637
638
639 def ngettext(msgid1, msgid2, n):
640 return dngettext(_current_domain, msgid1, msgid2, n)
641
642
643 def pgettext(context, message):
644 return dpgettext(_current_domain, context, message)
645
646
647 def npgettext(context, msgid1, msgid2, n):
648 return dnpgettext(_current_domain, context, msgid1, msgid2, n)
649
650
651 # dcgettext() has been deemed unnecessary and is not implemented.
652
653 # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
654 # was:
655 #
656 # import gettext
657 # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
658 # _ = cat.gettext
659 # print _('Hello World')
660
661 # The resulting catalog object currently don't support access through a
662 # dictionary API, which was supported (but apparently unused) in GNOME
663 # gettext.
664
665 Catalog = translation