gettext.py 21 KB

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