PageRenderTime 47ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/i18n/polib.py

https://bitbucket.org/mirror/mercurial/
Python | 1639 lines | 1558 code | 19 blank | 62 comment | 42 complexity | eadf227319c19f56026c8da6e6e157e9 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. # -*- coding: utf-8 -*-
  2. # no-check-code
  3. #
  4. # License: MIT (see LICENSE file provided)
  5. # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
  6. """
  7. **polib** allows you to manipulate, create, modify gettext files (pot, po and
  8. mo files). You can load existing files, iterate through it's entries, add,
  9. modify entries, comments or metadata, etc. or create new po files from scratch.
  10. **polib** provides a simple and pythonic API via the :func:`~polib.pofile` and
  11. :func:`~polib.mofile` convenience functions.
  12. """
  13. __author__ = 'David Jean Louis <izimobil@gmail.com>'
  14. __version__ = '0.6.4'
  15. __all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
  16. 'detect_encoding', 'escape', 'unescape', 'detect_encoding',]
  17. import array
  18. import codecs
  19. import os
  20. import re
  21. import struct
  22. import sys
  23. import textwrap
  24. import types
  25. # the default encoding to use when encoding cannot be detected
  26. default_encoding = 'utf-8'
  27. # _pofile_or_mofile {{{
  28. def _pofile_or_mofile(f, type, **kwargs):
  29. """
  30. Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to
  31. honor the DRY concept.
  32. """
  33. # get the file encoding
  34. enc = kwargs.get('encoding')
  35. if enc is None:
  36. enc = detect_encoding(f, type == 'mofile')
  37. # parse the file
  38. kls = type == 'pofile' and _POFileParser or _MOFileParser
  39. parser = kls(
  40. f,
  41. encoding=enc,
  42. check_for_duplicates=kwargs.get('check_for_duplicates', False)
  43. )
  44. instance = parser.parse()
  45. instance.wrapwidth = kwargs.get('wrapwidth', 78)
  46. return instance
  47. # }}}
  48. # function pofile() {{{
  49. def pofile(pofile, **kwargs):
  50. """
  51. Convenience function that parses the po or pot file ``pofile`` and returns
  52. a :class:`~polib.POFile` instance.
  53. Arguments:
  54. ``pofile``
  55. string, full or relative path to the po/pot file or its content (data).
  56. ``wrapwidth``
  57. integer, the wrap width, only useful when the ``-w`` option was passed
  58. to xgettext (optional, default: ``78``).
  59. ``encoding``
  60. string, the encoding to use (e.g. "utf-8") (default: ``None``, the
  61. encoding will be auto-detected).
  62. ``check_for_duplicates``
  63. whether to check for duplicate entries when adding entries to the
  64. file (optional, default: ``False``).
  65. """
  66. return _pofile_or_mofile(pofile, 'pofile', **kwargs)
  67. # }}}
  68. # function mofile() {{{
  69. def mofile(mofile, **kwargs):
  70. """
  71. Convenience function that parses the mo file ``mofile`` and returns a
  72. :class:`~polib.MOFile` instance.
  73. Arguments:
  74. ``mofile``
  75. string, full or relative path to the mo file or its content (data).
  76. ``wrapwidth``
  77. integer, the wrap width, only useful when the ``-w`` option was passed
  78. to xgettext to generate the po file that was used to format the mo file
  79. (optional, default: ``78``).
  80. ``encoding``
  81. string, the encoding to use (e.g. "utf-8") (default: ``None``, the
  82. encoding will be auto-detected).
  83. ``check_for_duplicates``
  84. whether to check for duplicate entries when adding entries to the
  85. file (optional, default: ``False``).
  86. """
  87. return _pofile_or_mofile(mofile, 'mofile', **kwargs)
  88. # }}}
  89. # function detect_encoding() {{{
  90. def detect_encoding(file, binary_mode=False):
  91. """
  92. Try to detect the encoding used by the ``file``. The ``file`` argument can
  93. be a PO or MO file path or a string containing the contents of the file.
  94. If the encoding cannot be detected, the function will return the value of
  95. ``default_encoding``.
  96. Arguments:
  97. ``file``
  98. string, full or relative path to the po/mo file or its content.
  99. ``binary_mode``
  100. boolean, set this to True if ``file`` is a mo file.
  101. """
  102. rx = re.compile(r'"?Content-Type:.+? charset=([\w_\-:\.]+)')
  103. def charset_exists(charset):
  104. """Check whether ``charset`` is valid or not."""
  105. try:
  106. codecs.lookup(charset)
  107. except LookupError:
  108. return False
  109. return True
  110. if not os.path.exists(file):
  111. match = rx.search(file)
  112. if match:
  113. enc = match.group(1).strip()
  114. if charset_exists(enc):
  115. return enc
  116. else:
  117. if binary_mode:
  118. mode = 'rb'
  119. else:
  120. mode = 'r'
  121. f = open(file, mode)
  122. for l in f.readlines():
  123. match = rx.search(l)
  124. if match:
  125. f.close()
  126. enc = match.group(1).strip()
  127. if charset_exists(enc):
  128. return enc
  129. f.close()
  130. return default_encoding
  131. # }}}
  132. # function escape() {{{
  133. def escape(st):
  134. """
  135. Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
  136. the given string ``st`` and returns it.
  137. """
  138. return st.replace('\\', r'\\')\
  139. .replace('\t', r'\t')\
  140. .replace('\r', r'\r')\
  141. .replace('\n', r'\n')\
  142. .replace('\"', r'\"')
  143. # }}}
  144. # function unescape() {{{
  145. def unescape(st):
  146. """
  147. Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
  148. the given string ``st`` and returns it.
  149. """
  150. def unescape_repl(m):
  151. m = m.group(1)
  152. if m == 'n':
  153. return '\n'
  154. if m == 't':
  155. return '\t'
  156. if m == 'r':
  157. return '\r'
  158. if m == '\\':
  159. return '\\'
  160. return m # handles escaped double quote
  161. return re.sub(r'\\(\\|n|t|r|")', unescape_repl, st)
  162. # }}}
  163. # class _BaseFile {{{
  164. class _BaseFile(list):
  165. """
  166. Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile`
  167. classes. This class should **not** be instanciated directly.
  168. """
  169. def __init__(self, *args, **kwargs):
  170. """
  171. Constructor, accepts the following keyword arguments:
  172. ``pofile``
  173. string, the path to the po or mo file, or its content as a string.
  174. ``wrapwidth``
  175. integer, the wrap width, only useful when the ``-w`` option was
  176. passed to xgettext (optional, default: ``78``).
  177. ``encoding``
  178. string, the encoding to use, defaults to ``default_encoding``
  179. global variable (optional).
  180. ``check_for_duplicates``
  181. whether to check for duplicate entries when adding entries to the
  182. file, (optional, default: ``False``).
  183. """
  184. list.__init__(self)
  185. # the opened file handle
  186. pofile = kwargs.get('pofile', None)
  187. if pofile and os.path.exists(pofile):
  188. self.fpath = pofile
  189. else:
  190. self.fpath = kwargs.get('fpath')
  191. # the width at which lines should be wrapped
  192. self.wrapwidth = kwargs.get('wrapwidth', 78)
  193. # the file encoding
  194. self.encoding = kwargs.get('encoding', default_encoding)
  195. # whether to check for duplicate entries or not
  196. self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
  197. # header
  198. self.header = ''
  199. # both po and mo files have metadata
  200. self.metadata = {}
  201. self.metadata_is_fuzzy = 0
  202. def __unicode__(self):
  203. """
  204. Returns the unicode representation of the file.
  205. """
  206. ret = []
  207. entries = [self.metadata_as_entry()] + \
  208. [e for e in self if not e.obsolete]
  209. for entry in entries:
  210. ret.append(entry.__unicode__(self.wrapwidth))
  211. for entry in self.obsolete_entries():
  212. ret.append(entry.__unicode__(self.wrapwidth))
  213. ret = '\n'.join(ret)
  214. if type(ret) != types.UnicodeType:
  215. return unicode(ret, self.encoding)
  216. return ret
  217. def __str__(self):
  218. """
  219. Returns the string representation of the file.
  220. """
  221. return unicode(self).encode(self.encoding)
  222. def __contains__(self, entry):
  223. """
  224. Overriden ``list`` method to implement the membership test (in and
  225. not in).
  226. The method considers that an entry is in the file if it finds an entry
  227. that has the same msgid (the test is **case sensitive**).
  228. Argument:
  229. ``entry``
  230. an instance of :class:`~polib._BaseEntry`.
  231. """
  232. return self.find(entry.msgid, by='msgid') is not None
  233. def __eq__(self, other):
  234. return unicode(self) == unicode(other)
  235. def append(self, entry):
  236. """
  237. Overriden method to check for duplicates entries, if a user tries to
  238. add an entry that is already in the file, the method will raise a
  239. ``ValueError`` exception.
  240. Argument:
  241. ``entry``
  242. an instance of :class:`~polib._BaseEntry`.
  243. """
  244. if self.check_for_duplicates and entry in self:
  245. raise ValueError('Entry "%s" already exists' % entry.msgid)
  246. super(_BaseFile, self).append(entry)
  247. def insert(self, index, entry):
  248. """
  249. Overriden method to check for duplicates entries, if a user tries to
  250. add an entry that is already in the file, the method will raise a
  251. ``ValueError`` exception.
  252. Arguments:
  253. ``index``
  254. index at which the entry should be inserted.
  255. ``entry``
  256. an instance of :class:`~polib._BaseEntry`.
  257. """
  258. if self.check_for_duplicates and entry in self:
  259. raise ValueError('Entry "%s" already exists' % entry.msgid)
  260. super(_BaseFile, self).insert(index, entry)
  261. def metadata_as_entry(self):
  262. """
  263. Returns the file metadata as a :class:`~polib.POFile` instance.
  264. """
  265. e = POEntry(msgid='')
  266. mdata = self.ordered_metadata()
  267. if mdata:
  268. strs = []
  269. for name, value in mdata:
  270. # Strip whitespace off each line in a multi-line entry
  271. strs.append('%s: %s' % (name, value))
  272. e.msgstr = '\n'.join(strs) + '\n'
  273. if self.metadata_is_fuzzy:
  274. e.flags.append('fuzzy')
  275. return e
  276. def save(self, fpath=None, repr_method='__str__'):
  277. """
  278. Saves the po file to ``fpath``.
  279. If it is an existing file and no ``fpath`` is provided, then the
  280. existing file is rewritten with the modified data.
  281. Keyword arguments:
  282. ``fpath``
  283. string, full or relative path to the file.
  284. ``repr_method``
  285. string, the method to use for output.
  286. """
  287. if self.fpath is None and fpath is None:
  288. raise IOError('You must provide a file path to save() method')
  289. contents = getattr(self, repr_method)()
  290. if fpath is None:
  291. fpath = self.fpath
  292. if repr_method == 'to_binary':
  293. fhandle = open(fpath, 'wb')
  294. else:
  295. fhandle = codecs.open(fpath, 'w', self.encoding)
  296. if type(contents) != types.UnicodeType:
  297. contents = contents.decode(self.encoding)
  298. fhandle.write(contents)
  299. fhandle.close()
  300. # set the file path if not set
  301. if self.fpath is None and fpath:
  302. self.fpath = fpath
  303. def find(self, st, by='msgid', include_obsolete_entries=False,
  304. msgctxt=False):
  305. """
  306. Find the entry which msgid (or property identified by the ``by``
  307. argument) matches the string ``st``.
  308. Keyword arguments:
  309. ``st``
  310. string, the string to search for.
  311. ``by``
  312. string, the property to use for comparison (default: ``msgid``).
  313. ``include_obsolete_entries``
  314. boolean, whether to also search in entries that are obsolete.
  315. ``msgctxt``
  316. string, allows to specify a specific message context for the
  317. search.
  318. """
  319. if include_obsolete_entries:
  320. entries = self[:]
  321. else:
  322. entries = [e for e in self if not e.obsolete]
  323. for e in entries:
  324. if getattr(e, by) == st:
  325. if msgctxt and e.msgctxt != msgctxt:
  326. continue
  327. return e
  328. return None
  329. def ordered_metadata(self):
  330. """
  331. Convenience method that returns an ordered version of the metadata
  332. dictionnary. The return value is list of tuples (metadata name,
  333. metadata_value).
  334. """
  335. # copy the dict first
  336. metadata = self.metadata.copy()
  337. data_order = [
  338. 'Project-Id-Version',
  339. 'Report-Msgid-Bugs-To',
  340. 'POT-Creation-Date',
  341. 'PO-Revision-Date',
  342. 'Last-Translator',
  343. 'Language-Team',
  344. 'MIME-Version',
  345. 'Content-Type',
  346. 'Content-Transfer-Encoding'
  347. ]
  348. ordered_data = []
  349. for data in data_order:
  350. try:
  351. value = metadata.pop(data)
  352. ordered_data.append((data, value))
  353. except KeyError:
  354. pass
  355. # the rest of the metadata will be alphabetically ordered since there
  356. # are no specs for this AFAIK
  357. keys = metadata.keys()
  358. keys.sort()
  359. for data in keys:
  360. value = metadata[data]
  361. ordered_data.append((data, value))
  362. return ordered_data
  363. def to_binary(self):
  364. """
  365. Return the binary representation of the file.
  366. """
  367. offsets = []
  368. entries = self.translated_entries()
  369. # the keys are sorted in the .mo file
  370. def cmp(_self, other):
  371. # msgfmt compares entries with msgctxt if it exists
  372. self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid
  373. other_msgid = other.msgctxt and other.msgctxt or other.msgid
  374. if self_msgid > other_msgid:
  375. return 1
  376. elif self_msgid < other_msgid:
  377. return -1
  378. else:
  379. return 0
  380. # add metadata entry
  381. entries.sort(cmp)
  382. mentry = self.metadata_as_entry()
  383. #mentry.msgstr = mentry.msgstr.replace('\\n', '').lstrip()
  384. entries = [mentry] + entries
  385. entries_len = len(entries)
  386. ids, strs = '', ''
  387. for e in entries:
  388. # For each string, we need size and file offset. Each string is
  389. # NUL terminated; the NUL does not count into the size.
  390. msgid = ''
  391. if e.msgctxt:
  392. # Contexts are stored by storing the concatenation of the
  393. # context, a <EOT> byte, and the original string
  394. msgid = self._encode(e.msgctxt + '\4')
  395. if e.msgid_plural:
  396. indexes = e.msgstr_plural.keys()
  397. indexes.sort()
  398. msgstr = []
  399. for index in indexes:
  400. msgstr.append(e.msgstr_plural[index])
  401. msgid += self._encode(e.msgid + '\0' + e.msgid_plural)
  402. msgstr = self._encode('\0'.join(msgstr))
  403. else:
  404. msgid += self._encode(e.msgid)
  405. msgstr = self._encode(e.msgstr)
  406. offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
  407. ids += msgid + '\0'
  408. strs += msgstr + '\0'
  409. # The header is 7 32-bit unsigned integers.
  410. keystart = 7*4+16*entries_len
  411. # and the values start after the keys
  412. valuestart = keystart + len(ids)
  413. koffsets = []
  414. voffsets = []
  415. # The string table first has the list of keys, then the list of values.
  416. # Each entry has first the size of the string, then the file offset.
  417. for o1, l1, o2, l2 in offsets:
  418. koffsets += [l1, o1+keystart]
  419. voffsets += [l2, o2+valuestart]
  420. offsets = koffsets + voffsets
  421. # check endianness for magic number
  422. if struct.pack('@h', 1) == struct.pack('<h', 1):
  423. magic_number = MOFile.LITTLE_ENDIAN
  424. else:
  425. magic_number = MOFile.BIG_ENDIAN
  426. output = struct.pack(
  427. "Iiiiiii",
  428. magic_number, # Magic number
  429. 0, # Version
  430. entries_len, # # of entries
  431. 7*4, # start of key index
  432. 7*4+entries_len*8, # start of value index
  433. 0, keystart # size and offset of hash table
  434. # Important: we don't use hash tables
  435. )
  436. output += array.array("i", offsets).tostring()
  437. output += ids
  438. output += strs
  439. return output
  440. def _encode(self, mixed):
  441. """
  442. Encodes the given ``mixed`` argument with the file encoding if and
  443. only if it's an unicode string and returns the encoded string.
  444. """
  445. if type(mixed) == types.UnicodeType:
  446. return mixed.encode(self.encoding)
  447. return mixed
  448. # }}}
  449. # class POFile {{{
  450. class POFile(_BaseFile):
  451. """
  452. Po (or Pot) file reader/writer.
  453. This class inherits the :class:`~polib._BaseFile` class and, by extension,
  454. the python ``list`` type.
  455. """
  456. def __unicode__(self):
  457. """
  458. Returns the unicode representation of the po file.
  459. """
  460. ret, headers = '', self.header.split('\n')
  461. for header in headers:
  462. if header[:1] in [',', ':']:
  463. ret += '#%s\n' % header
  464. else:
  465. ret += '# %s\n' % header
  466. if type(ret) != types.UnicodeType:
  467. ret = unicode(ret, self.encoding)
  468. return ret + _BaseFile.__unicode__(self)
  469. def save_as_mofile(self, fpath):
  470. """
  471. Saves the binary representation of the file to given ``fpath``.
  472. Keyword argument:
  473. ``fpath``
  474. string, full or relative path to the mo file.
  475. """
  476. _BaseFile.save(self, fpath, 'to_binary')
  477. def percent_translated(self):
  478. """
  479. Convenience method that returns the percentage of translated
  480. messages.
  481. """
  482. total = len([e for e in self if not e.obsolete])
  483. if total == 0:
  484. return 100
  485. translated = len(self.translated_entries())
  486. return int((100.00 / float(total)) * translated)
  487. def translated_entries(self):
  488. """
  489. Convenience method that returns the list of translated entries.
  490. """
  491. return [e for e in self if e.translated()]
  492. def untranslated_entries(self):
  493. """
  494. Convenience method that returns the list of untranslated entries.
  495. """
  496. return [e for e in self if not e.translated() and not e.obsolete \
  497. and not 'fuzzy' in e.flags]
  498. def fuzzy_entries(self):
  499. """
  500. Convenience method that returns the list of fuzzy entries.
  501. """
  502. return [e for e in self if 'fuzzy' in e.flags]
  503. def obsolete_entries(self):
  504. """
  505. Convenience method that returns the list of obsolete entries.
  506. """
  507. return [e for e in self if e.obsolete]
  508. def merge(self, refpot):
  509. """
  510. Convenience method that merges the current pofile with the pot file
  511. provided. It behaves exactly as the gettext msgmerge utility:
  512. * comments of this file will be preserved, but extracted comments and
  513. occurrences will be discarded;
  514. * any translations or comments in the file will be discarded, however,
  515. dot comments and file positions will be preserved;
  516. * the fuzzy flags are preserved.
  517. Keyword argument:
  518. ``refpot``
  519. object POFile, the reference catalog.
  520. """
  521. for entry in refpot:
  522. e = self.find(entry.msgid, include_obsolete_entries=True)
  523. if e is None:
  524. e = POEntry()
  525. self.append(e)
  526. e.merge(entry)
  527. # ok, now we must "obsolete" entries that are not in the refpot anymore
  528. for entry in self:
  529. if refpot.find(entry.msgid) is None:
  530. entry.obsolete = True
  531. # }}}
  532. # class MOFile {{{
  533. class MOFile(_BaseFile):
  534. """
  535. Mo file reader/writer.
  536. This class inherits the :class:`~polib._BaseFile` class and, by
  537. extension, the python ``list`` type.
  538. """
  539. BIG_ENDIAN = 0xde120495
  540. LITTLE_ENDIAN = 0x950412de
  541. def __init__(self, *args, **kwargs):
  542. """
  543. Constructor, accepts all keywords arguments accepted by
  544. :class:`~polib._BaseFile` class.
  545. """
  546. _BaseFile.__init__(self, *args, **kwargs)
  547. self.magic_number = None
  548. self.version = 0
  549. def save_as_pofile(self, fpath):
  550. """
  551. Saves the mofile as a pofile to ``fpath``.
  552. Keyword argument:
  553. ``fpath``
  554. string, full or relative path to the file.
  555. """
  556. _BaseFile.save(self, fpath)
  557. def save(self, fpath=None):
  558. """
  559. Saves the mofile to ``fpath``.
  560. Keyword argument:
  561. ``fpath``
  562. string, full or relative path to the file.
  563. """
  564. _BaseFile.save(self, fpath, 'to_binary')
  565. def percent_translated(self):
  566. """
  567. Convenience method to keep the same interface with POFile instances.
  568. """
  569. return 100
  570. def translated_entries(self):
  571. """
  572. Convenience method to keep the same interface with POFile instances.
  573. """
  574. return self
  575. def untranslated_entries(self):
  576. """
  577. Convenience method to keep the same interface with POFile instances.
  578. """
  579. return []
  580. def fuzzy_entries(self):
  581. """
  582. Convenience method to keep the same interface with POFile instances.
  583. """
  584. return []
  585. def obsolete_entries(self):
  586. """
  587. Convenience method to keep the same interface with POFile instances.
  588. """
  589. return []
  590. # }}}
  591. # class _BaseEntry {{{
  592. class _BaseEntry(object):
  593. """
  594. Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes.
  595. This class should **not** be instanciated directly.
  596. """
  597. def __init__(self, *args, **kwargs):
  598. """
  599. Constructor, accepts the following keyword arguments:
  600. ``msgid``
  601. string, the entry msgid.
  602. ``msgstr``
  603. string, the entry msgstr.
  604. ``msgid_plural``
  605. string, the entry msgid_plural.
  606. ``msgstr_plural``
  607. list, the entry msgstr_plural lines.
  608. ``msgctxt``
  609. string, the entry context (msgctxt).
  610. ``obsolete``
  611. bool, whether the entry is "obsolete" or not.
  612. ``encoding``
  613. string, the encoding to use, defaults to ``default_encoding``
  614. global variable (optional).
  615. """
  616. self.msgid = kwargs.get('msgid', '')
  617. self.msgstr = kwargs.get('msgstr', '')
  618. self.msgid_plural = kwargs.get('msgid_plural', '')
  619. self.msgstr_plural = kwargs.get('msgstr_plural', {})
  620. self.msgctxt = kwargs.get('msgctxt', None)
  621. self.obsolete = kwargs.get('obsolete', False)
  622. self.encoding = kwargs.get('encoding', default_encoding)
  623. def __unicode__(self, wrapwidth=78):
  624. """
  625. Returns the unicode representation of the entry.
  626. """
  627. if self.obsolete:
  628. delflag = '#~ '
  629. else:
  630. delflag = ''
  631. ret = []
  632. # write the msgctxt if any
  633. if self.msgctxt is not None:
  634. ret += self._str_field("msgctxt", delflag, "", self.msgctxt, wrapwidth)
  635. # write the msgid
  636. ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth)
  637. # write the msgid_plural if any
  638. if self.msgid_plural:
  639. ret += self._str_field("msgid_plural", delflag, "", self.msgid_plural, wrapwidth)
  640. if self.msgstr_plural:
  641. # write the msgstr_plural if any
  642. msgstrs = self.msgstr_plural
  643. keys = list(msgstrs)
  644. keys.sort()
  645. for index in keys:
  646. msgstr = msgstrs[index]
  647. plural_index = '[%s]' % index
  648. ret += self._str_field("msgstr", delflag, plural_index, msgstr, wrapwidth)
  649. else:
  650. # otherwise write the msgstr
  651. ret += self._str_field("msgstr", delflag, "", self.msgstr, wrapwidth)
  652. ret.append('')
  653. ret = '\n'.join(ret)
  654. if type(ret) != types.UnicodeType:
  655. return unicode(ret, self.encoding)
  656. return ret
  657. def __str__(self):
  658. """
  659. Returns the string representation of the entry.
  660. """
  661. return unicode(self).encode(self.encoding)
  662. def __eq__(self, other):
  663. return unicode(self) == unicode(other)
  664. def _str_field(self, fieldname, delflag, plural_index, field, wrapwidth=78):
  665. lines = field.splitlines(True)
  666. if len(lines) > 1:
  667. lines = [''] + lines # start with initial empty line
  668. else:
  669. escaped_field = escape(field)
  670. specialchars_count = 0
  671. for c in ['\\', '\n', '\r', '\t', '"']:
  672. specialchars_count += field.count(c)
  673. # comparison must take into account fieldname length + one space
  674. # + 2 quotes (eg. msgid "<string>")
  675. flength = len(fieldname) + 3
  676. if plural_index:
  677. flength += len(plural_index)
  678. real_wrapwidth = wrapwidth - flength + specialchars_count
  679. if wrapwidth > 0 and len(field) > real_wrapwidth:
  680. # Wrap the line but take field name into account
  681. lines = [''] + [unescape(item) for item in wrap(
  682. escaped_field,
  683. wrapwidth - 2, # 2 for quotes ""
  684. drop_whitespace=False,
  685. break_long_words=False
  686. )]
  687. else:
  688. lines = [field]
  689. if fieldname.startswith('previous_'):
  690. # quick and dirty trick to get the real field name
  691. fieldname = fieldname[9:]
  692. ret = ['%s%s%s "%s"' % (delflag, fieldname, plural_index,
  693. escape(lines.pop(0)))]
  694. for mstr in lines:
  695. ret.append('%s"%s"' % (delflag, escape(mstr)))
  696. return ret
  697. # }}}
  698. # class POEntry {{{
  699. class POEntry(_BaseEntry):
  700. """
  701. Represents a po file entry.
  702. """
  703. def __init__(self, *args, **kwargs):
  704. """
  705. Constructor, accepts the following keyword arguments:
  706. ``comment``
  707. string, the entry comment.
  708. ``tcomment``
  709. string, the entry translator comment.
  710. ``occurrences``
  711. list, the entry occurrences.
  712. ``flags``
  713. list, the entry flags.
  714. ``previous_msgctxt``
  715. string, the entry previous context.
  716. ``previous_msgid``
  717. string, the entry previous msgid.
  718. ``previous_msgid_plural``
  719. string, the entry previous msgid_plural.
  720. """
  721. _BaseEntry.__init__(self, *args, **kwargs)
  722. self.comment = kwargs.get('comment', '')
  723. self.tcomment = kwargs.get('tcomment', '')
  724. self.occurrences = kwargs.get('occurrences', [])
  725. self.flags = kwargs.get('flags', [])
  726. self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
  727. self.previous_msgid = kwargs.get('previous_msgid', None)
  728. self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)
  729. def __unicode__(self, wrapwidth=78):
  730. """
  731. Returns the unicode representation of the entry.
  732. """
  733. if self.obsolete:
  734. return _BaseEntry.__unicode__(self, wrapwidth)
  735. ret = []
  736. # comments first, if any (with text wrapping as xgettext does)
  737. comments = [('comment', '#. '), ('tcomment', '# ')]
  738. for c in comments:
  739. val = getattr(self, c[0])
  740. if val:
  741. for comment in val.split('\n'):
  742. if wrapwidth > 0 and len(comment) + len(c[1]) > wrapwidth:
  743. ret += wrap(
  744. comment,
  745. wrapwidth,
  746. initial_indent=c[1],
  747. subsequent_indent=c[1],
  748. break_long_words=False
  749. )
  750. else:
  751. ret.append('%s%s' % (c[1], comment))
  752. # occurrences (with text wrapping as xgettext does)
  753. if self.occurrences:
  754. filelist = []
  755. for fpath, lineno in self.occurrences:
  756. if lineno:
  757. filelist.append('%s:%s' % (fpath, lineno))
  758. else:
  759. filelist.append(fpath)
  760. filestr = ' '.join(filelist)
  761. if wrapwidth > 0 and len(filestr) + 3 > wrapwidth:
  762. # textwrap split words that contain hyphen, this is not
  763. # what we want for filenames, so the dirty hack is to
  764. # temporally replace hyphens with a char that a file cannot
  765. # contain, like "*"
  766. ret += [l.replace('*', '-') for l in wrap(
  767. filestr.replace('-', '*'),
  768. wrapwidth,
  769. initial_indent='#: ',
  770. subsequent_indent='#: ',
  771. break_long_words=False
  772. )]
  773. else:
  774. ret.append('#: ' + filestr)
  775. # flags (TODO: wrapping ?)
  776. if self.flags:
  777. ret.append('#, %s' % ', '.join(self.flags))
  778. # previous context and previous msgid/msgid_plural
  779. fields = ['previous_msgctxt', 'previous_msgid', 'previous_msgid_plural']
  780. for f in fields:
  781. val = getattr(self, f)
  782. if val:
  783. ret += self._str_field(f, "#| ", "", val, wrapwidth)
  784. ret.append(_BaseEntry.__unicode__(self, wrapwidth))
  785. ret = '\n'.join(ret)
  786. if type(ret) != types.UnicodeType:
  787. return unicode(ret, self.encoding)
  788. return ret
  789. def __cmp__(self, other):
  790. """
  791. Called by comparison operations if rich comparison is not defined.
  792. """
  793. def compare_occurrences(a, b):
  794. """
  795. Compare an entry occurrence with another one.
  796. """
  797. if a[0] != b[0]:
  798. return a[0] < b[0]
  799. if a[1] != b[1]:
  800. return a[1] < b[1]
  801. return 0
  802. # First: Obsolete test
  803. if self.obsolete != other.obsolete:
  804. if self.obsolete:
  805. return -1
  806. else:
  807. return 1
  808. # Work on a copy to protect original
  809. occ1 = self.occurrences[:]
  810. occ2 = other.occurrences[:]
  811. # Sorting using compare method
  812. occ1.sort(compare_occurrences)
  813. occ2.sort(compare_occurrences)
  814. # Comparing sorted occurrences
  815. pos = 0
  816. for entry1 in occ1:
  817. try:
  818. entry2 = occ2[pos]
  819. except IndexError:
  820. return 1
  821. pos = pos + 1
  822. if entry1[0] != entry2[0]:
  823. if entry1[0] > entry2[0]:
  824. return 1
  825. else:
  826. return -1
  827. if entry1[1] != entry2[1]:
  828. if entry1[1] > entry2[1]:
  829. return 1
  830. else:
  831. return -1
  832. # Finally: Compare message ID
  833. if self.msgid > other.msgid: return 1
  834. else: return -1
  835. def translated(self):
  836. """
  837. Returns ``True`` if the entry has been translated or ``False``
  838. otherwise.
  839. """
  840. if self.obsolete or 'fuzzy' in self.flags:
  841. return False
  842. if self.msgstr != '':
  843. return True
  844. if self.msgstr_plural:
  845. for pos in self.msgstr_plural:
  846. if self.msgstr_plural[pos] == '':
  847. return False
  848. return True
  849. return False
  850. def merge(self, other):
  851. """
  852. Merge the current entry with the given pot entry.
  853. """
  854. self.msgid = other.msgid
  855. self.msgctxt = other.msgctxt
  856. self.occurrences = other.occurrences
  857. self.comment = other.comment
  858. fuzzy = 'fuzzy' in self.flags
  859. self.flags = other.flags[:] # clone flags
  860. if fuzzy:
  861. self.flags.append('fuzzy')
  862. self.msgid_plural = other.msgid_plural
  863. self.obsolete = other.obsolete
  864. self.previous_msgctxt = other.previous_msgctxt
  865. self.previous_msgid = other.previous_msgid
  866. self.previous_msgid_plural = other.previous_msgid_plural
  867. if other.msgstr_plural:
  868. for pos in other.msgstr_plural:
  869. try:
  870. # keep existing translation at pos if any
  871. self.msgstr_plural[pos]
  872. except KeyError:
  873. self.msgstr_plural[pos] = ''
  874. # }}}
  875. # class MOEntry {{{
  876. class MOEntry(_BaseEntry):
  877. """
  878. Represents a mo file entry.
  879. """
  880. pass
  881. # }}}
  882. # class _POFileParser {{{
  883. class _POFileParser(object):
  884. """
  885. A finite state machine to parse efficiently and correctly po
  886. file format.
  887. """
  888. def __init__(self, pofile, *args, **kwargs):
  889. """
  890. Constructor.
  891. Keyword arguments:
  892. ``pofile``
  893. string, path to the po file or its content
  894. ``encoding``
  895. string, the encoding to use, defaults to ``default_encoding``
  896. global variable (optional).
  897. ``check_for_duplicates``
  898. whether to check for duplicate entries when adding entries to the
  899. file (optional, default: ``False``).
  900. """
  901. enc = kwargs.get('encoding', default_encoding)
  902. if os.path.exists(pofile):
  903. try:
  904. self.fhandle = codecs.open(pofile, 'rU', enc)
  905. except LookupError:
  906. enc = default_encoding
  907. self.fhandle = codecs.open(pofile, 'rU', enc)
  908. else:
  909. self.fhandle = pofile.splitlines()
  910. self.instance = POFile(
  911. pofile=pofile,
  912. encoding=enc,
  913. check_for_duplicates=kwargs.get('check_for_duplicates', False)
  914. )
  915. self.transitions = {}
  916. self.current_entry = POEntry()
  917. self.current_state = 'ST'
  918. self.current_token = None
  919. # two memo flags used in handlers
  920. self.msgstr_index = 0
  921. self.entry_obsolete = 0
  922. # Configure the state machine, by adding transitions.
  923. # Signification of symbols:
  924. # * ST: Beginning of the file (start)
  925. # * HE: Header
  926. # * TC: a translation comment
  927. # * GC: a generated comment
  928. # * OC: a file/line occurence
  929. # * FL: a flags line
  930. # * CT: a message context
  931. # * PC: a previous msgctxt
  932. # * PM: a previous msgid
  933. # * PP: a previous msgid_plural
  934. # * MI: a msgid
  935. # * MP: a msgid plural
  936. # * MS: a msgstr
  937. # * MX: a msgstr plural
  938. # * MC: a msgid or msgstr continuation line
  939. all = ['ST', 'HE', 'GC', 'OC', 'FL', 'CT', 'PC', 'PM', 'PP', 'TC',
  940. 'MS', 'MP', 'MX', 'MI']
  941. self.add('TC', ['ST', 'HE'], 'HE')
  942. self.add('TC', ['GC', 'OC', 'FL', 'TC', 'PC', 'PM', 'PP', 'MS',
  943. 'MP', 'MX', 'MI'], 'TC')
  944. self.add('GC', all, 'GC')
  945. self.add('OC', all, 'OC')
  946. self.add('FL', all, 'FL')
  947. self.add('PC', all, 'PC')
  948. self.add('PM', all, 'PM')
  949. self.add('PP', all, 'PP')
  950. self.add('CT', ['ST', 'HE', 'GC', 'OC', 'FL', 'TC', 'PC', 'PM',
  951. 'PP', 'MS', 'MX'], 'CT')
  952. self.add('MI', ['ST', 'HE', 'GC', 'OC', 'FL', 'CT', 'TC', 'PC',
  953. 'PM', 'PP', 'MS', 'MX'], 'MI')
  954. self.add('MP', ['TC', 'GC', 'PC', 'PM', 'PP', 'MI'], 'MP')
  955. self.add('MS', ['MI', 'MP', 'TC'], 'MS')
  956. self.add('MX', ['MI', 'MX', 'MP', 'TC'], 'MX')
  957. self.add('MC', ['CT', 'MI', 'MP', 'MS', 'MX', 'PM', 'PP', 'PC'], 'MC')
  958. def parse(self):
  959. """
  960. Run the state machine, parse the file line by line and call process()
  961. with the current matched symbol.
  962. """
  963. i = 0
  964. keywords = {
  965. 'msgctxt': 'CT',
  966. 'msgid': 'MI',
  967. 'msgstr': 'MS',
  968. 'msgid_plural': 'MP',
  969. }
  970. prev_keywords = {
  971. 'msgid_plural': 'PP',
  972. 'msgid': 'PM',
  973. 'msgctxt': 'PC',
  974. }
  975. for line in self.fhandle:
  976. i += 1
  977. line = line.strip()
  978. if line == '':
  979. continue
  980. tokens = line.split(None, 2)
  981. nb_tokens = len(tokens)
  982. if tokens[0] == '#~' and nb_tokens > 1:
  983. line = line[3:].strip()
  984. tokens = tokens[1:]
  985. nb_tokens -= 1
  986. self.entry_obsolete = 1
  987. else:
  988. self.entry_obsolete = 0
  989. # Take care of keywords like
  990. # msgid, msgid_plural, msgctxt & msgstr.
  991. if tokens[0] in keywords and nb_tokens > 1:
  992. line = line[len(tokens[0]):].lstrip()
  993. self.current_token = line
  994. self.process(keywords[tokens[0]], i)
  995. continue
  996. self.current_token = line
  997. if tokens[0] == '#:' and nb_tokens > 1:
  998. # we are on a occurrences line
  999. self.process('OC', i)
  1000. elif line[:1] == '"':
  1001. # we are on a continuation line
  1002. self.process('MC', i)
  1003. elif line[:7] == 'msgstr[':
  1004. # we are on a msgstr plural
  1005. self.process('MX', i)
  1006. elif tokens[0] == '#,' and nb_tokens > 1:
  1007. # we are on a flags line
  1008. self.process('FL', i)
  1009. elif tokens[0] == '#':
  1010. if line == '#': line += ' '
  1011. # we are on a translator comment line
  1012. self.process('TC', i)
  1013. elif tokens[0] == '#.' and nb_tokens > 1:
  1014. # we are on a generated comment line
  1015. self.process('GC', i)
  1016. elif tokens[0] == '#|':
  1017. if nb_tokens < 2:
  1018. self.process('??', i)
  1019. continue
  1020. # Remove the marker and any whitespace right after that.
  1021. line = line[2:].lstrip()
  1022. self.current_token = line
  1023. if tokens[1].startswith('"'):
  1024. # Continuation of previous metadata.
  1025. self.process('MC', i)
  1026. continue
  1027. if nb_tokens == 2:
  1028. # Invalid continuation line.
  1029. self.process('??', i)
  1030. # we are on a "previous translation" comment line,
  1031. if tokens[1] not in prev_keywords:
  1032. # Unknown keyword in previous translation comment.
  1033. self.process('??', i)
  1034. # Remove the keyword and any whitespace
  1035. # between it and the starting quote.
  1036. line = line[len(tokens[1]):].lstrip()
  1037. self.current_token = line
  1038. self.process(prev_keywords[tokens[1]], i)
  1039. else:
  1040. self.process('??', i)
  1041. if self.current_entry:
  1042. # since entries are added when another entry is found, we must add
  1043. # the last entry here (only if there are lines)
  1044. self.instance.append(self.current_entry)
  1045. # before returning the instance, check if there's metadata and if
  1046. # so extract it in a dict
  1047. firstentry = self.instance[0]
  1048. if firstentry.msgid == '': # metadata found
  1049. # remove the entry
  1050. firstentry = self.instance.pop(0)
  1051. self.instance.metadata_is_fuzzy = firstentry.flags
  1052. key = None
  1053. for msg in firstentry.msgstr.splitlines():
  1054. try:
  1055. key, val = msg.split(':', 1)
  1056. self.instance.metadata[key] = val.strip()
  1057. except:
  1058. if key is not None:
  1059. self.instance.metadata[key] += '\n'+ msg.strip()
  1060. # close opened file
  1061. if isinstance(self.fhandle, file):
  1062. self.fhandle.close()
  1063. return self.instance
  1064. def add(self, symbol, states, next_state):
  1065. """
  1066. Add a transition to the state machine.
  1067. Keywords arguments:
  1068. ``symbol``
  1069. string, the matched token (two chars symbol).
  1070. ``states``
  1071. list, a list of states (two chars symbols).
  1072. ``next_state``
  1073. the next state the fsm will have after the action.
  1074. """
  1075. for state in states:
  1076. action = getattr(self, 'handle_%s' % next_state.lower())
  1077. self.transitions[(symbol, state)] = (action, next_state)
  1078. def process(self, symbol, linenum):
  1079. """
  1080. Process the transition corresponding to the current state and the
  1081. symbol provided.
  1082. Keywords arguments:
  1083. ``symbol``
  1084. string, the matched token (two chars symbol).
  1085. ``linenum``
  1086. integer, the current line number of the parsed file.
  1087. """
  1088. try:
  1089. (action, state) = self.transitions[(symbol, self.current_state)]
  1090. if action():
  1091. self.current_state = state
  1092. except Exception, exc:
  1093. raise IOError('Syntax error in po file (line %s)' % linenum)
  1094. # state handlers
  1095. def handle_he(self):
  1096. """Handle a header comment."""
  1097. if self.instance.header != '':
  1098. self.instance.header += '\n'
  1099. self.instance.header += self.current_token[2:]
  1100. return 1
  1101. def handle_tc(self):
  1102. """Handle a translator comment."""
  1103. if self.current_state in ['MC', 'MS', 'MX']:
  1104. self.instance.append(self.current_entry)
  1105. self.current_entry = POEntry()
  1106. if self.current_entry.tcomment != '':
  1107. self.current_entry.tcomment += '\n'
  1108. self.current_entry.tcomment += self.current_token[2:]
  1109. return True
  1110. def handle_gc(self):
  1111. """Handle a generated comment."""
  1112. if self.current_state in ['MC', 'MS', 'MX']:
  1113. self.instance.append(self.current_entry)
  1114. self.current_entry = POEntry()
  1115. if self.current_entry.comment != '':
  1116. self.current_entry.comment += '\n'
  1117. self.current_entry.comment += self.current_token[3:]
  1118. return True
  1119. def handle_oc(self):
  1120. """Handle a file:num occurence."""
  1121. if self.current_state in ['MC', 'MS', 'MX']:
  1122. self.instance.append(self.current_entry)
  1123. self.current_entry = POEntry()
  1124. occurrences = self.current_token[3:].split()
  1125. for occurrence in occurrences:
  1126. if occurrence != '':
  1127. try:
  1128. fil, line = occurrence.split(':')
  1129. if not line.isdigit():
  1130. fil = fil + line
  1131. line = ''
  1132. self.current_entry.occurrences.append((fil, line))
  1133. except:
  1134. self.current_entry.occurrences.append((occurrence, ''))
  1135. return True
  1136. def handle_fl(self):
  1137. """Handle a flags line."""
  1138. if self.current_state in ['MC', 'MS', 'MX']:
  1139. self.instance.append(self.current_entry)
  1140. self.current_entry = POEntry()
  1141. self.current_entry.flags += self.current_token[3:].split(', ')
  1142. return True
  1143. def handle_pp(self):
  1144. """Handle a previous msgid_plural line."""
  1145. if self.current_state in ['MC', 'MS', 'MX']:
  1146. self.instance.append(self.current_entry)
  1147. self.current_entry = POEntry()
  1148. self.current_entry.previous_msgid_plural = \
  1149. unescape(self.current_token[1:-1])
  1150. return True
  1151. def handle_pm(self):
  1152. """Handle a previous msgid line."""
  1153. if self.current_state in ['MC', 'MS', 'MX']:
  1154. self.instance.append(self.current_entry)
  1155. self.current_entry = POEntry()
  1156. self.current_entry.previous_msgid = \
  1157. unescape(self.current_token[1:-1])
  1158. return True
  1159. def handle_pc(self):
  1160. """Handle a previous msgctxt line."""
  1161. if self.current_state in ['MC', 'MS', 'MX']:
  1162. self.instance.append(self.current_entry)
  1163. self.current_entry = POEntry()
  1164. self.current_entry.previous_msgctxt = \
  1165. unescape(self.current_token[1:-1])
  1166. return True
  1167. def handle_ct(self):
  1168. """Handle a msgctxt."""
  1169. if self.current_state in ['MC', 'MS', 'MX']:
  1170. self.instance.append(self.current_entry)
  1171. self.current_entry = POEntry()
  1172. self.current_entry.msgctxt = unescape(self.current_token[1:-1])
  1173. return True
  1174. def handle_mi(self):
  1175. """Handle a msgid."""
  1176. if self.current_state in ['MC', 'MS', 'MX']:
  1177. self.instance.append(self.current_entry)
  1178. self.current_entry = POEntry()
  1179. self.current_entry.obsolete = self.entry_obsolete
  1180. self.current_entry.msgid = unescape(self.current_token[1:-1])
  1181. return True
  1182. def handle_mp(self):
  1183. """Handle a msgid plural."""
  1184. self.current_entry.msgid_plural = unescape(self.current_token[1:-1])
  1185. return True
  1186. def handle_ms(self):
  1187. """Handle a msgstr."""
  1188. self.current_entry.msgstr = unescape(self.current_token[1:-1])
  1189. return True
  1190. def handle_mx(self):
  1191. """Handle a msgstr plural."""
  1192. index, value = self.current_token[7], self.current_token[11:-1]
  1193. self.current_entry.msgstr_plural[index] = unescape(value)
  1194. self.msgstr_index = index
  1195. return True
  1196. def handle_mc(self):
  1197. """Handle a msgid or msgstr continuation line."""
  1198. token = unescape(self.current_token[1:-1])
  1199. if self.current_state == 'CT':
  1200. typ = 'msgctxt'
  1201. self.current_entry.msgctxt += token
  1202. elif self.current_state == 'MI':
  1203. typ = 'msgid'
  1204. self.current_entry.msgid += token
  1205. elif self.current_state == 'MP':
  1206. typ = 'msgid_plural'
  1207. self.current_entry.msgid_plural += token
  1208. elif self.current_state == 'MS':
  1209. typ = 'msgstr'
  1210. self.current_entry.msgstr += token
  1211. elif self.current_state == 'MX':
  1212. typ = 'msgstr[%s]' % self.msgstr_index
  1213. self.current_entry.msgstr_plural[self.msgstr_index] += token
  1214. elif self.current_state == 'PP':
  1215. typ = 'previous_msgid_plural'
  1216. token = token[3:]
  1217. self.current_entry.previous_msgid_plural += token
  1218. elif self.current_state == 'PM':
  1219. typ = 'previous_msgid'
  1220. token = token[3:]
  1221. self.current_entry.previous_msgid += token
  1222. elif self.current_state == 'PC':
  1223. typ = 'previous_msgctxt'
  1224. token = token[3:]
  1225. self.current_entry.previous_msgctxt += token
  1226. # don't change the current state
  1227. return False
  1228. # }}}
  1229. # class _MOFileParser {{{
  1230. class _MOFileParser(object):
  1231. """
  1232. A class to parse binary mo files.
  1233. """
  1234. def __init__(self, mofile, *args, **kwargs):
  1235. """
  1236. Constructor.
  1237. Keyword arguments:
  1238. ``mofile``
  1239. string, path to the mo file or its content
  1240. ``encoding``
  1241. string, the encoding to use, defaults to ``default_encoding``
  1242. global variable (optional).
  1243. ``check_for_duplicates``
  1244. whether to check for duplicate entries when adding entries to the
  1245. file (optional, default: ``False``).
  1246. """
  1247. self.fhandle = open(mofile, 'rb')
  1248. self.instance = MOFile(
  1249. fpath=mofile,
  1250. encoding=kwargs.get('encoding', default_encoding),
  1251. check_for_duplicates=kwargs.get('check_for_duplicates', False)
  1252. )
  1253. def parse(self):
  1254. """
  1255. Build the instance with the file handle provided in the
  1256. constructor.
  1257. """
  1258. # parse magic number
  1259. magic_number = self._readbinary('<I', 4)
  1260. if magic_number == MOFile.LITTLE_ENDIAN:
  1261. ii = '<II'
  1262. elif magic_number == MOFile.BIG_ENDIAN:
  1263. ii = '>II'
  1264. else:
  1265. raise IOError('Invalid mo file, magic number is incorrect !')
  1266. self.instance.magic_number = magic_number
  1267. # parse the version number and the number of strings
  1268. self.instance.version, numofstrings = self._readbinary(ii, 8)
  1269. # original strings and translation strings hash table offset
  1270. msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8)
  1271. # move to msgid hash table and read length and offset of msgids
  1272. self.fhandle.seek(msgids_hash_offset)
  1273. msgids_index = []
  1274. for i in range(numofstrings):
  1275. msgids_index.append(self._readbinary(ii, 8))
  1276. # move to msgstr hash table and read length and offset of msgstrs
  1277. self.fhandle.seek(msgstrs_hash_offset)
  1278. msgstrs_index = []
  1279. for i in range(numofstrings):
  1280. msgstrs_index.append(self._readbinary(ii, 8))
  1281. # build entries
  1282. for i in range(numofstrings):
  1283. self.fhandle.seek(msgids_index[i][1])
  1284. msgid = self.fhandle.read(msgids_index[i][0])
  1285. self.fhandle.seek(msgstrs_index[i][1])
  1286. msgstr = self.fhandle.read(msgstrs_index[i][0])
  1287. if i == 0: # metadata
  1288. raw_metadata, metadata = msgstr.split('\n'), {}

Large files files are truncated, but you can click here to view the full file