gettext.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 os
  44. import re
  45. import sys
  46. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  47. 'bindtextdomain', 'find', 'translation', 'install',
  48. 'textdomain', 'dgettext', 'dngettext', 'gettext',
  49. 'ngettext', 'pgettext', 'dpgettext', 'npgettext',
  50. 'dnpgettext'
  51. ]
  52. _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
  53. # Expression parsing for plural form selection.
  54. #
  55. # The gettext library supports a small subset of C syntax. The only
  56. # incompatible difference is that integer literals starting with zero are
  57. # decimal.
  58. #
  59. # https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
  60. # http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
  61. _token_pattern = re.compile(r"""
  62. (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
  63. (?P<NUMBER>[0-9]+\b) | # decimal integer
  64. (?P<NAME>n\b) | # only n is allowed
  65. (?P<PARENTHESIS>[()]) |
  66. (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
  67. # <=, >=, ==, !=, &&, ||,
  68. # ? :
  69. # unary and bitwise ops
  70. # not allowed
  71. (?P<INVALID>\w+|.) # invalid token
  72. """, re.VERBOSE|re.DOTALL)
  73. def _tokenize(plural):
  74. for mo in re.finditer(_token_pattern, plural):
  75. kind = mo.lastgroup
  76. if kind == 'WHITESPACES':
  77. continue
  78. value = mo.group(kind)
  79. if kind == 'INVALID':
  80. raise ValueError('invalid token in plural form: %s' % value)
  81. yield value
  82. yield ''
  83. def _error(value):
  84. if value:
  85. return ValueError('unexpected token in plural form: %s' % value)
  86. else:
  87. return ValueError('unexpected end of plural form')
  88. _binary_ops = (
  89. ('||',),
  90. ('&&',),
  91. ('==', '!='),
  92. ('<', '>', '<=', '>='),
  93. ('+', '-'),
  94. ('*', '/', '%'),
  95. )
  96. _binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
  97. _c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
  98. def _parse(tokens, priority=-1):
  99. result = ''
  100. nexttok = next(tokens)
  101. while nexttok == '!':
  102. result += 'not '
  103. nexttok = next(tokens)
  104. if nexttok == '(':
  105. sub, nexttok = _parse(tokens)
  106. result = '%s(%s)' % (result, sub)
  107. if nexttok != ')':
  108. raise ValueError('unbalanced parenthesis in plural form')
  109. elif nexttok == 'n':
  110. result = '%s%s' % (result, nexttok)
  111. else:
  112. try:
  113. value = int(nexttok, 10)
  114. except ValueError:
  115. raise _error(nexttok) from None
  116. result = '%s%d' % (result, value)
  117. nexttok = next(tokens)
  118. j = 100
  119. while nexttok in _binary_ops:
  120. i = _binary_ops[nexttok]
  121. if i < priority:
  122. break
  123. # Break chained comparisons
  124. if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
  125. result = '(%s)' % result
  126. # Replace some C operators by their Python equivalents
  127. op = _c2py_ops.get(nexttok, nexttok)
  128. right, nexttok = _parse(tokens, i + 1)
  129. result = '%s %s %s' % (result, op, right)
  130. j = i
  131. if j == priority == 4: # '<', '>', '<=', '>='
  132. result = '(%s)' % result
  133. if nexttok == '?' and priority <= 0:
  134. if_true, nexttok = _parse(tokens, 0)
  135. if nexttok != ':':
  136. raise _error(nexttok)
  137. if_false, nexttok = _parse(tokens)
  138. result = '%s if %s else %s' % (if_true, result, if_false)
  139. if priority == 0:
  140. result = '(%s)' % result
  141. return result, nexttok
  142. def _as_int(n):
  143. try:
  144. i = round(n)
  145. except TypeError:
  146. raise TypeError('Plural value must be an integer, got %s' %
  147. (n.__class__.__name__,)) from None
  148. import warnings
  149. warnings.warn('Plural value must be an integer, got %s' %
  150. (n.__class__.__name__,),
  151. DeprecationWarning, 4)
  152. return n
  153. def c2py(plural):
  154. """Gets a C expression as used in PO files for plural forms and returns a
  155. Python function that implements an equivalent expression.
  156. """
  157. if len(plural) > 1000:
  158. raise ValueError('plural form expression is too long')
  159. try:
  160. result, nexttok = _parse(_tokenize(plural))
  161. if nexttok:
  162. raise _error(nexttok)
  163. depth = 0
  164. for c in result:
  165. if c == '(':
  166. depth += 1
  167. if depth > 20:
  168. # Python compiler limit is about 90.
  169. # The most complex example has 2.
  170. raise ValueError('plural form expression is too complex')
  171. elif c == ')':
  172. depth -= 1
  173. ns = {'_as_int': _as_int}
  174. exec('''if True:
  175. def func(n):
  176. if not isinstance(n, int):
  177. n = _as_int(n)
  178. return int(%s)
  179. ''' % result, ns)
  180. return ns['func']
  181. except RecursionError:
  182. # Recursion error can be raised in _parse() or exec().
  183. raise ValueError('plural form expression is too complex')
  184. def _expand_lang(loc):
  185. import locale
  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._fallback = None
  229. if fp is not None:
  230. self._parse(fp)
  231. def _parse(self, fp):
  232. pass
  233. def add_fallback(self, fallback):
  234. if self._fallback:
  235. self._fallback.add_fallback(fallback)
  236. else:
  237. self._fallback = fallback
  238. def gettext(self, message):
  239. if self._fallback:
  240. return self._fallback.gettext(message)
  241. return message
  242. def ngettext(self, msgid1, msgid2, n):
  243. if self._fallback:
  244. return self._fallback.ngettext(msgid1, msgid2, n)
  245. if n == 1:
  246. return msgid1
  247. else:
  248. return msgid2
  249. def pgettext(self, context, message):
  250. if self._fallback:
  251. return self._fallback.pgettext(context, message)
  252. return message
  253. def npgettext(self, context, msgid1, msgid2, n):
  254. if self._fallback:
  255. return self._fallback.npgettext(context, msgid1, msgid2, n)
  256. if n == 1:
  257. return msgid1
  258. else:
  259. return msgid2
  260. def info(self):
  261. return self._info
  262. def charset(self):
  263. return self._charset
  264. def install(self, names=None):
  265. import builtins
  266. builtins.__dict__['_'] = self.gettext
  267. if names is not None:
  268. allowed = {'gettext', 'ngettext', 'npgettext', 'pgettext'}
  269. for name in allowed & set(names):
  270. builtins.__dict__[name] = getattr(self, name)
  271. class GNUTranslations(NullTranslations):
  272. # Magic number of .mo files
  273. LE_MAGIC = 0x950412de
  274. BE_MAGIC = 0xde120495
  275. # The encoding of a msgctxt and a msgid in a .mo file is
  276. # msgctxt + "\x04" + msgid (gettext version >= 0.15)
  277. CONTEXT = "%s\x04%s"
  278. # Acceptable .mo versions
  279. VERSIONS = (0, 1)
  280. def _get_versions(self, version):
  281. """Returns a tuple of major version, minor version"""
  282. return (version >> 16, version & 0xffff)
  283. def _parse(self, fp):
  284. """Override this method to support alternative .mo formats."""
  285. # Delay struct import for speeding up gettext import when .mo files
  286. # are not used.
  287. from struct import unpack
  288. filename = getattr(fp, 'name', '')
  289. # Parse the .mo file header, which consists of 5 little endian 32
  290. # bit words.
  291. self._catalog = catalog = {}
  292. self.plural = lambda n: int(n != 1) # germanic plural by default
  293. buf = fp.read()
  294. buflen = len(buf)
  295. # Are we big endian or little endian?
  296. magic = unpack('<I', buf[:4])[0]
  297. if magic == self.LE_MAGIC:
  298. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  299. ii = '<II'
  300. elif magic == self.BE_MAGIC:
  301. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  302. ii = '>II'
  303. else:
  304. raise OSError(0, 'Bad magic number', filename)
  305. major_version, minor_version = self._get_versions(version)
  306. if major_version not in self.VERSIONS:
  307. raise OSError(0, 'Bad version number ' + str(major_version), filename)
  308. # Now put all messages from the .mo file buffer into the catalog
  309. # dictionary.
  310. for i in range(0, msgcount):
  311. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  312. mend = moff + mlen
  313. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  314. tend = toff + tlen
  315. if mend < buflen and tend < buflen:
  316. msg = buf[moff:mend]
  317. tmsg = buf[toff:tend]
  318. else:
  319. raise OSError(0, 'File is corrupt', filename)
  320. # See if we're looking at GNU .mo conventions for metadata
  321. if mlen == 0:
  322. # Catalog description
  323. lastk = None
  324. for b_item in tmsg.split(b'\n'):
  325. item = b_item.decode().strip()
  326. if not item:
  327. continue
  328. # Skip over comment lines:
  329. if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
  330. continue
  331. k = v = None
  332. if ':' in item:
  333. k, v = item.split(':', 1)
  334. k = k.strip().lower()
  335. v = v.strip()
  336. self._info[k] = v
  337. lastk = k
  338. elif lastk:
  339. self._info[lastk] += '\n' + item
  340. if k == 'content-type':
  341. self._charset = v.split('charset=')[1]
  342. elif k == 'plural-forms':
  343. v = v.split(';')
  344. plural = v[1].split('plural=')[1]
  345. self.plural = c2py(plural)
  346. # Note: we unconditionally convert both msgids and msgstrs to
  347. # Unicode using the character encoding specified in the charset
  348. # parameter of the Content-Type header. The gettext documentation
  349. # strongly encourages msgids to be us-ascii, but some applications
  350. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  351. # traditional gettext applications, the msgid conversion will
  352. # cause no problems since us-ascii should always be a subset of
  353. # the charset encoding. We may want to fall back to 8-bit msgids
  354. # if the Unicode conversion fails.
  355. charset = self._charset or 'ascii'
  356. if b'\x00' in msg:
  357. # Plural forms
  358. msgid1, msgid2 = msg.split(b'\x00')
  359. tmsg = tmsg.split(b'\x00')
  360. msgid1 = str(msgid1, charset)
  361. for i, x in enumerate(tmsg):
  362. catalog[(msgid1, i)] = str(x, charset)
  363. else:
  364. catalog[str(msg, charset)] = str(tmsg, charset)
  365. # advance to next entry in the seek tables
  366. masteridx += 8
  367. transidx += 8
  368. def gettext(self, message):
  369. missing = object()
  370. tmsg = self._catalog.get(message, missing)
  371. if tmsg is missing:
  372. tmsg = self._catalog.get((message, self.plural(1)), missing)
  373. if tmsg is not missing:
  374. return tmsg
  375. if self._fallback:
  376. return self._fallback.gettext(message)
  377. return message
  378. def ngettext(self, msgid1, msgid2, n):
  379. try:
  380. tmsg = self._catalog[(msgid1, self.plural(n))]
  381. except KeyError:
  382. if self._fallback:
  383. return self._fallback.ngettext(msgid1, msgid2, n)
  384. if n == 1:
  385. tmsg = msgid1
  386. else:
  387. tmsg = msgid2
  388. return tmsg
  389. def pgettext(self, context, message):
  390. ctxt_msg_id = self.CONTEXT % (context, message)
  391. missing = object()
  392. tmsg = self._catalog.get(ctxt_msg_id, missing)
  393. if tmsg is missing:
  394. tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing)
  395. if tmsg is not missing:
  396. return tmsg
  397. if self._fallback:
  398. return self._fallback.pgettext(context, message)
  399. return message
  400. def npgettext(self, context, msgid1, msgid2, n):
  401. ctxt_msg_id = self.CONTEXT % (context, msgid1)
  402. try:
  403. tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
  404. except KeyError:
  405. if self._fallback:
  406. return self._fallback.npgettext(context, msgid1, msgid2, n)
  407. if n == 1:
  408. tmsg = msgid1
  409. else:
  410. tmsg = msgid2
  411. return tmsg
  412. # Locate a .mo file using the gettext strategy
  413. def find(domain, localedir=None, languages=None, all=False):
  414. # Get some reasonable defaults for arguments that were not supplied
  415. if localedir is None:
  416. localedir = _default_localedir
  417. if languages is None:
  418. languages = []
  419. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  420. val = os.environ.get(envar)
  421. if val:
  422. languages = val.split(':')
  423. break
  424. if 'C' not in languages:
  425. languages.append('C')
  426. # now normalize and expand the languages
  427. nelangs = []
  428. for lang in languages:
  429. for nelang in _expand_lang(lang):
  430. if nelang not in nelangs:
  431. nelangs.append(nelang)
  432. # select a language
  433. if all:
  434. result = []
  435. else:
  436. result = None
  437. for lang in nelangs:
  438. if lang == 'C':
  439. break
  440. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  441. if os.path.exists(mofile):
  442. if all:
  443. result.append(mofile)
  444. else:
  445. return mofile
  446. return result
  447. # a mapping between absolute .mo file path and Translation object
  448. _translations = {}
  449. def translation(domain, localedir=None, languages=None,
  450. class_=None, fallback=False):
  451. if class_ is None:
  452. class_ = GNUTranslations
  453. mofiles = find(domain, localedir, languages, all=True)
  454. if not mofiles:
  455. if fallback:
  456. return NullTranslations()
  457. from errno import ENOENT
  458. raise FileNotFoundError(ENOENT,
  459. 'No translation file found for domain', domain)
  460. # Avoid opening, reading, and parsing the .mo file after it's been done
  461. # once.
  462. result = None
  463. for mofile in mofiles:
  464. key = (class_, os.path.abspath(mofile))
  465. t = _translations.get(key)
  466. if t is None:
  467. with open(mofile, 'rb') as fp:
  468. t = _translations.setdefault(key, class_(fp))
  469. # Copy the translation object to allow setting fallbacks and
  470. # output charset. All other instance data is shared with the
  471. # cached object.
  472. # Delay copy import for speeding up gettext import when .mo files
  473. # are not used.
  474. import copy
  475. t = copy.copy(t)
  476. if result is None:
  477. result = t
  478. else:
  479. result.add_fallback(t)
  480. return result
  481. def install(domain, localedir=None, *, names=None):
  482. t = translation(domain, localedir, fallback=True)
  483. t.install(names)
  484. # a mapping b/w domains and locale directories
  485. _localedirs = {}
  486. # current global domain, `messages' used for compatibility w/ GNU gettext
  487. _current_domain = 'messages'
  488. def textdomain(domain=None):
  489. global _current_domain
  490. if domain is not None:
  491. _current_domain = domain
  492. return _current_domain
  493. def bindtextdomain(domain, localedir=None):
  494. global _localedirs
  495. if localedir is not None:
  496. _localedirs[domain] = localedir
  497. return _localedirs.get(domain, _default_localedir)
  498. def dgettext(domain, message):
  499. try:
  500. t = translation(domain, _localedirs.get(domain, None))
  501. except OSError:
  502. return message
  503. return t.gettext(message)
  504. def dngettext(domain, msgid1, msgid2, n):
  505. try:
  506. t = translation(domain, _localedirs.get(domain, None))
  507. except OSError:
  508. if n == 1:
  509. return msgid1
  510. else:
  511. return msgid2
  512. return t.ngettext(msgid1, msgid2, n)
  513. def dpgettext(domain, context, message):
  514. try:
  515. t = translation(domain, _localedirs.get(domain, None))
  516. except OSError:
  517. return message
  518. return t.pgettext(context, message)
  519. def dnpgettext(domain, context, msgid1, msgid2, n):
  520. try:
  521. t = translation(domain, _localedirs.get(domain, None))
  522. except OSError:
  523. if n == 1:
  524. return msgid1
  525. else:
  526. return msgid2
  527. return t.npgettext(context, msgid1, msgid2, n)
  528. def gettext(message):
  529. return dgettext(_current_domain, message)
  530. def ngettext(msgid1, msgid2, n):
  531. return dngettext(_current_domain, msgid1, msgid2, n)
  532. def pgettext(context, message):
  533. return dpgettext(_current_domain, context, message)
  534. def npgettext(context, msgid1, msgid2, n):
  535. return dnpgettext(_current_domain, context, msgid1, msgid2, n)
  536. # dcgettext() has been deemed unnecessary and is not implemented.
  537. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  538. # was:
  539. #
  540. # import gettext
  541. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  542. # _ = cat.gettext
  543. # print _('Hello World')
  544. # The resulting catalog object currently don't support access through a
  545. # dictionary API, which was supported (but apparently unused) in GNOME
  546. # gettext.
  547. Catalog = translation