PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/gettext.py

https://bitbucket.org/kcr/pypy
Python | 591 lines | 444 code | 50 blank | 97 comment | 91 complexity | 05665e8bc713314b3bfe28abe86bb3f7 MD5 | raw file
Possible License(s): Apache-2.0
  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, copy, os, re, struct, sys
  44. from errno import ENOENT
  45. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  46. 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
  47. 'dgettext', 'dngettext', 'gettext', 'ngettext',
  48. ]
  49. _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
  50. def test(condition, true, false):
  51. """
  52. Implements the C expression:
  53. condition ? true : false
  54. Required to correctly interpret plural forms.
  55. """
  56. if condition:
  57. return true
  58. else:
  59. return false
  60. def c2py(plural):
  61. """Gets a C expression as used in PO files for plural forms and returns a
  62. Python lambda function that implements an equivalent expression.
  63. """
  64. # Security check, allow only the "n" identifier
  65. try:
  66. from cStringIO import StringIO
  67. except ImportError:
  68. from StringIO import StringIO
  69. import token, tokenize
  70. tokens = tokenize.generate_tokens(StringIO(plural).readline)
  71. try:
  72. danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
  73. except tokenize.TokenError:
  74. raise ValueError, \
  75. 'plural forms expression error, maybe unbalanced parenthesis'
  76. else:
  77. if danger:
  78. raise ValueError, 'plural forms expression could be dangerous'
  79. # Replace some C operators by their Python equivalents
  80. plural = plural.replace('&&', ' and ')
  81. plural = plural.replace('||', ' or ')
  82. expr = re.compile(r'\!([^=])')
  83. plural = expr.sub(' not \\1', plural)
  84. # Regular expression and replacement function used to transform
  85. # "a?b:c" to "test(a,b,c)".
  86. expr = re.compile(r'(.*?)\?(.*?):(.*)')
  87. def repl(x):
  88. return "test(%s, %s, %s)" % (x.group(1), x.group(2),
  89. expr.sub(repl, x.group(3)))
  90. # Code to transform the plural expression, taking care of parentheses
  91. stack = ['']
  92. for c in plural:
  93. if c == '(':
  94. stack.append('')
  95. elif c == ')':
  96. if len(stack) == 1:
  97. # Actually, we never reach this code, because unbalanced
  98. # parentheses get caught in the security check at the
  99. # beginning.
  100. raise ValueError, 'unbalanced parenthesis in plural form'
  101. s = expr.sub(repl, stack.pop())
  102. stack[-1] += '(%s)' % s
  103. else:
  104. stack[-1] += c
  105. plural = expr.sub(repl, stack.pop())
  106. return eval('lambda n: int(%s)' % plural)
  107. def _expand_lang(locale):
  108. from locale import normalize
  109. locale = normalize(locale)
  110. COMPONENT_CODESET = 1 << 0
  111. COMPONENT_TERRITORY = 1 << 1
  112. COMPONENT_MODIFIER = 1 << 2
  113. # split up the locale into its base components
  114. mask = 0
  115. pos = locale.find('@')
  116. if pos >= 0:
  117. modifier = locale[pos:]
  118. locale = locale[:pos]
  119. mask |= COMPONENT_MODIFIER
  120. else:
  121. modifier = ''
  122. pos = locale.find('.')
  123. if pos >= 0:
  124. codeset = locale[pos:]
  125. locale = locale[:pos]
  126. mask |= COMPONENT_CODESET
  127. else:
  128. codeset = ''
  129. pos = locale.find('_')
  130. if pos >= 0:
  131. territory = locale[pos:]
  132. locale = locale[:pos]
  133. mask |= COMPONENT_TERRITORY
  134. else:
  135. territory = ''
  136. language = locale
  137. ret = []
  138. for i in range(mask+1):
  139. if not (i & ~mask): # if all components for this combo exist ...
  140. val = language
  141. if i & COMPONENT_TERRITORY: val += territory
  142. if i & COMPONENT_CODESET: val += codeset
  143. if i & COMPONENT_MODIFIER: val += modifier
  144. ret.append(val)
  145. ret.reverse()
  146. return ret
  147. class NullTranslations:
  148. def __init__(self, fp=None):
  149. self._info = {}
  150. self._charset = None
  151. self._output_charset = None
  152. self._fallback = None
  153. if fp is not None:
  154. self._parse(fp)
  155. def _parse(self, fp):
  156. pass
  157. def add_fallback(self, fallback):
  158. if self._fallback:
  159. self._fallback.add_fallback(fallback)
  160. else:
  161. self._fallback = fallback
  162. def gettext(self, message):
  163. if self._fallback:
  164. return self._fallback.gettext(message)
  165. return message
  166. def lgettext(self, message):
  167. if self._fallback:
  168. return self._fallback.lgettext(message)
  169. return message
  170. def ngettext(self, msgid1, msgid2, n):
  171. if self._fallback:
  172. return self._fallback.ngettext(msgid1, msgid2, n)
  173. if n == 1:
  174. return msgid1
  175. else:
  176. return msgid2
  177. def lngettext(self, msgid1, msgid2, n):
  178. if self._fallback:
  179. return self._fallback.lngettext(msgid1, msgid2, n)
  180. if n == 1:
  181. return msgid1
  182. else:
  183. return msgid2
  184. def ugettext(self, message):
  185. if self._fallback:
  186. return self._fallback.ugettext(message)
  187. return unicode(message)
  188. def ungettext(self, msgid1, msgid2, n):
  189. if self._fallback:
  190. return self._fallback.ungettext(msgid1, msgid2, n)
  191. if n == 1:
  192. return unicode(msgid1)
  193. else:
  194. return unicode(msgid2)
  195. def info(self):
  196. return self._info
  197. def charset(self):
  198. return self._charset
  199. def output_charset(self):
  200. return self._output_charset
  201. def set_output_charset(self, charset):
  202. self._output_charset = charset
  203. def install(self, unicode=False, names=None):
  204. import __builtin__
  205. __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
  206. if hasattr(names, "__contains__"):
  207. if "gettext" in names:
  208. __builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
  209. if "ngettext" in names:
  210. __builtin__.__dict__['ngettext'] = (unicode and self.ungettext
  211. or self.ngettext)
  212. if "lgettext" in names:
  213. __builtin__.__dict__['lgettext'] = self.lgettext
  214. if "lngettext" in names:
  215. __builtin__.__dict__['lngettext'] = self.lngettext
  216. class GNUTranslations(NullTranslations):
  217. # Magic number of .mo files
  218. LE_MAGIC = 0x950412deL
  219. BE_MAGIC = 0xde120495L
  220. def _parse(self, fp):
  221. """Override this method to support alternative .mo formats."""
  222. unpack = struct.unpack
  223. filename = getattr(fp, 'name', '')
  224. # Parse the .mo file header, which consists of 5 little endian 32
  225. # bit words.
  226. self._catalog = catalog = {}
  227. self.plural = lambda n: int(n != 1) # germanic plural by default
  228. buf = fp.read()
  229. buflen = len(buf)
  230. # Are we big endian or little endian?
  231. magic = unpack('<I', buf[:4])[0]
  232. if magic == self.LE_MAGIC:
  233. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  234. ii = '<II'
  235. elif magic == self.BE_MAGIC:
  236. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  237. ii = '>II'
  238. else:
  239. raise IOError(0, 'Bad magic number', filename)
  240. # Now put all messages from the .mo file buffer into the catalog
  241. # dictionary.
  242. for i in xrange(0, msgcount):
  243. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  244. mend = moff + mlen
  245. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  246. tend = toff + tlen
  247. if mend < buflen and tend < buflen:
  248. msg = buf[moff:mend]
  249. tmsg = buf[toff:tend]
  250. else:
  251. raise IOError(0, 'File is corrupt', filename)
  252. # See if we're looking at GNU .mo conventions for metadata
  253. if mlen == 0:
  254. # Catalog description
  255. lastk = k = None
  256. for item in tmsg.splitlines():
  257. item = item.strip()
  258. if not item:
  259. continue
  260. if ':' in item:
  261. k, v = item.split(':', 1)
  262. k = k.strip().lower()
  263. v = v.strip()
  264. self._info[k] = v
  265. lastk = k
  266. elif lastk:
  267. self._info[lastk] += '\n' + item
  268. if k == 'content-type':
  269. self._charset = v.split('charset=')[1]
  270. elif k == 'plural-forms':
  271. v = v.split(';')
  272. plural = v[1].split('plural=')[1]
  273. self.plural = c2py(plural)
  274. # Note: we unconditionally convert both msgids and msgstrs to
  275. # Unicode using the character encoding specified in the charset
  276. # parameter of the Content-Type header. The gettext documentation
  277. # strongly encourages msgids to be us-ascii, but some applications
  278. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  279. # traditional gettext applications, the msgid conversion will
  280. # cause no problems since us-ascii should always be a subset of
  281. # the charset encoding. We may want to fall back to 8-bit msgids
  282. # if the Unicode conversion fails.
  283. if '\x00' in msg:
  284. # Plural forms
  285. msgid1, msgid2 = msg.split('\x00')
  286. tmsg = tmsg.split('\x00')
  287. if self._charset:
  288. msgid1 = unicode(msgid1, self._charset)
  289. tmsg = [unicode(x, self._charset) for x in tmsg]
  290. for i in range(len(tmsg)):
  291. catalog[(msgid1, i)] = tmsg[i]
  292. else:
  293. if self._charset:
  294. msg = unicode(msg, self._charset)
  295. tmsg = unicode(tmsg, self._charset)
  296. catalog[msg] = tmsg
  297. # advance to next entry in the seek tables
  298. masteridx += 8
  299. transidx += 8
  300. def gettext(self, message):
  301. missing = object()
  302. tmsg = self._catalog.get(message, missing)
  303. if tmsg is missing:
  304. if self._fallback:
  305. return self._fallback.gettext(message)
  306. return message
  307. # Encode the Unicode tmsg back to an 8-bit string, if possible
  308. if self._output_charset:
  309. return tmsg.encode(self._output_charset)
  310. elif self._charset:
  311. return tmsg.encode(self._charset)
  312. return tmsg
  313. def lgettext(self, message):
  314. missing = object()
  315. tmsg = self._catalog.get(message, missing)
  316. if tmsg is missing:
  317. if self._fallback:
  318. return self._fallback.lgettext(message)
  319. return message
  320. if self._output_charset:
  321. return tmsg.encode(self._output_charset)
  322. return tmsg.encode(locale.getpreferredencoding())
  323. def ngettext(self, msgid1, msgid2, n):
  324. try:
  325. tmsg = self._catalog[(msgid1, self.plural(n))]
  326. if self._output_charset:
  327. return tmsg.encode(self._output_charset)
  328. elif self._charset:
  329. return tmsg.encode(self._charset)
  330. return tmsg
  331. except KeyError:
  332. if self._fallback:
  333. return self._fallback.ngettext(msgid1, msgid2, n)
  334. if n == 1:
  335. return msgid1
  336. else:
  337. return msgid2
  338. def lngettext(self, msgid1, msgid2, n):
  339. try:
  340. tmsg = self._catalog[(msgid1, self.plural(n))]
  341. if self._output_charset:
  342. return tmsg.encode(self._output_charset)
  343. return tmsg.encode(locale.getpreferredencoding())
  344. except KeyError:
  345. if self._fallback:
  346. return self._fallback.lngettext(msgid1, msgid2, n)
  347. if n == 1:
  348. return msgid1
  349. else:
  350. return msgid2
  351. def ugettext(self, message):
  352. missing = object()
  353. tmsg = self._catalog.get(message, missing)
  354. if tmsg is missing:
  355. if self._fallback:
  356. return self._fallback.ugettext(message)
  357. return unicode(message)
  358. return tmsg
  359. def ungettext(self, msgid1, msgid2, n):
  360. try:
  361. tmsg = self._catalog[(msgid1, self.plural(n))]
  362. except KeyError:
  363. if self._fallback:
  364. return self._fallback.ungettext(msgid1, msgid2, n)
  365. if n == 1:
  366. tmsg = unicode(msgid1)
  367. else:
  368. tmsg = unicode(msgid2)
  369. return tmsg
  370. # Locate a .mo file using the gettext strategy
  371. def find(domain, localedir=None, languages=None, all=0):
  372. # Get some reasonable defaults for arguments that were not supplied
  373. if localedir is None:
  374. localedir = _default_localedir
  375. if languages is None:
  376. languages = []
  377. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  378. val = os.environ.get(envar)
  379. if val:
  380. languages = val.split(':')
  381. break
  382. if 'C' not in languages:
  383. languages.append('C')
  384. # now normalize and expand the languages
  385. nelangs = []
  386. for lang in languages:
  387. for nelang in _expand_lang(lang):
  388. if nelang not in nelangs:
  389. nelangs.append(nelang)
  390. # select a language
  391. if all:
  392. result = []
  393. else:
  394. result = None
  395. for lang in nelangs:
  396. if lang == 'C':
  397. break
  398. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  399. if os.path.exists(mofile):
  400. if all:
  401. result.append(mofile)
  402. else:
  403. return mofile
  404. return result
  405. # a mapping between absolute .mo file path and Translation object
  406. _translations = {}
  407. def translation(domain, localedir=None, languages=None,
  408. class_=None, fallback=False, codeset=None):
  409. if class_ is None:
  410. class_ = GNUTranslations
  411. mofiles = find(domain, localedir, languages, all=1)
  412. if not mofiles:
  413. if fallback:
  414. return NullTranslations()
  415. raise IOError(ENOENT, 'No translation file found for domain', domain)
  416. # Avoid opening, reading, and parsing the .mo file after it's been done
  417. # once.
  418. result = None
  419. for mofile in mofiles:
  420. key = (class_, os.path.abspath(mofile))
  421. t = _translations.get(key)
  422. if t is None:
  423. with open(mofile, 'rb') as fp:
  424. t = _translations.setdefault(key, class_(fp))
  425. # Copy the translation object to allow setting fallbacks and
  426. # output charset. All other instance data is shared with the
  427. # cached object.
  428. t = copy.copy(t)
  429. if codeset:
  430. t.set_output_charset(codeset)
  431. if result is None:
  432. result = t
  433. else:
  434. result.add_fallback(t)
  435. return result
  436. def install(domain, localedir=None, unicode=False, codeset=None, names=None):
  437. t = translation(domain, localedir, fallback=True, codeset=codeset)
  438. t.install(unicode, names)
  439. # a mapping b/w domains and locale directories
  440. _localedirs = {}
  441. # a mapping b/w domains and codesets
  442. _localecodesets = {}
  443. # current global domain, `messages' used for compatibility w/ GNU gettext
  444. _current_domain = 'messages'
  445. def textdomain(domain=None):
  446. global _current_domain
  447. if domain is not None:
  448. _current_domain = domain
  449. return _current_domain
  450. def bindtextdomain(domain, localedir=None):
  451. global _localedirs
  452. if localedir is not None:
  453. _localedirs[domain] = localedir
  454. return _localedirs.get(domain, _default_localedir)
  455. def bind_textdomain_codeset(domain, codeset=None):
  456. global _localecodesets
  457. if codeset is not None:
  458. _localecodesets[domain] = codeset
  459. return _localecodesets.get(domain)
  460. def dgettext(domain, message):
  461. try:
  462. t = translation(domain, _localedirs.get(domain, None),
  463. codeset=_localecodesets.get(domain))
  464. except IOError:
  465. return message
  466. return t.gettext(message)
  467. def ldgettext(domain, message):
  468. try:
  469. t = translation(domain, _localedirs.get(domain, None),
  470. codeset=_localecodesets.get(domain))
  471. except IOError:
  472. return message
  473. return t.lgettext(message)
  474. def dngettext(domain, msgid1, msgid2, n):
  475. try:
  476. t = translation(domain, _localedirs.get(domain, None),
  477. codeset=_localecodesets.get(domain))
  478. except IOError:
  479. if n == 1:
  480. return msgid1
  481. else:
  482. return msgid2
  483. return t.ngettext(msgid1, msgid2, n)
  484. def ldngettext(domain, msgid1, msgid2, n):
  485. try:
  486. t = translation(domain, _localedirs.get(domain, None),
  487. codeset=_localecodesets.get(domain))
  488. except IOError:
  489. if n == 1:
  490. return msgid1
  491. else:
  492. return msgid2
  493. return t.lngettext(msgid1, msgid2, n)
  494. def gettext(message):
  495. return dgettext(_current_domain, message)
  496. def lgettext(message):
  497. return ldgettext(_current_domain, message)
  498. def ngettext(msgid1, msgid2, n):
  499. return dngettext(_current_domain, msgid1, msgid2, n)
  500. def lngettext(msgid1, msgid2, n):
  501. return ldngettext(_current_domain, msgid1, msgid2, n)
  502. # dcgettext() has been deemed unnecessary and is not implemented.
  503. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  504. # was:
  505. #
  506. # import gettext
  507. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  508. # _ = cat.gettext
  509. # print _('Hello World')
  510. # The resulting catalog object currently don't support access through a
  511. # dictionary API, which was supported (but apparently unused) in GNOME
  512. # gettext.
  513. Catalog = translation