blob: a5544424e2437c4c64e08643ba8dd732e2198b5e [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
8GNU msgfmt program, however, it is a simpler implementation.
9
10Usage: msgfmt.py [OPTIONS] filename.po
11
12Options:
Barry Warsaw78d7dc42001-03-02 16:53:54 +000013 -o file
14 --output-file=file
15 Specify the output file to write to. If omitted, output will go to a
16 file named filename.mo (based off the input file name).
17
Barry Warsaw72dacb82000-09-01 08:10:08 +000018 -h
19 --help
20 Print this message and exit.
21
22 -V
23 --version
24 Display version information and exit.
Barry Warsaw72dacb82000-09-01 08:10:08 +000025"""
26
27import sys
Barry Warsaw78d7dc42001-03-02 16:53:54 +000028import os
Barry Warsaw72dacb82000-09-01 08:10:08 +000029import getopt
30import struct
31import array
Martin v. Löwisb6b81102010-06-04 18:40:55 +000032from email.parser import HeaderParser
Barry Warsaw72dacb82000-09-01 08:10:08 +000033
Barry Warsaw78d7dc42001-03-02 16:53:54 +000034__version__ = "1.1"
Barry Warsaw72dacb82000-09-01 08:10:08 +000035
36MESSAGES = {}
37
38
39
40def usage(code, msg=''):
Collin Winter6afaeb72007-08-03 17:06:41 +000041 print(__doc__, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +000042 if msg:
Collin Winter6afaeb72007-08-03 17:06:41 +000043 print(msg, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +000044 sys.exit(code)
45
46
47
48def add(id, str, fuzzy):
49 "Add a non-fuzzy translation to the dictionary."
50 global MESSAGES
51 if not fuzzy and str:
52 MESSAGES[id] = str
53
54
55
56def generate():
57 "Return the generated output."
58 global MESSAGES
Barry Warsaw72dacb82000-09-01 08:10:08 +000059 # the keys are sorted in the .mo file
Georg Brandlbf82e372008-05-16 17:02:34 +000060 keys = sorted(MESSAGES.keys())
Barry Warsaw72dacb82000-09-01 08:10:08 +000061 offsets = []
Martin v. Löwisb6b81102010-06-04 18:40:55 +000062 ids = strs = b''
Barry Warsaw72dacb82000-09-01 08:10:08 +000063 for id in keys:
64 # For each string, we need size and file offset. Each string is NUL
65 # terminated; the NUL does not count into the size.
66 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
Martin v. Löwisb6b81102010-06-04 18:40:55 +000067 ids += id + b'\0'
68 strs += MESSAGES[id] + b'\0'
Barry Warsaw72dacb82000-09-01 08:10:08 +000069 output = ''
70 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
71 # the keys start right after the index tables.
72 # translated string.
73 keystart = 7*4+16*len(keys)
74 # and the values start after the keys
75 valuestart = keystart + len(ids)
76 koffsets = []
77 voffsets = []
78 # The string table first has the list of keys, then the list of values.
79 # Each entry has first the size of the string, then the file offset.
80 for o1, l1, o2, l2 in offsets:
81 koffsets += [l1, o1+keystart]
82 voffsets += [l2, o2+valuestart]
83 offsets = koffsets + voffsets
Martin v. Löwis8f0bd562003-05-09 08:59:17 +000084 output = struct.pack("Iiiiiii",
Guido van Rossumcd16bf62007-06-13 18:07:49 +000085 0x950412de, # Magic
Barry Warsaw72dacb82000-09-01 08:10:08 +000086 0, # Version
87 len(keys), # # of entries
88 7*4, # start of key index
89 7*4+len(keys)*8, # start of value index
90 0, 0) # size and offset of hash table
91 output += array.array("i", offsets).tostring()
92 output += ids
93 output += strs
94 return output
95
96
97
Barry Warsaw78d7dc42001-03-02 16:53:54 +000098def make(filename, outfile):
Barry Warsaw72dacb82000-09-01 08:10:08 +000099 ID = 1
100 STR = 2
101
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000102 # Compute .mo name from .po name and arguments
Barry Warsaw72dacb82000-09-01 08:10:08 +0000103 if filename.endswith('.po'):
104 infile = filename
Barry Warsaw72dacb82000-09-01 08:10:08 +0000105 else:
106 infile = filename + '.po'
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000107 if outfile is None:
108 outfile = os.path.splitext(infile)[0] + '.mo'
109
Barry Warsaw72dacb82000-09-01 08:10:08 +0000110 try:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000111 lines = open(infile, 'rb').readlines()
Guido van Rossumb940e112007-01-10 16:19:56 +0000112 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000113 print(msg, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000114 sys.exit(1)
Tim Peters182b5ac2004-07-18 06:16:08 +0000115
Barry Warsaw72dacb82000-09-01 08:10:08 +0000116 section = None
117 fuzzy = 0
118
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000119 # Start off assuming Latin-1, so everything decodes without failure,
120 # until we know the exact encoding
121 encoding = 'latin-1'
122
Barry Warsaw72dacb82000-09-01 08:10:08 +0000123 # Parse the catalog
124 lno = 0
125 for l in lines:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000126 l = l.decode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000127 lno += 1
128 # If we get a comment line after a msgstr, this is a new entry
129 if l[0] == '#' and section == STR:
130 add(msgid, msgstr, fuzzy)
131 section = None
132 fuzzy = 0
133 # Record a fuzzy mark
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 if l[:2] == '#,' and 'fuzzy' in l:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000135 fuzzy = 1
136 # Skip comments
137 if l[0] == '#':
138 continue
139 # Now we are in a msgid section, output previous section
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000140 if l.startswith('msgid') and not l.startswith('msgid_plural'):
Barry Warsaw72dacb82000-09-01 08:10:08 +0000141 if section == STR:
142 add(msgid, msgstr, fuzzy)
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000143 if not msgid:
144 # See whether there is an encoding declaration
145 p = HeaderParser()
146 charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
147 if charset:
148 encoding = charset
Barry Warsaw72dacb82000-09-01 08:10:08 +0000149 section = ID
150 l = l[5:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000151 msgid = msgstr = b''
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000152 is_plural = False
153 # This is a message with plural forms
154 elif l.startswith('msgid_plural'):
155 if section != ID:
156 print('msgid_plural not preceeded by msgid on %s:%d' % (infile, lno),
157 file=sys.stderr)
158 sys.exit(1)
159 l = l[12:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000160 msgid += b'\0' # separator of singular and plural
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000161 is_plural = True
Barry Warsaw72dacb82000-09-01 08:10:08 +0000162 # Now we are in a msgstr section
163 elif l.startswith('msgstr'):
164 section = STR
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000165 if l.startswith('msgstr['):
166 if not is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000167 print('plural without msgid_plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000168 file=sys.stderr)
169 sys.exit(1)
170 l = l.split(']', 1)[1]
171 if msgstr:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000172 msgstr += b'\0' # Separator of the various plural forms
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000173 else:
174 if is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000175 print('indexed msgstr required for plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000176 file=sys.stderr)
177 sys.exit(1)
178 l = l[6:]
Barry Warsaw72dacb82000-09-01 08:10:08 +0000179 # Skip empty lines
180 l = l.strip()
181 if not l:
182 continue
183 # XXX: Does this always follow Python escape semantics?
184 l = eval(l)
185 if section == ID:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000186 msgid += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000187 elif section == STR:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000188 msgstr += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000189 else:
Collin Winter6afaeb72007-08-03 17:06:41 +0000190 print('Syntax error on %s:%d' % (infile, lno), \
191 'before:', file=sys.stderr)
192 print(l, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000193 sys.exit(1)
194 # Add last entry
195 if section == STR:
196 add(msgid, msgstr, fuzzy)
197
198 # Compute output
199 output = generate()
200
Barry Warsaw72dacb82000-09-01 08:10:08 +0000201 try:
202 open(outfile,"wb").write(output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000203 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000204 print(msg, file=sys.stderr)
Tim Peters182b5ac2004-07-18 06:16:08 +0000205
Barry Warsaw72dacb82000-09-01 08:10:08 +0000206
207
208def main():
209 try:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000210 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
211 ['help', 'version', 'output-file='])
Guido van Rossumb940e112007-01-10 16:19:56 +0000212 except getopt.error as msg:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000213 usage(1, msg)
214
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000215 outfile = None
Barry Warsaw72dacb82000-09-01 08:10:08 +0000216 # parse options
217 for opt, arg in opts:
218 if opt in ('-h', '--help'):
219 usage(0)
220 elif opt in ('-V', '--version'):
Collin Winter6afaeb72007-08-03 17:06:41 +0000221 print("msgfmt.py", __version__, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000222 sys.exit(0)
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000223 elif opt in ('-o', '--output-file'):
224 outfile = arg
Barry Warsaw72dacb82000-09-01 08:10:08 +0000225 # do it
226 if not args:
Collin Winter6afaeb72007-08-03 17:06:41 +0000227 print('No input file given', file=sys.stderr)
228 print("Try `msgfmt --help' for more information.", file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000229 return
230
231 for filename in args:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000232 make(filename, outfile)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000233
234
235if __name__ == '__main__':
236 main()