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