blob: 3f731e941eafe77418e9e8c451a52170ee2bc8fa [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Alexander Belopolskye8f58322010-10-15 16:28:20 +00002# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
Barry Warsaw72dacb82000-09-01 08:10:08 +00003
4"""Generate binary message catalog from textual translation description.
5
6This program converts a textual Uniforum-style message catalog (.po file) into
7a binary GNU catalog (.mo file). This is essentially the same function as the
Cheryl Sabella637a33b2018-11-07 09:12:20 -05008GNU msgfmt program, however, it is a simpler implementation. Currently it
9does not handle plural forms but it does handle message contexts.
Barry Warsaw72dacb82000-09-01 08:10:08 +000010
11Usage: msgfmt.py [OPTIONS] filename.po
12
13Options:
Barry Warsaw78d7dc42001-03-02 16:53:54 +000014 -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
Barry Warsaw72dacb82000-09-01 08:10:08 +000019 -h
20 --help
21 Print this message and exit.
22
23 -V
24 --version
25 Display version information and exit.
Barry Warsaw72dacb82000-09-01 08:10:08 +000026"""
27
Barry Warsaw78d7dc42001-03-02 16:53:54 +000028import os
Ezio Melotti9bf379e2012-11-09 11:46:19 +010029import sys
30import ast
Barry Warsaw72dacb82000-09-01 08:10:08 +000031import getopt
32import struct
33import array
Martin v. Löwisb6b81102010-06-04 18:40:55 +000034from email.parser import HeaderParser
Barry Warsaw72dacb82000-09-01 08:10:08 +000035
Cheryl Sabella637a33b2018-11-07 09:12:20 -050036__version__ = "1.2"
Barry Warsaw72dacb82000-09-01 08:10:08 +000037
38MESSAGES = {}
39
40
Barry Warsaw72dacb82000-09-01 08:10:08 +000041def usage(code, msg=''):
Collin Winter6afaeb72007-08-03 17:06:41 +000042 print(__doc__, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +000043 if msg:
Collin Winter6afaeb72007-08-03 17:06:41 +000044 print(msg, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +000045 sys.exit(code)
46
47
Cheryl Sabella637a33b2018-11-07 09:12:20 -050048def add(ctxt, id, str, fuzzy):
Barry Warsaw72dacb82000-09-01 08:10:08 +000049 "Add a non-fuzzy translation to the dictionary."
50 global MESSAGES
51 if not fuzzy and str:
Cheryl Sabella637a33b2018-11-07 09:12:20 -050052 if ctxt is None:
53 MESSAGES[id] = str
54 else:
55 MESSAGES[b"%b\x04%b" % (ctxt, id)] = str
Barry Warsaw72dacb82000-09-01 08:10:08 +000056
57
Barry Warsaw72dacb82000-09-01 08:10:08 +000058def generate():
59 "Return the generated output."
60 global MESSAGES
Barry Warsaw72dacb82000-09-01 08:10:08 +000061 # the keys are sorted in the .mo file
Georg Brandlbf82e372008-05-16 17:02:34 +000062 keys = sorted(MESSAGES.keys())
Barry Warsaw72dacb82000-09-01 08:10:08 +000063 offsets = []
Martin v. Löwisb6b81102010-06-04 18:40:55 +000064 ids = strs = b''
Barry Warsaw72dacb82000-09-01 08:10:08 +000065 for id in keys:
66 # For each string, we need size and file offset. Each string is NUL
67 # terminated; the NUL does not count into the size.
68 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
Martin v. Löwisb6b81102010-06-04 18:40:55 +000069 ids += id + b'\0'
70 strs += MESSAGES[id] + b'\0'
Barry Warsaw72dacb82000-09-01 08:10:08 +000071 output = ''
72 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
73 # the keys start right after the index tables.
74 # translated string.
75 keystart = 7*4+16*len(keys)
76 # and the values start after the keys
77 valuestart = keystart + len(ids)
78 koffsets = []
79 voffsets = []
80 # The string table first has the list of keys, then the list of values.
81 # Each entry has first the size of the string, then the file offset.
82 for o1, l1, o2, l2 in offsets:
83 koffsets += [l1, o1+keystart]
84 voffsets += [l2, o2+valuestart]
85 offsets = koffsets + voffsets
Martin v. Löwis8f0bd562003-05-09 08:59:17 +000086 output = struct.pack("Iiiiiii",
Guido van Rossumcd16bf62007-06-13 18:07:49 +000087 0x950412de, # Magic
Barry Warsaw72dacb82000-09-01 08:10:08 +000088 0, # Version
89 len(keys), # # of entries
90 7*4, # start of key index
91 7*4+len(keys)*8, # start of value index
92 0, 0) # size and offset of hash table
Xtreaka692efe2018-07-21 11:52:12 +053093 output += array.array("i", offsets).tobytes()
Barry Warsaw72dacb82000-09-01 08:10:08 +000094 output += ids
95 output += strs
96 return output
97
98
Barry Warsaw78d7dc42001-03-02 16:53:54 +000099def make(filename, outfile):
Barry Warsaw72dacb82000-09-01 08:10:08 +0000100 ID = 1
101 STR = 2
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500102 CTXT = 3
Barry Warsaw72dacb82000-09-01 08:10:08 +0000103
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000104 # Compute .mo name from .po name and arguments
Barry Warsaw72dacb82000-09-01 08:10:08 +0000105 if filename.endswith('.po'):
106 infile = filename
Barry Warsaw72dacb82000-09-01 08:10:08 +0000107 else:
108 infile = filename + '.po'
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000109 if outfile is None:
110 outfile = os.path.splitext(infile)[0] + '.mo'
111
Barry Warsaw72dacb82000-09-01 08:10:08 +0000112 try:
Xtreaka692efe2018-07-21 11:52:12 +0530113 with open(infile, 'rb') as f:
114 lines = f.readlines()
Guido van Rossumb940e112007-01-10 16:19:56 +0000115 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000116 print(msg, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000117 sys.exit(1)
Tim Peters182b5ac2004-07-18 06:16:08 +0000118
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500119 section = msgctxt = None
Barry Warsaw72dacb82000-09-01 08:10:08 +0000120 fuzzy = 0
121
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000122 # Start off assuming Latin-1, so everything decodes without failure,
123 # until we know the exact encoding
124 encoding = 'latin-1'
125
Barry Warsaw72dacb82000-09-01 08:10:08 +0000126 # Parse the catalog
127 lno = 0
128 for l in lines:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000129 l = l.decode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000130 lno += 1
131 # If we get a comment line after a msgstr, this is a new entry
132 if l[0] == '#' and section == STR:
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500133 add(msgctxt, msgid, msgstr, fuzzy)
134 section = msgctxt = None
Barry Warsaw72dacb82000-09-01 08:10:08 +0000135 fuzzy = 0
136 # Record a fuzzy mark
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000137 if l[:2] == '#,' and 'fuzzy' in l:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000138 fuzzy = 1
139 # Skip comments
140 if l[0] == '#':
141 continue
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500142 # Now we are in a msgid or msgctxt section, output previous section
143 if l.startswith('msgctxt'):
Barry Warsaw72dacb82000-09-01 08:10:08 +0000144 if section == STR:
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500145 add(msgctxt, msgid, msgstr, fuzzy)
146 section = CTXT
147 l = l[7:]
148 msgctxt = b''
149 elif l.startswith('msgid') and not l.startswith('msgid_plural'):
150 if section == STR:
151 add(msgctxt, msgid, msgstr, fuzzy)
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000152 if not msgid:
153 # See whether there is an encoding declaration
154 p = HeaderParser()
155 charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
156 if charset:
157 encoding = charset
Barry Warsaw72dacb82000-09-01 08:10:08 +0000158 section = ID
159 l = l[5:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000160 msgid = msgstr = b''
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000161 is_plural = False
162 # This is a message with plural forms
163 elif l.startswith('msgid_plural'):
164 if section != ID:
Ezio Melotti7c4a7e62013-08-26 01:32:56 +0300165 print('msgid_plural not preceded by msgid on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000166 file=sys.stderr)
167 sys.exit(1)
168 l = l[12:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000169 msgid += b'\0' # separator of singular and plural
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000170 is_plural = True
Barry Warsaw72dacb82000-09-01 08:10:08 +0000171 # Now we are in a msgstr section
172 elif l.startswith('msgstr'):
173 section = STR
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000174 if l.startswith('msgstr['):
175 if not is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000176 print('plural without msgid_plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000177 file=sys.stderr)
178 sys.exit(1)
179 l = l.split(']', 1)[1]
180 if msgstr:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000181 msgstr += b'\0' # Separator of the various plural forms
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000182 else:
183 if is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000184 print('indexed msgstr required for plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000185 file=sys.stderr)
186 sys.exit(1)
187 l = l[6:]
Barry Warsaw72dacb82000-09-01 08:10:08 +0000188 # Skip empty lines
189 l = l.strip()
190 if not l:
191 continue
Ezio Melotti9bf379e2012-11-09 11:46:19 +0100192 l = ast.literal_eval(l)
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500193 if section == CTXT:
194 msgctxt += l.encode(encoding)
195 elif section == ID:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000196 msgid += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000197 elif section == STR:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000198 msgstr += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000199 else:
Collin Winter6afaeb72007-08-03 17:06:41 +0000200 print('Syntax error on %s:%d' % (infile, lno), \
201 'before:', file=sys.stderr)
202 print(l, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000203 sys.exit(1)
204 # Add last entry
205 if section == STR:
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500206 add(msgctxt, msgid, msgstr, fuzzy)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000207
208 # Compute output
209 output = generate()
210
Barry Warsaw72dacb82000-09-01 08:10:08 +0000211 try:
Xtreaka692efe2018-07-21 11:52:12 +0530212 with open(outfile,"wb") as f:
213 f.write(output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000214 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000215 print(msg, file=sys.stderr)
Tim Peters182b5ac2004-07-18 06:16:08 +0000216
Barry Warsaw72dacb82000-09-01 08:10:08 +0000217
Barry Warsaw72dacb82000-09-01 08:10:08 +0000218def main():
219 try:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000220 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
221 ['help', 'version', 'output-file='])
Guido van Rossumb940e112007-01-10 16:19:56 +0000222 except getopt.error as msg:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000223 usage(1, msg)
224
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000225 outfile = None
Barry Warsaw72dacb82000-09-01 08:10:08 +0000226 # parse options
227 for opt, arg in opts:
228 if opt in ('-h', '--help'):
229 usage(0)
230 elif opt in ('-V', '--version'):
Serhiy Storchakac56894d2013-09-05 17:44:53 +0300231 print("msgfmt.py", __version__)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000232 sys.exit(0)
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000233 elif opt in ('-o', '--output-file'):
234 outfile = arg
Barry Warsaw72dacb82000-09-01 08:10:08 +0000235 # do it
236 if not args:
Collin Winter6afaeb72007-08-03 17:06:41 +0000237 print('No input file given', file=sys.stderr)
238 print("Try `msgfmt --help' for more information.", file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000239 return
240
241 for filename in args:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000242 make(filename, outfile)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000243
244
245if __name__ == '__main__':
246 main()