1 # -*- coding: utf-8 -*-
6 Writing of files in the ``gettext`` MO (machine object) format.
8 :copyright: (c) 2013 by the Babel Team.
9 :license: BSD, see LICENSE for more details.
15 from babel.messages.catalog import Catalog, Message
16 from babel._compat import range_type, array_tobytes
24 """Read a binary MO file from the given file-like object and return a
25 corresponding `Catalog` object.
27 :param fileobj: the file-like object to read the MO file from
29 :note: The implementation of this function is heavily based on the
30 ``GNUTranslations._parse`` method of the ``gettext`` module in the
36 filename = getattr(fileobj, 'name', '')
40 unpack = struct.unpack
42 # Parse the .mo file header, which consists of 5 little endian 32
44 magic = unpack('<I', buf[:4])[0] # Are we big endian or little endian?
46 version, msgcount, origidx, transidx = unpack('<4I', buf[4:20])
48 elif magic == BE_MAGIC:
49 version, msgcount, origidx, transidx = unpack('>4I', buf[4:20])
52 raise IOError(0, 'Bad magic number', filename)
54 # Now put all messages from the .mo file buffer into the catalog
56 for i in range_type(0, msgcount):
57 mlen, moff = unpack(ii, buf[origidx:origidx + 8])
59 tlen, toff = unpack(ii, buf[transidx:transidx + 8])
61 if mend < buflen and tend < buflen:
65 raise IOError(0, 'File is corrupt', filename)
67 # See if we're looking at GNU .mo conventions for metadata
71 for item in tmsg.splitlines():
76 key, value = item.split(b':', 1)
77 lastkey = key = key.strip().lower()
78 headers[key] = value.strip()
80 headers[lastkey] += b'\n' + item
82 if b'\x04' in msg: # context
83 ctxt, msg = msg.split(b'\x04')
87 if b'\x00' in msg: # plural forms
88 msg = msg.split(b'\x00')
89 tmsg = tmsg.split(b'\x00')
91 msg = [x.decode(catalog.charset) for x in msg]
92 tmsg = [x.decode(catalog.charset) for x in tmsg]
95 msg = msg.decode(catalog.charset)
96 tmsg = tmsg.decode(catalog.charset)
97 catalog[msg] = Message(msg, tmsg, context=ctxt)
99 # advance to next entry in the seek tables
103 catalog.mime_headers = headers.items()
107 def write_mo(fileobj, catalog, use_fuzzy=False):
108 """Write a catalog to the specified file-like object using the GNU MO file
112 >>> from babel.messages import Catalog
113 >>> from gettext import GNUTranslations
114 >>> from babel._compat import BytesIO
116 >>> catalog = Catalog(locale='en_US')
117 >>> catalog.add('foo', 'Voh')
119 >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
121 >>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
123 >>> catalog.add('Fizz', '')
125 >>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
129 >>> write_mo(buf, catalog)
131 >>> translations = GNUTranslations(fp=buf)
132 >>> if sys.version_info[0] >= 3:
133 ... translations.ugettext = translations.gettext
134 ... translations.ungettext = translations.ngettext
135 >>> translations.ugettext('foo')
137 >>> translations.ungettext('bar', 'baz', 1)
139 >>> translations.ungettext('bar', 'baz', 2)
141 >>> translations.ugettext('fuz')
143 >>> translations.ugettext('Fizz')
145 >>> translations.ugettext('Fuzz')
147 >>> translations.ugettext('Fuzzes')
150 :param fileobj: the file-like object to write to
151 :param catalog: the `Catalog` instance
152 :param use_fuzzy: whether translations marked as "fuzzy" should be included
155 messages = list(catalog)
157 messages[1:] = [m for m in messages[1:] if not m.fuzzy]
163 for message in messages:
164 # For each string, we need size and file offset. Each string is NUL
165 # terminated; the NUL does not count into the size.
166 if message.pluralizable:
167 msgid = b'\x00'.join([
168 msgid.encode(catalog.charset) for msgid in message.id
171 for idx, string in enumerate(message.string):
173 msgstrs.append(message.id[min(int(idx), 1)])
175 msgstrs.append(string)
176 msgstr = b'\x00'.join([
177 msgstr.encode(catalog.charset) for msgstr in msgstrs
180 msgid = message.id.encode(catalog.charset)
181 if not message.string:
182 msgstr = message.id.encode(catalog.charset)
184 msgstr = message.string.encode(catalog.charset)
186 msgid = b'\x04'.join([message.context.encode(catalog.charset),
188 offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
189 ids += msgid + b'\x00'
190 strs += msgstr + b'\x00'
192 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
193 # the keys start right after the index tables.
194 keystart = 7 * 4 + 16 * len(messages)
195 valuestart = keystart + len(ids)
197 # The string table first has the list of keys, then the list of values.
198 # Each entry has first the size of the string, then the file offset.
201 for o1, l1, o2, l2 in offsets:
202 koffsets += [l1, o1 + keystart]
203 voffsets += [l2, o2 + valuestart]
204 offsets = koffsets + voffsets
206 fileobj.write(struct.pack('Iiiiiii',
209 len(messages), # number of entries
210 7 * 4, # start of key index
211 7 * 4 + len(messages) * 8, # start of value index
212 0, 0 # size and offset of hash table
213 ) + array_tobytes(array.array("i", offsets)) + ids + strs)