gettext.py 21 KB

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