2
# -*- coding: iso-8859-1 -*-
4
# PYTHON MODULE: MKI18N.PY
7
# Abstract: Make Internationalization (i18n) files for an application.
8
# Copyright Pierre Rouleau. 2003. Released to public domain.
9
# Last update: Saturday, November 8, 2003. @ 15:55:18.
10
# File: ROUP2003N01::C:/dev/python/mki18n.py
13
# - File updated: Thursday, June 12, 2007 by Cody Precord
14
# - File created: Saturday, June 7, 2003. by Pierre Rouleau
15
# - 07/12/07: Make it work with current wx code and clean up code CJP
16
# - 10/06/03 rcs : RCS Revision 1.1 2003/06/10 10:06:12 PRouleau
17
# - 10/06/03 rcs : RCS Initial revision
18
# - 23/08/03 rcs : RCS Revision 1.2 2003/06/10 10:54:27 PRouleau
19
# - 23/08/03 P.R.: [code:fix] : The strings encoded in this file are encode
20
# in iso-8859-1 format. Added the encoding
21
# notification to Python to comply with Python's 2.3 PEP 263.
22
# - 23/08/03 P.R.: [feature:new] : Added the '-e' switch which is used to
23
# force the creation of the empty English
25
# - 22/10/03 P.R.: [code] : incorporated utility functions in here
26
# to make script self sufficient.
27
# - 05/11/03 rcs : RCS Revision 1.4 2003/10/22 06:39:31 PRouleau
28
# - 05/11/03 P.R.: [code:fix] : included the unixpath() in this file.
29
# - 08/11/03 rcs : RCS Revision 1.5 2003/11/05 19:40:04 PRouleau
34
# -----------------------------------------------------------------------------
36
mki18n allows you to internationalize your software. You can use it to
37
create the GNU .po files (Portable Object) and the compiled .mo files
40
mki18n module can be used from the command line or from within a script (see
41
the Usage at the end of this page).
45
makePO() -- Build the Portable Object file for the application --
46
catPO() -- Concatenate one or several PO files with the application
48
makeMO() -- Compile the Portable Object files into the Machine Object
49
stored in the right location.
50
printUsage -- Displays how to use this script from the command line --
51
Scriptexecution -- Runs when invoked from the command line --
53
NOTE: this module uses GNU gettext utilities.
55
You can get the gettext tools from the following sites:
57
- `GNU FTP site for gettetx`_ where several versions
58
(0.10.40, 0.11.2, 0.11.5 and 0.12.1) are available.
59
Note that you need to use `GNU libiconv`_ to use this. Get it from the
61
libiconv ftp site`_ and get version 1.9.1 or later. Get the Windows .ZIP
62
files and install the packages inside c:/gnu. All binaries will be stored
63
inside c:/gnu/bin. Just put c:/gnu/bin inside your PATH. You will need
66
- `gettext-runtime-0.12.1.bin.woe32.zip`_
67
- `gettext-tools-0.12.1.bin.woe32.zip`_
68
- `libiconv-1.9.1.bin.woe32.zip`_
71
.. _GNU libiconv: http://www.gnu.org/software/libiconv/
72
.. _GNU libiconv ftp site: http://www.ibiblio.org/pub/gnu/libiconv/
73
.. _gettext-runtime-0.12.1.bin.woe32.zip:
74
ftp://ftp.gnu.org/gnu/gettext/gettext-runtime-0.12.1.bin.woe32.zip
75
.. _gettext-tools-0.12.1.bin.woe32.zip:
76
.. ftp://ftp.gnu.org/gnu/gettext/gettext-tools-0.12.1.bin.woe32.zip
77
.. _libiconv-1.9.1.bin.woe32.zip:
78
http://www.ibiblio.org/pub/gnu/libiconv/libiconv-1.9.1.bin.woe32.zip
81
# -----------------------------------------------------------------------------
88
# -----------------------------------------------------------------------------
93
__author__ = "Pierre Rouleau"
94
__version__ = "$Revision: 70029 $"
96
# -----------------------------------------------------------------------------
98
def getlanguageDict():
99
"""Get a dictionary of the available languages from wx"""
102
for lang in [x for x in dir(wx) if x.startswith("LANGUAGE")]:
103
i = wx.Locale(wx.LANGUAGE_DEFAULT).GetLanguageInfo(getattr(wx, lang))
105
lang_dict[i.CanonicalName] = i.Description
108
# -----------------------------------------------------------------------------
109
# m a k e P O ( ) -- Build the Portable Object file for the application --
112
def makePO(app_dir, app_domain=None, verbose=0) :
113
"""Build the Portable Object Template file for the application.
115
makePO builds the .pot file for the application stored inside
116
a specified directory by running xgettext for all application source
117
files. It finds the name of all files by looking for a file called
119
If this file does not exists, makePo raises an IOError exception.
120
By default the application domain (the application
121
name) is the same as the directory name but it can be overridden by the
122
'applicationDomain' argument.
124
makePO always creates a new file called messages.pot. If it finds files
125
of the form app_xx.po where 'app' is the application name and 'xx' is one
126
of the ISO 639 two-letter language codes, makePO resynchronizes those
127
files with the latest extracted strings (now contained in messages.pot).
128
This process updates all line location number in the language-specific
129
.po files and may also create new entries for translation (or comment out
130
some). The .po file is not changed, instead a new file is created with
131
the .new extension appended to the name of the .po file.
133
By default the function does not display what it is doing. Set the
134
verbose argument to 1 to force it to print its commands.
137
if app_domain is None:
138
app_name = fileBaseOf(app_dir, withPath=0)
140
app_name = app_domain
141
curr_dir = os.getcwd()
143
if not os.path.exists('app.fil'):
144
raise IOError(2,'No module file: app.fil')
147
# Use xgettext to parse all application modules
148
# The following switches are used:
150
# -s : sort output by string content
151
# (easier to use when we need to merge several .po files)
152
# --files-from=app.fil : The list of files is taken from the file: app.fil
153
# --output= : specifies the name of the output file
154
# (using a .pot extension)
155
cmd = 'xgettext -s --from-code=utf-8 --no-wrap --files-from=app.fil --output=Editra.pot'
160
lang_dict = getlanguageDict()
161
for lang_code in lang_dict.keys():
162
if lang_code == 'en':
165
lang_po_filename = "%s_%s.po" % (app_name, lang_code)
166
if os.path.exists(lang_po_filename):
167
cmd = 'msgmerge -s --no-wrap "%s" Editra.pot > "%s.new"' % \
168
(lang_po_filename, lang_po_filename)
174
# -----------------------------------------------------------------------------
176
# -- Concatenate one or several PO files with the application domain files. --
179
def catPO(app_dir, listOf_extraPo, app_domain=None, \
180
target_dir=None, verbose=0) :
181
"""Concatenate one or several PO files with the application domain files.
184
if app_domain is None:
185
app_name = fileBaseOf(app_dir, withPath=0)
187
app_name = app_domain
188
curr_dir = os.getcwd()
191
lang_dict = getlanguageDict()
193
for lang_code in lang_dict.keys():
194
if lang_code == 'en':
197
lang_po_fname = "%s_%s.po" % (app_name, lang_code)
198
if os.path.exists(lang_po_fname):
200
for fname in listOf_extraPo:
201
fileList += ("%s_%s.po " % (fname, lang_code))
202
cmd = "msgcat -s --no-wrap %s %s > %s.cat" % (lang_po_fname, \
208
if target_dir is None:
211
mo_targetDir = "%s/%s/LC_MESSAGES" % (target_dir, lang_code)
212
cmd = "msgfmt --output-file=%s/%s.mo %s_%s.po.cat" % \
213
(mo_targetDir, app_name, app_name, lang_code)
219
# -----------------------------------------------------------------------------
220
# m a k e M O ( ) Compile the POfiles into the MO stored in the right location.
223
def makeMO(applicationDirectoryPath, targetDir='./locale',
224
applicationDomain=None, verbose=0, forceEnglish=0) :
225
"""Compile the Portable Object files into the Machine Object stored in the
228
makeMO converts all translated language-specific PO files located inside
229
the application directory into the binary .MO files stored inside the
230
LC_MESSAGES sub-directory for the found locale files.
232
makeMO searches for all files that have a name of the form 'app_xx.po'
233
inside the application directory specified by the first argument. The
234
'app' is the application domain name (that can be specified by the
235
applicationDomain argument or is taken from the directory name). The 'xx'
236
corresponds to one of the ISO 639 two-letter language codes.
238
makeMo stores the resulting files inside a sub-directory of `targetDir`
239
called xx/LC_MESSAGES where 'xx' corresponds to the 2-letter language
242
if targetDir is None:
243
targetDir = './locale'
245
print "Target directory for .mo files is: %s" % targetDir
247
if applicationDomain is None:
248
applicationName = fileBaseOf(applicationDirectoryPath, withPath=0)
250
applicationName = applicationDomain
251
currentDir = os.getcwd()
252
os.chdir(applicationDirectoryPath)
254
languageDict = getlanguageDict()
256
for langCode in languageDict.keys():
257
if (langCode == 'en') and (forceEnglish==0):
260
langPOfileName = "%s_%s.po" % (applicationName, langCode)
261
if os.path.exists(langPOfileName):
262
mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir, langCode)
263
if not os.path.exists(mo_targetDir):
265
cmd = 'msgfmt --output-file="%s/%s.mo" "%s_%s.po"' % \
266
(mo_targetDir, applicationName, applicationName, langCode)
272
# -----------------------------------------------------------------------------
273
# printUsage -- Displays how to use this script from the command line --
274
# ^^^^^^^^^^^^^^^^^^^
276
def printUsage(errorMsg=None):
277
"""Displays how to use this script from the command line."""
279
###########################################################################
280
# mki18n : Make internationalization files. #
281
# Uses the GNU gettext system to create PO (Portable Object) #
282
# files from source code, compile PO into MO (Machine Object) #
284
# Supports C, C++, and Python source files. #
286
# Usage: mki18n {OPTION} [appDirPath] #
289
# -e : When -m is used, forces English .mo file #
291
# -h : prints this help #
292
# -m : make MO from existing PO files #
293
# -p : make PO, update PO files: Creates a new #
294
# messages.pot file. Creates a dom_xx.po.new for #
295
# every existing language specific .po file. #
296
# ('xx' stands for the ISO639 two-letter language #
297
# code and 'dom' stands for the application domain #
298
# name). mki18n requires that you write a #
299
# 'app.fil' file which contains the list of all #
300
# source code to parse. #
301
# -v : verbose (prints comments while running) #
302
# --domain=appName : specifies the application domain name. #
303
# By default the directory name is used. #
304
# --moTarget=dir : specifies the directory where .mo files are stored.#
305
# If not specified, the target is './locale' #
307
# You must specify one of the -p or -m option to perform the work. You #
308
# can specify the path of the target application. If you leave it out #
309
# mki18n will use the current directory as the application main #
311
###########################################################################
314
print "\n ERROR: %s" % errorMsg
316
# -----------------------------------------------------------------------------
317
# f i l e B a s e O f ( ) -- Return base name of filename --
318
# ^^^^^^^^^^^^^^^^^^^^^^^
320
def fileBaseOf(filename, withPath=0) :
321
"""fileBaseOf(filename,withPath) ---> string
323
Return base name of filename. The returned string never includes the
325
Use os.path.basename() to return the basename with the extension. The
326
second argument is optional. If specified and if set to 'true' (non zero)
327
the string returned contains the full path of the file name. Otherwise the
331
>>> fn = 'd:/dev/telepath/tvapp/code/test.html'
337
'd:/dev/telepath/tvapp/code/test'
351
pos = filename.rfind('.')
353
filename = filename[:pos]
357
return os.path.basename(filename)
358
# -----------------------------------------------------------------------------
359
# m k d i r ( ) -- Create a directory (and possibly the entire tree) --
362
def mkdir(directory) :
363
"""Create a directory (and possibly the entire tree).
365
The os.mkdir() will fail to create a directory if one of the
366
directory in the specified path does not exist. mkdir()
367
solves this problem. It creates every intermediate directory
368
required to create the final path. Under Unix, the function
369
only supports forward slash separator, but under Windows and MacOS
370
the function supports the forward slash and the OS separator (backslash
373
# translate the path separators
374
directory = unixpath(directory)
376
# build a list of all directory elements
377
elem_list = filter(lambda x: len(x) > 0, directory.split('/'))
378
the_len = len(elem_list)
380
# if the first element is a Windows-style disk drive
381
# concatenate it with the first directory
382
if elem_list[0].endswith(':'):
384
elem_list[1] = elem_list[0] + '/' + elem_list[1]
388
# if the original directory starts at root,
389
# make sure the first element of the list
391
if directory[0] == '/':
392
elem_list[0] = '/' + elem_list[0]
394
# Now iterate through the list, check if the
395
# directory exists and if not create it
397
for i in range(the_len):
398
the_dir += elem_list[i]
399
if not os.path.exists(the_dir):
403
# -----------------------------------------------------------------------------
404
# u n i x p a t h ( ) -- Return a path name that contains Unix separator. --
405
# ^^^^^^^^^^^^^^^^^^^
408
r"""Return a path name that contains Unix separator.
411
>>> unixpath(r"d:\test")
413
>>> unixpath("d:/test/file.txt")
417
path = os.path.normpath(path)
421
return path.replace(os.sep, '/')
423
# -----------------------------------------------------------------------------
424
# S c r i p t e x e c u t i o n -- Runs when invoked from the command line --
425
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
427
if __name__ == "__main__":
428
import getopt # command line parsing
431
printUsage('Missing argument: specify at least one of -m or -p '
434
# If there is some arguments, parse the command line
436
valid_lopts = ['domain=', 'moTarget=']
438
option['forceEnglish'] = 0
441
option['verbose'] = 0
442
option['domain'] = None
443
option['moTarget'] = None
445
optionList, pargs = getopt.getopt(sys.argv[1:], valid_opts, valid_lopts)
446
except getopt.GetoptError, e:
449
for (opt, val) in optionList:
454
option['forceEnglish'] = 1
460
option['verbose'] = 1
461
elif (opt == '--domain'):
462
option['domain'] = val
463
elif (opt == '--moTarget'):
464
option['moTarget'] = val
466
app_dir_path = os.getcwd()
467
if option['verbose']:
468
print "No project directory given. Using current one: %s" % \
470
elif len(pargs) == 1:
471
app_dir_path = pargs[0]
473
printUsage(('Too many arguments (%u). Use double quotes if you have '
474
'space in directory name') % len(pargs))
476
if option['domain'] is None:
477
# If no domain specified, use the name of the target directory
478
option['domain'] = fileBaseOf(app_dir_path)
479
if option['verbose']:
480
print "Application domain used is: '%s'" % option['domain']
483
makePO(app_dir_path, option['domain'], option['verbose'])
485
printUsage(e[1] + ('\n You must write a file app.fil that '
486
'containsthe list of all files to parse.'))
488
makeMO(app_dir_path, option['moTarget'], option['domain'],
489
option['verbose'], option['forceEnglish'])
492
# -----------------------------------------------------------------------------