Debian Codegraph @

Tools/i18n/msgfmt.py

raw
1 #! /usr/bin/env python3
2 # Written by Martin v. Löwis <[email protected]>
3
4 """Generate binary message catalog from textual translation description.
5
6 This program converts a textual Uniforum-style message catalog (.po file) into
7 a binary GNU catalog (.mo file). This is essentially the same function as the
8 GNU msgfmt program, however, it is a simpler implementation. Currently it
9 does not handle plural forms but it does handle message contexts.
10
11 Usage: msgfmt.py [OPTIONS] filename.po
12
13 Options:
14 -o file
15 --output-file=file
16 Specify the output file to write to. If omitted, output will go to a
17 file named filename.mo (based off the input file name).
18
19 -h
20 --help
21 Print this message and exit.
22
23 -V
24 --version
25 Display version information and exit.
26 """
27
28 import array
29 import ast
30 import getopt
31 import os
32 import struct
33 import sys
34 from email.parser import HeaderParser
35
36 __version__ = "1.2"
37
38
39 MESSAGES = {}
40
41
42 def usage(code, msg=''):
43 print(__doc__, file=sys.stderr)
44 if msg:
45 print(msg, file=sys.stderr)
46 sys.exit(code)
47
48
49 def add(ctxt, id, str, fuzzy):
50 "Add a non-fuzzy translation to the dictionary."
51 global MESSAGES
52 if not fuzzy and str:
53 if ctxt is None:
54 MESSAGES[id] = str
55 else:
56 MESSAGES[b"%b\x04%b" % (ctxt, id)] = str
57
58
59 def generate():
60 "Return the generated output."
61 global MESSAGES
62 # the keys are sorted in the .mo file
63 keys = sorted(MESSAGES.keys())
64 offsets = []
65 ids = strs = b''
66 for id in keys:
67 # For each string, we need size and file offset. Each string is NUL
68 # terminated; the NUL does not count into the size.
69 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
70 ids += id + b'\0'
71 strs += MESSAGES[id] + b'\0'
72 output = ''
73 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
74 # the keys start right after the index tables.
75 # translated string.
76 keystart = 7*4+16*len(keys)
77 # and the values start after the keys
78 valuestart = keystart + len(ids)
79 koffsets = []
80 voffsets = []
81 # The string table first has the list of keys, then the list of values.
82 # Each entry has first the size of the string, then the file offset.
83 for o1, l1, o2, l2 in offsets:
84 koffsets += [l1, o1+keystart]
85 voffsets += [l2, o2+valuestart]
86 offsets = koffsets + voffsets
87 output = struct.pack("Iiiiiii",
88 0x950412de, # Magic
89 0, # Version
90 len(keys), # # of entries
91 7*4, # start of key index
92 7*4+len(keys)*8, # start of value index
93 0, 0) # size and offset of hash table
94 output += array.array("i", offsets).tobytes()
95 output += ids
96 output += strs
97 return output
98
99
100 def make(filename, outfile):
101 ID = 1
102 STR = 2
103 CTXT = 3
104
105 # Compute .mo name from .po name and arguments
106 if filename.endswith('.po'):
107 infile = filename
108 else:
109 infile = filename + '.po'
110 if outfile is None:
111 outfile = os.path.splitext(infile)[0] + '.mo'
112
113 try:
114 with open(infile, 'rb') as f:
115 lines = f.readlines()
116 except OSError as msg:
117 print(msg, file=sys.stderr)
118 sys.exit(1)
119
120 section = msgctxt = None
121 msgid = msgstr = b''
122 fuzzy = 0
123
124 # Start off assuming Latin-1, so everything decodes without failure,
125 # until we know the exact encoding
126 encoding = 'latin-1'
127
128 # Parse the catalog
129 lno = 0
130 for l in lines:
131 l = l.decode(encoding)
132 lno += 1
133 # If we get a comment line after a msgstr, this is a new entry
134 if l[0] == '#' and section == STR:
135 add(msgctxt, msgid, msgstr, fuzzy)
136 section = msgctxt = None
137 fuzzy = 0
138 # Record a fuzzy mark
139 if l[:2] == '#,' and 'fuzzy' in l:
140 fuzzy = 1
141 # Skip comments
142 if l[0] == '#':
143 continue
144 # Now we are in a msgid or msgctxt section, output previous section
145 if l.startswith('msgctxt'):
146 if section == STR:
147 add(msgctxt, msgid, msgstr, fuzzy)
148 section = CTXT
149 l = l[7:]
150 msgctxt = b''
151 elif l.startswith('msgid') and not l.startswith('msgid_plural'):
152 if section == STR:
153 if not msgid:
154 # Filter out POT-Creation-Date
155 # See issue #131852
156 msgstr = b''.join(line for line in msgstr.splitlines(True)
157 if not line.startswith(b'POT-Creation-Date:'))
158
159 # See whether there is an encoding declaration
160 p = HeaderParser()
161 charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
162 if charset:
163 encoding = charset
164 add(msgctxt, msgid, msgstr, fuzzy)
165 msgctxt = None
166 section = ID
167 l = l[5:]
168 msgid = msgstr = b''
169 is_plural = False
170 # This is a message with plural forms
171 elif l.startswith('msgid_plural'):
172 if section != ID:
173 print(f'msgid_plural not preceded by msgid on {infile}:{lno}',
174 file=sys.stderr)
175 sys.exit(1)
176 l = l[12:]
177 msgid += b'\0' # separator of singular and plural
178 is_plural = True
179 # Now we are in a msgstr section
180 elif l.startswith('msgstr'):
181 section = STR
182 if l.startswith('msgstr['):
183 if not is_plural:
184 print(f'plural without msgid_plural on {infile}:{lno}',
185 file=sys.stderr)
186 sys.exit(1)
187 l = l.split(']', 1)[1]
188 if msgstr:
189 msgstr += b'\0' # Separator of the various plural forms
190 else:
191 if is_plural:
192 print(f'indexed msgstr required for plural on {infile}:{lno}',
193 file=sys.stderr)
194 sys.exit(1)
195 l = l[6:]
196 # Skip empty lines
197 l = l.strip()
198 if not l:
199 continue
200 l = ast.literal_eval(l)
201 if section == CTXT:
202 msgctxt += l.encode(encoding)
203 elif section == ID:
204 msgid += l.encode(encoding)
205 elif section == STR:
206 msgstr += l.encode(encoding)
207 else:
208 print(f'Syntax error on {infile}:{lno} before:', file=sys.stderr)
209 print(l, file=sys.stderr)
210 sys.exit(1)
211 # Add last entry
212 if section == STR:
213 add(msgctxt, msgid, msgstr, fuzzy)
214
215 # Compute output
216 output = generate()
217
218 try:
219 with open(outfile,"wb") as f:
220 f.write(output)
221 except OSError as msg:
222 print(msg, file=sys.stderr)
223
224
225 def main():
226 try:
227 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
228 ['help', 'version', 'output-file='])
229 except getopt.error as msg:
230 usage(1, msg)
231
232 outfile = None
233 # parse options
234 for opt, arg in opts:
235 if opt in ('-h', '--help'):
236 usage(0)
237 elif opt in ('-V', '--version'):
238 print("msgfmt.py", __version__)
239 sys.exit(0)
240 elif opt in ('-o', '--output-file'):
241 outfile = arg
242 # do it
243 if not args:
244 print('No input file given', file=sys.stderr)
245 print("Try `msgfmt --help' for more information.", file=sys.stderr)
246 return
247
248 for filename in args:
249 make(filename, outfile)
250
251
252 if __name__ == '__main__':
253 main()