d05c7118366880099f62e0daf82aa4b96c4d4a54
[iso_3166_1.git] / _sources / make.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 ####################################################
4 # Copyright © 2009 Luxia SAS. All rights reserved. #
5 # #
6 # Contributors: #
7 # - Benoît Pin <pinbe@luxia.fr> #
8 ####################################################
9 """ generates python, po and mo files from xml sources.
10
11
12
13 """
14
15
16 import os
17 from xml.dom.minidom import parse
18 from os.path import exists, sep
19 from os import mkdir
20 from subprocess import Popen
21
22 POHEADER ="""msgid ""
23 msgstr ""
24 "Project-Id-Version: ISO-3166_1\\n"
25 "MIME-Version: 1.0\\n"
26 "Content-Type: text/plain; charset=%(charset)s\\n"
27 "Content-Transfer-Encoding: 8bit\\n"
28 "Language-Code: %(lang)s\\n"
29 "Preferred-Encodings: %(charset)s latin1\\n"
30 "Domain: iso_3166_1\\n"
31
32 """
33
34 def main():
35 xmlFileNames = [name for name in os.listdir('.') if not name.startswith('.') and name.endswith('.xml')]
36
37 for name in xmlFileNames:
38 lang = os.path.splitext(name)[0].split('_')[-1]
39 entries = getEntries(name)
40 makePy(lang, entries)
41 makePo(lang, entries)
42
43
44
45
46 def getEntries(name):
47 d = parse(name)
48 countries = []
49 for entry in d.documentElement.getElementsByTagName('ISO_3166-1_Entry') :
50 code = entry.getElementsByTagName('ISO_3166-1_Alpha-2_code')[0].firstChild.nodeValue
51 value = entry.getElementsByTagName('ISO_3166-1_Country_name')[0].firstChild.nodeValue
52 countries.append((code, value))
53
54 return countries
55
56 def makePy(lang, entries, encoding='utf-8'):
57 out = open('../%s.py' % lang, 'w')
58 out.write('# -*- coding: %s -*-\n\n' % encoding)
59 out.write('__allow_access_to_unprotected_subobjects__ = 1\n\n')
60 out.write('countries = (\n')
61
62 for e in entries :
63 encodedEntry = tuple(map(lambda s : s.encode(encoding), e))
64 out.write(''' ('%s', "%s"),\n''' % encodedEntry)
65
66 out.write(' )')
67 out.close()
68
69 def makePo(lang, entries, encoding='utf-8'):
70 path = ('..', 'locales', lang, 'LC_MESSAGES')
71 poFilepath = ''
72 for p in path :
73 poFilepath = poFilepath + p + sep
74 if not exists(poFilepath) :
75 mkdir(poFilepath)
76
77 poFilepath = poFilepath + 'iso_3166_1.po'
78 out = open(poFilepath, 'w')
79
80 header = POHEADER % {'charset':encoding, 'lang':lang}
81 out.write(header)
82
83 for e in entries :
84 id, msg = tuple(map(lambda s : s.encode(encoding), e))
85 out.write('msgid "%s"\n' % id)
86 out.write('msgstr "%s"\n\n' % msg)
87 out.close()
88
89 moFilepath = poFilepath[:-3] + '.mo'
90 MSGFMT = "msgfmt -o %s %s" % (moFilepath, poFilepath)
91 p = Popen(MSGFMT, shell=True)
92 p.wait()
93
94
95
96 if __name__ == '__main__' :
97 main()