Debian Codegraph @

babel/messages/mofile.py

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