Updated Arabic Translation by Djihed Afifi.
[straw.git] / tools / msgfmt.py
blob49ccf3a8c24702ed872a96803f32e18d92829277
1 #! /usr/bin/env python
2 # -*- coding: iso-8859-1 -*-
3 # Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
5 """Generate binary message catalog from textual translation description.
7 This program converts a textual Uniforum-style message catalog (.po file) into
8 a binary GNU catalog (.mo file). This is essentially the same function as the
9 GNU msgfmt program, however, it is a simpler implementation.
11 Usage: msgfmt.py [OPTIONS] filename.po
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).
20 --help
21 Print this message and exit.
24 --version
25 Display version information and exit.
26 """
28 import sys
29 import os
30 import getopt
31 import struct
32 import array
34 __version__ = "1.1"
36 def usage(code, msg=''):
37 print >> sys.stderr, __doc__
38 if msg:
39 print >> sys.stderr, msg
40 sys.exit(code)
42 def add(id, str, fuzzy):
43 "Add a non-fuzzy translation to the dictionary."
44 global MESSAGES
45 if not fuzzy and str:
46 MESSAGES[id] = str
48 def generate():
49 "Return the generated output."
50 global MESSAGES
51 keys = MESSAGES.keys()
52 # the keys are sorted in the .mo file
53 keys.sort()
54 offsets = []
55 ids = strs = ''
56 for id in keys:
57 # For each string, we need size and file offset. Each string is NUL
58 # terminated; the NUL does not count into the size.
59 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
60 ids += id + '\0'
61 strs += MESSAGES[id] + '\0'
62 output = ''
63 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
64 # the keys start right after the index tables.
65 # translated string.
66 keystart = 7*4+16*len(keys)
67 # and the values start after the keys
68 valuestart = keystart + len(ids)
69 koffsets = []
70 voffsets = []
71 # The string table first has the list of keys, then the list of values.
72 # Each entry has first the size of the string, then the file offset.
73 for o1, l1, o2, l2 in offsets:
74 koffsets += [l1, o1+keystart]
75 voffsets += [l2, o2+valuestart]
76 offsets = koffsets + voffsets
77 output = struct.pack("Iiiiiii",
78 0x950412deL, # Magic
79 0, # Version
80 len(keys), # # of entries
81 7*4, # start of key index
82 7*4+len(keys)*8, # start of value index
83 0, 0) # size and offset of hash table
84 output += array.array("i", offsets).tostring()
85 output += ids
86 output += strs
87 return output
91 def make(filename, outfile):
92 global MESSAGES
93 MESSAGES = {}
94 ID = 1
95 STR = 2
97 # Compute .mo name from .po name and arguments
98 if filename.endswith('.po'):
99 infile = filename
100 else:
101 infile = filename + '.po'
102 if outfile is None:
103 outfile = os.path.splitext(infile)[0] + '.mo'
105 try:
106 lines = open(infile).readlines()
107 except IOError, msg:
108 print >> sys.stderr, msg
109 sys.exit(1)
111 section = None
112 fuzzy = 0
114 # Parse the catalog
115 lno = 0
116 for l in lines:
117 lno += 1
118 # If we get a comment line after a msgstr, this is a new entry
119 if l[0] == '#' and section == STR:
120 add(msgid, msgstr, fuzzy)
121 section = None
122 fuzzy = 0
123 # Record a fuzzy mark
124 if l[:2] == '#,' and l.count('fuzzy'):
125 fuzzy = 1
126 # Skip comments
127 if l[0] == '#':
128 continue
129 # Now we are in a msgid section, output previous section
130 if l.startswith('msgid'):
131 if section == STR:
132 add(msgid, msgstr, fuzzy)
133 section = ID
134 l = l[5:]
135 msgid = msgstr = ''
136 # Now we are in a msgstr section
137 elif l.startswith('msgstr'):
138 section = STR
139 l = l[6:]
140 # Skip empty lines
141 l = l.strip()
142 if not l:
143 continue
144 # XXX: Does this always follow Python escape semantics?
145 l = eval(l)
146 if section == ID:
147 msgid += l
148 elif section == STR:
149 msgstr += l
150 else:
151 print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
152 'before:'
153 print >> sys.stderr, l
154 sys.exit(1)
155 # Add last entry
156 if section == STR:
157 add(msgid, msgstr, fuzzy)
159 # Compute output
160 output = generate()
162 try:
163 open(outfile,"wb").write(output)
164 except IOError,msg:
165 print >> sys.stderr, msg
169 def main():
170 try:
171 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
172 ['help', 'version', 'output-file='])
173 except getopt.error, msg:
174 usage(1, msg)
176 outfile = None
177 # parse options
178 for opt, arg in opts:
179 if opt in ('-h', '--help'):
180 usage(0)
181 elif opt in ('-V', '--version'):
182 print >> sys.stderr, "msgfmt.py", __version__
183 sys.exit(0)
184 elif opt in ('-o', '--output-file'):
185 outfile = arg
186 # do it
187 if not args:
188 print >> sys.stderr, 'No input file given'
189 print >> sys.stderr, "Try `msgfmt --help' for more information."
190 return
192 for filename in args:
193 make(filename, outfile)
196 if __name__ == '__main__':
197 main()