Mercurial > babel > old > babel-test
annotate babel/messages/mofile.py @ 530:85e1beadacb0
Update the copyright line.
author | jruigrok |
---|---|
date | Sat, 05 Mar 2011 15:22:28 +0000 |
parents | 53c68c594b5f |
children | f642c81ce8cc |
rev | line source |
---|---|
160 | 1 # -*- coding: utf-8 -*- |
2 # | |
530 | 3 # Copyright (C) 2007-2011 Edgewall Software |
160 | 4 # All rights reserved. |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
8 # are also available at http://babel.edgewall.org/wiki/License. | |
9 # | |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
12 # history and logs, available at http://babel.edgewall.org/log/. | |
13 | |
14 """Writing of files in the ``gettext`` MO (machine object) format. | |
15 | |
234 | 16 :since: version 0.9 |
160 | 17 :see: `The Format of MO Files |
18 <http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files>`_ | |
19 """ | |
20 | |
21 import array | |
22 import struct | |
23 | |
334 | 24 from babel.messages.catalog import Catalog, Message |
25 | |
26 __all__ = ['read_mo', 'write_mo'] | |
161 | 27 __docformat__ = 'restructuredtext en' |
28 | |
334 | 29 |
30 LE_MAGIC = 0x950412deL | |
31 BE_MAGIC = 0xde120495L | |
32 | |
33 def read_mo(fileobj): | |
34 """Read a binary MO file from the given file-like object and return a | |
35 corresponding `Catalog` object. | |
36 | |
37 :param fileobj: the file-like object to read the MO file from | |
38 :return: a catalog object representing the parsed MO file | |
39 :rtype: `Catalog` | |
40 | |
41 :note: The implementation of this function is heavily based on the | |
42 ``GNUTranslations._parse`` method of the ``gettext`` module in the | |
43 standard library. | |
44 """ | |
45 catalog = Catalog() | |
46 headers = {} | |
47 | |
48 filename = getattr(fileobj, 'name', '') | |
49 charset = None | |
50 | |
51 buf = fileobj.read() | |
52 buflen = len(buf) | |
335 | 53 unpack = struct.unpack |
334 | 54 |
55 # Parse the .mo file header, which consists of 5 little endian 32 | |
56 # bit words. | |
57 magic = unpack('<I', buf[:4])[0] # Are we big endian or little endian? | |
58 if magic == LE_MAGIC: | |
335 | 59 version, msgcount, origidx, transidx = unpack('<4I', buf[4:20]) |
334 | 60 ii = '<II' |
61 elif magic == BE_MAGIC: | |
335 | 62 version, msgcount, origidx, transidx = unpack('>4I', buf[4:20]) |
334 | 63 ii = '>II' |
64 else: | |
65 raise IOError(0, 'Bad magic number', filename) | |
66 | |
67 # Now put all messages from the .mo file buffer into the catalog | |
68 # dictionary | |
69 for i in xrange(0, msgcount): | |
335 | 70 mlen, moff = unpack(ii, buf[origidx:origidx + 8]) |
334 | 71 mend = moff + mlen |
72 tlen, toff = unpack(ii, buf[transidx:transidx + 8]) | |
73 tend = toff + tlen | |
74 if mend < buflen and tend < buflen: | |
75 msg = buf[moff:mend] | |
76 tmsg = buf[toff:tend] | |
77 else: | |
78 raise IOError(0, 'File is corrupt', filename) | |
79 | |
80 # See if we're looking at GNU .mo conventions for metadata | |
81 if mlen == 0: | |
82 # Catalog description | |
83 lastkey = key = None | |
84 for item in tmsg.splitlines(): | |
85 item = item.strip() | |
86 if not item: | |
87 continue | |
88 if ':' in item: | |
89 key, value = item.split(':', 1) | |
90 lastkey = key = key.strip().lower() | |
335 | 91 headers[key] = value.strip() |
334 | 92 elif lastkey: |
335 | 93 headers[lastkey] += '\n' + item |
334 | 94 |
335 | 95 if '\x04' in msg: # context |
96 ctxt, msg = msg.split('\x04') | |
97 else: | |
98 ctxt = None | |
99 | |
100 if '\x00' in msg: # plural forms | |
334 | 101 msg = msg.split('\x00') |
102 tmsg = tmsg.split('\x00') | |
335 | 103 if catalog.charset: |
104 msg = [x.decode(catalog.charset) for x in msg] | |
105 tmsg = [x.decode(catalog.charset) for x in tmsg] | |
334 | 106 else: |
335 | 107 if catalog.charset: |
108 msg = msg.decode(catalog.charset) | |
109 tmsg = tmsg.decode(catalog.charset) | |
110 catalog[msg] = Message(msg, tmsg, context=ctxt) | |
334 | 111 |
112 # advance to next entry in the seek tables | |
335 | 113 origidx += 8 |
334 | 114 transidx += 8 |
115 | |
116 catalog.mime_headers = headers.items() | |
117 return catalog | |
118 | |
160 | 119 def write_mo(fileobj, catalog, use_fuzzy=False): |
120 """Write a catalog to the specified file-like object using the GNU MO file | |
121 format. | |
122 | |
123 >>> from babel.messages import Catalog | |
124 >>> from gettext import GNUTranslations | |
125 >>> from StringIO import StringIO | |
126 | |
127 >>> catalog = Catalog(locale='en_US') | |
128 >>> catalog.add('foo', 'Voh') | |
129 >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz')) | |
130 >>> catalog.add('fuz', 'Futz', flags=['fuzzy']) | |
172 | 131 >>> catalog.add('Fizz', '') |
174
456ee0941987
Extended the doctest to include tests for the fix on [176].
palgarvio
parents:
173
diff
changeset
|
132 >>> catalog.add(('Fuzz', 'Fuzzes'), ('', '')) |
160 | 133 >>> buf = StringIO() |
134 | |
135 >>> write_mo(buf, catalog) | |
136 >>> buf.seek(0) | |
137 >>> translations = GNUTranslations(fp=buf) | |
138 >>> translations.ugettext('foo') | |
139 u'Voh' | |
140 >>> translations.ungettext('bar', 'baz', 1) | |
141 u'Bahr' | |
142 >>> translations.ungettext('bar', 'baz', 2) | |
143 u'Batz' | |
144 >>> translations.ugettext('fuz') | |
145 u'fuz' | |
172 | 146 >>> translations.ugettext('Fizz') |
147 u'Fizz' | |
174
456ee0941987
Extended the doctest to include tests for the fix on [176].
palgarvio
parents:
173
diff
changeset
|
148 >>> translations.ugettext('Fuzz') |
456ee0941987
Extended the doctest to include tests for the fix on [176].
palgarvio
parents:
173
diff
changeset
|
149 u'Fuzz' |
456ee0941987
Extended the doctest to include tests for the fix on [176].
palgarvio
parents:
173
diff
changeset
|
150 >>> translations.ugettext('Fuzzes') |
456ee0941987
Extended the doctest to include tests for the fix on [176].
palgarvio
parents:
173
diff
changeset
|
151 u'Fuzzes' |
160 | 152 |
153 :param fileobj: the file-like object to write to | |
154 :param catalog: the `Catalog` instance | |
155 :param use_fuzzy: whether translations marked as "fuzzy" should be included | |
156 in the output | |
157 """ | |
158 messages = list(catalog) | |
159 if not use_fuzzy: | |
160 messages[1:] = [m for m in messages[1:] if not m.fuzzy] | |
248
bedaaeadc1db
add a __cmp__ to Message that correctly sorts by id, taking into account plurals
pjenvey
parents:
234
diff
changeset
|
161 messages.sort() |
160 | 162 |
163 ids = strs = '' | |
164 offsets = [] | |
165 | |
166 for message in messages: | |
167 # For each string, we need size and file offset. Each string is NUL | |
168 # terminated; the NUL does not count into the size. | |
169 if message.pluralizable: | |
170 msgid = '\x00'.join([ | |
171 msgid.encode(catalog.charset) for msgid in message.id | |
172 ]) | |
173
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
173 msgstrs = [] |
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
174 for idx, string in enumerate(message.string): |
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
175 if not string: |
330
5f67aa47609c
Fix for #97, compilation of message catalogs for locales with more than two plural forms where the translations were empty was failing.
cmlenz
parents:
248
diff
changeset
|
176 msgstrs.append(message.id[min(int(idx), 1)]) |
173
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
177 else: |
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
178 msgstrs.append(string) |
160 | 179 msgstr = '\x00'.join([ |
173
743abd4ca3c3
Forgot to fix the pluralizable messages, regarding #28.
palgarvio
parents:
172
diff
changeset
|
180 msgstr.encode(catalog.charset) for msgstr in msgstrs |
160 | 181 ]) |
182 else: | |
183 msgid = message.id.encode(catalog.charset) | |
172 | 184 if not message.string: |
185 msgstr = message.id.encode(catalog.charset) | |
186 else: | |
187 msgstr = message.string.encode(catalog.charset) | |
335 | 188 if message.context: |
420 | 189 msgid = '\x04'.join([message.context.encode(catalog.charset), |
190 msgid]) | |
160 | 191 offsets.append((len(ids), len(msgid), len(strs), len(msgstr))) |
192 ids += msgid + '\x00' | |
193 strs += msgstr + '\x00' | |
194 | |
195 # The header is 7 32-bit unsigned integers. We don't use hash tables, so | |
196 # the keys start right after the index tables. | |
197 keystart = 7 * 4 + 16 * len(messages) | |
198 valuestart = keystart + len(ids) | |
199 | |
200 # The string table first has the list of keys, then the list of values. | |
201 # Each entry has first the size of the string, then the file offset. | |
202 koffsets = [] | |
203 voffsets = [] | |
204 for o1, l1, o2, l2 in offsets: | |
205 koffsets += [l1, o1 + keystart] | |
206 voffsets += [l2, o2 + valuestart] | |
207 offsets = koffsets + voffsets | |
208 | |
209 fileobj.write(struct.pack('Iiiiiii', | |
334 | 210 LE_MAGIC, # magic |
160 | 211 0, # version |
212 len(messages), # number of entries | |
213 7 * 4, # start of key index | |
214 7 * 4 + len(messages) * 8, # start of value index | |
215 0, 0 # size and offset of hash table | |
216 ) + array.array("i", offsets).tostring() + ids + strs) |