blob: 63d52d1f46e561438b5375dfd87860d6ae27fd15 [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
Barry Warsaw78d7dc42001-03-02 16:53:54 +000027import os
Ezio Melotti9bf379e2012-11-09 11:46:19 +010028import sys
29import ast
Barry Warsaw72dacb82000-09-01 08:10:08 +000030import getopt
31import struct
32import array
Martin v. Löwisb6b81102010-06-04 18:40:55 +000033from email.parser import HeaderParser
Barry Warsaw72dacb82000-09-01 08:10:08 +000034
Barry Warsaw78d7dc42001-03-02 16:53:54 +000035__version__ = "1.1"
Barry Warsaw72dacb82000-09-01 08:10:08 +000036
37MESSAGES = {}
38
39
40
41def 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
48
49def add(id, str, fuzzy):
50 "Add a non-fuzzy translation to the dictionary."
51 global MESSAGES
52 if not fuzzy and str:
53 MESSAGES[id] = str
54
55
56
57def generate():
58 "Return the generated output."
59 global MESSAGES
Barry Warsaw72dacb82000-09-01 08:10:08 +000060 # the keys are sorted in the .mo file
Georg Brandlbf82e372008-05-16 17:02:34 +000061 keys = sorted(MESSAGES.keys())
Barry Warsaw72dacb82000-09-01 08:10:08 +000062 offsets = []
Martin v. Löwisb6b81102010-06-04 18:40:55 +000063 ids = strs = b''
Barry Warsaw72dacb82000-09-01 08:10:08 +000064 for id in keys:
65 # For each string, we need size and file offset. Each string is NUL
66 # terminated; the NUL does not count into the size.
67 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
Martin v. Löwisb6b81102010-06-04 18:40:55 +000068 ids += id + b'\0'
69 strs += MESSAGES[id] + b'\0'
Barry Warsaw72dacb82000-09-01 08:10:08 +000070 output = ''
71 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
72 # the keys start right after the index tables.
73 # translated string.
74 keystart = 7*4+16*len(keys)
75 # and the values start after the keys
76 valuestart = keystart + len(ids)
77 koffsets = []
78 voffsets = []
79 # The string table first has the list of keys, then the list of values.
80 # Each entry has first the size of the string, then the file offset.
81 for o1, l1, o2, l2 in offsets:
82 koffsets += [l1, o1+keystart]
83 voffsets += [l2, o2+valuestart]
84 offsets = koffsets + voffsets
Martin v. Löwis8f0bd562003-05-09 08:59:17 +000085 output = struct.pack("Iiiiiii",
Guido van Rossumcd16bf62007-06-13 18:07:49 +000086 0x950412de, # Magic
Barry Warsaw72dacb82000-09-01 08:10:08 +000087 0, # Version
88 len(keys), # # of entries
89 7*4, # start of key index
90 7*4+len(keys)*8, # start of value index
91 0, 0) # size and offset of hash table
Xtreaka692efe2018-07-21 11:52:12 +053092 output += array.array("i", offsets).tobytes()
Barry Warsaw72dacb82000-09-01 08:10:08 +000093 output += ids
94 output += strs
95 return output
96
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
102
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000103 # Compute .mo name from .po name and arguments
Barry Warsaw72dacb82000-09-01 08:10:08 +0000104 if filename.endswith('.po'):
105 infile = filename
Barry Warsaw72dacb82000-09-01 08:10:08 +0000106 else:
107 infile = filename + '.po'
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000108 if outfile is None:
109 outfile = os.path.splitext(infile)[0] + '.mo'
110
Barry Warsaw72dacb82000-09-01 08:10:08 +0000111 try:
Xtreaka692efe2018-07-21 11:52:12 +0530112 with open(infile, 'rb') as f:
113 lines = f.readlines()
Guido van Rossumb940e112007-01-10 16:19:56 +0000114 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000115 print(msg, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000116 sys.exit(1)
Tim Peters182b5ac2004-07-18 06:16:08 +0000117
Barry Warsaw72dacb82000-09-01 08:10:08 +0000118 section = None
119 fuzzy = 0
120
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000121 # Start off assuming Latin-1, so everything decodes without failure,
122 # until we know the exact encoding
123 encoding = 'latin-1'
124
Barry Warsaw72dacb82000-09-01 08:10:08 +0000125 # Parse the catalog
126 lno = 0
127 for l in lines:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000128 l = l.decode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000129 lno += 1
130 # If we get a comment line after a msgstr, this is a new entry
131 if l[0] == '#' and section == STR:
132 add(msgid, msgstr, fuzzy)
133 section = None
134 fuzzy = 0
135 # Record a fuzzy mark
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136 if l[:2] == '#,' and 'fuzzy' in l:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000137 fuzzy = 1
138 # Skip comments
139 if l[0] == '#':
140 continue
141 # Now we are in a msgid section, output previous section
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000142 if l.startswith('msgid') and not l.startswith('msgid_plural'):
Barry Warsaw72dacb82000-09-01 08:10:08 +0000143 if section == STR:
144 add(msgid, msgstr, fuzzy)
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000145 if not msgid:
146 # See whether there is an encoding declaration
147 p = HeaderParser()
148 charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
149 if charset:
150 encoding = charset
Barry Warsaw72dacb82000-09-01 08:10:08 +0000151 section = ID
152 l = l[5:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000153 msgid = msgstr = b''
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000154 is_plural = False
155 # This is a message with plural forms
156 elif l.startswith('msgid_plural'):
157 if section != ID:
Ezio Melotti7c4a7e62013-08-26 01:32:56 +0300158 print('msgid_plural not preceded by msgid on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000159 file=sys.stderr)
160 sys.exit(1)
161 l = l[12:]
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000162 msgid += b'\0' # separator of singular and plural
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000163 is_plural = True
Barry Warsaw72dacb82000-09-01 08:10:08 +0000164 # Now we are in a msgstr section
165 elif l.startswith('msgstr'):
166 section = STR
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000167 if l.startswith('msgstr['):
168 if not is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000169 print('plural without msgid_plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000170 file=sys.stderr)
171 sys.exit(1)
172 l = l.split(']', 1)[1]
173 if msgstr:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000174 msgstr += b'\0' # Separator of the various plural forms
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000175 else:
176 if is_plural:
Martin v. Löwis25fcd392010-07-11 17:39:46 +0000177 print('indexed msgstr required for plural on %s:%d' % (infile, lno),
Martin v. Löwiscb081b82010-06-04 18:14:42 +0000178 file=sys.stderr)
179 sys.exit(1)
180 l = l[6:]
Barry Warsaw72dacb82000-09-01 08:10:08 +0000181 # Skip empty lines
182 l = l.strip()
183 if not l:
184 continue
Ezio Melotti9bf379e2012-11-09 11:46:19 +0100185 l = ast.literal_eval(l)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000186 if section == ID:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000187 msgid += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000188 elif section == STR:
Martin v. Löwisb6b81102010-06-04 18:40:55 +0000189 msgstr += l.encode(encoding)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000190 else:
Collin Winter6afaeb72007-08-03 17:06:41 +0000191 print('Syntax error on %s:%d' % (infile, lno), \
192 'before:', file=sys.stderr)
193 print(l, file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000194 sys.exit(1)
195 # Add last entry
196 if section == STR:
197 add(msgid, msgstr, fuzzy)
198
199 # Compute output
200 output = generate()
201
Barry Warsaw72dacb82000-09-01 08:10:08 +0000202 try:
Xtreaka692efe2018-07-21 11:52:12 +0530203 with open(outfile,"wb") as f:
204 f.write(output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000205 except IOError as msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000206 print(msg, file=sys.stderr)
Tim Peters182b5ac2004-07-18 06:16:08 +0000207
Barry Warsaw72dacb82000-09-01 08:10:08 +0000208
209
210def main():
211 try:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000212 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
213 ['help', 'version', 'output-file='])
Guido van Rossumb940e112007-01-10 16:19:56 +0000214 except getopt.error as msg:
Barry Warsaw72dacb82000-09-01 08:10:08 +0000215 usage(1, msg)
216
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000217 outfile = None
Barry Warsaw72dacb82000-09-01 08:10:08 +0000218 # parse options
219 for opt, arg in opts:
220 if opt in ('-h', '--help'):
221 usage(0)
222 elif opt in ('-V', '--version'):
Serhiy Storchakac56894d2013-09-05 17:44:53 +0300223 print("msgfmt.py", __version__)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000224 sys.exit(0)
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000225 elif opt in ('-o', '--output-file'):
226 outfile = arg
Barry Warsaw72dacb82000-09-01 08:10:08 +0000227 # do it
228 if not args:
Collin Winter6afaeb72007-08-03 17:06:41 +0000229 print('No input file given', file=sys.stderr)
230 print("Try `msgfmt --help' for more information.", file=sys.stderr)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000231 return
232
233 for filename in args:
Barry Warsaw78d7dc42001-03-02 16:53:54 +0000234 make(filename, outfile)
Barry Warsaw72dacb82000-09-01 08:10:08 +0000235
236
237if __name__ == '__main__':
238 main()