mofile.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.messages.mofile
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. Writing of files in the ``gettext`` MO (machine object) format.
  6. :copyright: (c) 2013-2021 by the Babel Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import array
  10. import struct
  11. from babel.messages.catalog import Catalog, Message
  12. from babel._compat import range_type, array_tobytes
  13. LE_MAGIC = 0x950412de
  14. BE_MAGIC = 0xde120495
  15. def read_mo(fileobj):
  16. """Read a binary MO file from the given file-like object and return a
  17. corresponding `Catalog` object.
  18. :param fileobj: the file-like object to read the MO file from
  19. :note: The implementation of this function is heavily based on the
  20. ``GNUTranslations._parse`` method of the ``gettext`` module in the
  21. standard library.
  22. """
  23. catalog = Catalog()
  24. headers = {}
  25. filename = getattr(fileobj, 'name', '')
  26. buf = fileobj.read()
  27. buflen = len(buf)
  28. unpack = struct.unpack
  29. # Parse the .mo file header, which consists of 5 little endian 32
  30. # bit words.
  31. magic = unpack('<I', buf[:4])[0] # Are we big endian or little endian?
  32. if magic == LE_MAGIC:
  33. version, msgcount, origidx, transidx = unpack('<4I', buf[4:20])
  34. ii = '<II'
  35. elif magic == BE_MAGIC:
  36. version, msgcount, origidx, transidx = unpack('>4I', buf[4:20])
  37. ii = '>II'
  38. else:
  39. raise IOError(0, 'Bad magic number', filename)
  40. # Now put all messages from the .mo file buffer into the catalog
  41. # dictionary
  42. for i in range_type(0, msgcount):
  43. mlen, moff = unpack(ii, buf[origidx:origidx + 8])
  44. mend = moff + mlen
  45. tlen, toff = unpack(ii, buf[transidx:transidx + 8])
  46. tend = toff + tlen
  47. if mend < buflen and tend < buflen:
  48. msg = buf[moff:mend]
  49. tmsg = buf[toff:tend]
  50. else:
  51. raise IOError(0, 'File is corrupt', filename)
  52. # See if we're looking at GNU .mo conventions for metadata
  53. if mlen == 0:
  54. # Catalog description
  55. lastkey = key = None
  56. for item in tmsg.splitlines():
  57. item = item.strip()
  58. if not item:
  59. continue
  60. if b':' in item:
  61. key, value = item.split(b':', 1)
  62. lastkey = key = key.strip().lower()
  63. headers[key] = value.strip()
  64. elif lastkey:
  65. headers[lastkey] += b'\n' + item
  66. if b'\x04' in msg: # context
  67. ctxt, msg = msg.split(b'\x04')
  68. else:
  69. ctxt = None
  70. if b'\x00' in msg: # plural forms
  71. msg = msg.split(b'\x00')
  72. tmsg = tmsg.split(b'\x00')
  73. if catalog.charset:
  74. msg = [x.decode(catalog.charset) for x in msg]
  75. tmsg = [x.decode(catalog.charset) for x in tmsg]
  76. else:
  77. if catalog.charset:
  78. msg = msg.decode(catalog.charset)
  79. tmsg = tmsg.decode(catalog.charset)
  80. catalog[msg] = Message(msg, tmsg, context=ctxt)
  81. # advance to next entry in the seek tables
  82. origidx += 8
  83. transidx += 8
  84. catalog.mime_headers = headers.items()
  85. return catalog
  86. def write_mo(fileobj, catalog, use_fuzzy=False):
  87. """Write a catalog to the specified file-like object using the GNU MO file
  88. format.
  89. >>> import sys
  90. >>> from babel.messages import Catalog
  91. >>> from gettext import GNUTranslations
  92. >>> from babel._compat import BytesIO
  93. >>> catalog = Catalog(locale='en_US')
  94. >>> catalog.add('foo', 'Voh')
  95. <Message ...>
  96. >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
  97. <Message ...>
  98. >>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
  99. <Message ...>
  100. >>> catalog.add('Fizz', '')
  101. <Message ...>
  102. >>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
  103. <Message ...>
  104. >>> buf = BytesIO()
  105. >>> write_mo(buf, catalog)
  106. >>> x = buf.seek(0)
  107. >>> translations = GNUTranslations(fp=buf)
  108. >>> if sys.version_info[0] >= 3:
  109. ... translations.ugettext = translations.gettext
  110. ... translations.ungettext = translations.ngettext
  111. >>> translations.ugettext('foo')
  112. u'Voh'
  113. >>> translations.ungettext('bar', 'baz', 1)
  114. u'Bahr'
  115. >>> translations.ungettext('bar', 'baz', 2)
  116. u'Batz'
  117. >>> translations.ugettext('fuz')
  118. u'fuz'
  119. >>> translations.ugettext('Fizz')
  120. u'Fizz'
  121. >>> translations.ugettext('Fuzz')
  122. u'Fuzz'
  123. >>> translations.ugettext('Fuzzes')
  124. u'Fuzzes'
  125. :param fileobj: the file-like object to write to
  126. :param catalog: the `Catalog` instance
  127. :param use_fuzzy: whether translations marked as "fuzzy" should be included
  128. in the output
  129. """
  130. messages = list(catalog)
  131. messages[1:] = [m for m in messages[1:]
  132. if m.string and (use_fuzzy or not m.fuzzy)]
  133. messages.sort()
  134. ids = strs = b''
  135. offsets = []
  136. for message in messages:
  137. # For each string, we need size and file offset. Each string is NUL
  138. # terminated; the NUL does not count into the size.
  139. if message.pluralizable:
  140. msgid = b'\x00'.join([
  141. msgid.encode(catalog.charset) for msgid in message.id
  142. ])
  143. msgstrs = []
  144. for idx, string in enumerate(message.string):
  145. if not string:
  146. msgstrs.append(message.id[min(int(idx), 1)])
  147. else:
  148. msgstrs.append(string)
  149. msgstr = b'\x00'.join([
  150. msgstr.encode(catalog.charset) for msgstr in msgstrs
  151. ])
  152. else:
  153. msgid = message.id.encode(catalog.charset)
  154. msgstr = message.string.encode(catalog.charset)
  155. if message.context:
  156. msgid = b'\x04'.join([message.context.encode(catalog.charset),
  157. msgid])
  158. offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
  159. ids += msgid + b'\x00'
  160. strs += msgstr + b'\x00'
  161. # The header is 7 32-bit unsigned integers. We don't use hash tables, so
  162. # the keys start right after the index tables.
  163. keystart = 7 * 4 + 16 * len(messages)
  164. valuestart = keystart + len(ids)
  165. # The string table first has the list of keys, then the list of values.
  166. # Each entry has first the size of the string, then the file offset.
  167. koffsets = []
  168. voffsets = []
  169. for o1, l1, o2, l2 in offsets:
  170. koffsets += [l1, o1 + keystart]
  171. voffsets += [l2, o2 + valuestart]
  172. offsets = koffsets + voffsets
  173. fileobj.write(struct.pack('Iiiiiii',
  174. LE_MAGIC, # magic
  175. 0, # version
  176. len(messages), # number of entries
  177. 7 * 4, # start of key index
  178. 7 * 4 + len(messages) * 8, # start of value index
  179. 0, 0 # size and offset of hash table
  180. ) + array_tobytes(array.array("i", offsets)) + ids + strs)