~brian-sidebotham/wxwidgets-cmake/wxpython-2.9.4

« back to all changes in this revision

Viewing changes to wxPython/wx/tools/Editra/scripts/i18n/mki18n.py

  • Committer: Brian Sidebotham
  • Date: 2013-08-03 14:30:08 UTC
  • Revision ID: brian.sidebotham@gmail.com-20130803143008-c7806tkych1tp6fc
Initial import into Bazaar

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# -*- coding: iso-8859-1 -*-
 
3
#   
 
4
#   PYTHON MODULE:     MKI18N.PY
 
5
#                      =========
 
6
 
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
 
11
 
12
#   Update history:
 
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 
 
24
#                                    .mo file.
 
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
 
30
 
31
#   RCS $Log: $
 
32
 
33
 
34
# -----------------------------------------------------------------------------
 
35
"""                                
 
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
 
38
(Machine Object).
 
39
 
 
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).
 
42
 
 
43
    Table of Contents
 
44
    -----------------
 
45
    makePO()  -- Build the Portable Object file for the application --
 
46
    catPO()   -- Concatenate one or several PO files with the application 
 
47
                 domain files.
 
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 --
 
52
 
 
53
NOTE:  this module uses GNU gettext utilities.
 
54
 
 
55
You can get the gettext tools from the following sites:
 
56
 
 
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 
 
60
     `GNU
 
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
 
64
     the following files: 
 
65
 
 
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`_ 
 
69
 
 
70
 
 
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
 
79
 
 
80
"""
 
81
# -----------------------------------------------------------------------------
 
82
# Module Import
 
83
# -------------
 
84
 
85
import os
 
86
import sys
 
87
import wx
 
88
# -----------------------------------------------------------------------------
 
89
# Global variables
 
90
# ----------------
 
91
#
 
92
 
 
93
__author__ = "Pierre Rouleau"
 
94
__version__ = "$Revision: 70029 $"
 
95
 
 
96
# -----------------------------------------------------------------------------
 
97
 
 
98
def getlanguageDict():
 
99
    """Get a dictionary of the available languages from wx"""
 
100
    lang_dict = {}
 
101
    app = wx.App()
 
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))
 
104
        if i:
 
105
            lang_dict[i.CanonicalName] = i.Description
 
106
    return lang_dict
 
107
 
 
108
# -----------------------------------------------------------------------------
 
109
# m a k e P O ( )  -- Build the Portable Object file for the application --
 
110
# ^^^^^^^^^^^^^^^
 
111
#
 
112
def makePO(app_dir,  app_domain=None, verbose=0) :
 
113
    """Build the Portable Object Template file for the application.
 
114
 
 
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 
 
118
    'app.fil'. 
 
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.
 
123
 
 
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.
 
132
 
 
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.
 
135
    """
 
136
 
 
137
    if app_domain is None:
 
138
        app_name = fileBaseOf(app_dir, withPath=0)
 
139
    else:
 
140
        app_name = app_domain
 
141
    curr_dir = os.getcwd()
 
142
    os.chdir(app_dir)                    
 
143
    if not os.path.exists('app.fil'):
 
144
        raise IOError(2,'No module file: app.fil')
 
145
 
 
146
    # Steps:                                  
 
147
    #  Use xgettext to parse all application modules
 
148
    #  The following switches are used:
 
149
    #  
 
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'
 
156
    if verbose: 
 
157
        print cmd
 
158
    os.system(cmd)                                                
 
159
 
 
160
    lang_dict = getlanguageDict()
 
161
    for lang_code in lang_dict.keys():
 
162
        if lang_code == 'en':
 
163
            pass
 
164
        else:
 
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)
 
169
                if verbose: 
 
170
                    print cmd
 
171
                os.system(cmd)
 
172
    os.chdir(curr_dir)
 
173
 
 
174
# -----------------------------------------------------------------------------
 
175
# c a t P O ( ) 
 
176
# -- Concatenate one or several PO files with the application domain files. --
 
177
# ^^^^^^^^^^^^^
 
178
#
 
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.
 
182
    """
 
183
 
 
184
    if app_domain is None:
 
185
        app_name = fileBaseOf(app_dir, withPath=0)
 
186
    else:
 
187
        app_name = app_domain
 
188
    curr_dir = os.getcwd()
 
189
    os.chdir(app_dir)
 
190
 
 
191
    lang_dict = getlanguageDict()
 
192
 
 
193
    for lang_code in lang_dict.keys():
 
194
        if lang_code == 'en':
 
195
            pass
 
196
        else:
 
197
            lang_po_fname = "%s_%s.po" % (app_name, lang_code)
 
198
            if os.path.exists(lang_po_fname):
 
199
                fileList = ''
 
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, \
 
203
                                                              fileList, \
 
204
                                                              lang_po_fname)
 
205
                if verbose: 
 
206
                    print cmd
 
207
                os.system(cmd)
 
208
                if target_dir is None:
 
209
                    pass
 
210
                else:
 
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)
 
214
                    if verbose: 
 
215
                        print cmd
 
216
                    os.system(cmd)
 
217
    os.chdir(curr_dir)
 
218
 
 
219
# -----------------------------------------------------------------------------
 
220
# m a k e M O ( ) Compile the POfiles into the MO stored in the right location.
 
221
# ^^^^^^^^^^^^^^^
 
222
 
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 
 
226
    right location.
 
227
 
 
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.
 
231
 
 
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.
 
237
 
 
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
 
240
    code.
 
241
    """
 
242
    if targetDir is None:
 
243
        targetDir = './locale'
 
244
    if verbose:
 
245
        print "Target directory for .mo files is: %s" % targetDir
 
246
 
 
247
    if applicationDomain is None:
 
248
        applicationName = fileBaseOf(applicationDirectoryPath, withPath=0)
 
249
    else:
 
250
        applicationName = applicationDomain
 
251
    currentDir = os.getcwd()
 
252
    os.chdir(applicationDirectoryPath)
 
253
 
 
254
    languageDict = getlanguageDict()
 
255
 
 
256
    for langCode in languageDict.keys():
 
257
        if (langCode == 'en') and (forceEnglish==0):
 
258
            pass
 
259
        else:
 
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):
 
264
                    mkdir(mo_targetDir)
 
265
                cmd = 'msgfmt --output-file="%s/%s.mo" "%s_%s.po"' % \
 
266
                      (mo_targetDir, applicationName, applicationName, langCode)
 
267
                if verbose: 
 
268
                    print cmd
 
269
                os.system(cmd)
 
270
    os.chdir(currentDir)
 
271
   
 
272
# -----------------------------------------------------------------------------
 
273
# printUsage -- Displays how to use this script from the command line --
 
274
# ^^^^^^^^^^^^^^^^^^^
 
275
#
 
276
def printUsage(errorMsg=None):
 
277
    """Displays how to use this script from the command line."""
 
278
    print """
 
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)  #
 
283
    #            files.                                                       #
 
284
    #            Supports C, C++, and Python source files.                    #
 
285
    #                                                                         #
 
286
    #   Usage: mki18n {OPTION} [appDirPath]                                   #
 
287
    #                                                                         #
 
288
    #   Options:                                                              #
 
289
    #     -e               : When -m is used, forces English .mo file         #
 
290
    #                        creation                                         #
 
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'         #
 
306
    #                                                                         #
 
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         #
 
310
    #   directory.                                                            #
 
311
    ###########################################################################
 
312
    """
 
313
    if errorMsg:
 
314
        print "\n   ERROR: %s" % errorMsg
 
315
 
 
316
# -----------------------------------------------------------------------------
 
317
# f i l e B a s e O f ( )         -- Return base name of filename --
 
318
# ^^^^^^^^^^^^^^^^^^^^^^^
 
319
 
320
def fileBaseOf(filename, withPath=0) :
 
321
    """fileBaseOf(filename,withPath) ---> string
 
322
 
 
323
    Return base name of filename. The returned string never includes the 
 
324
    extension.
 
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
 
328
    path is excluded.
 
329
 
 
330
    [Example]
 
331
    >>> fn = 'd:/dev/telepath/tvapp/code/test.html'
 
332
    >>> fileBaseOf(fn)
 
333
    'test'
 
334
    >>> fileBaseOf(fn)
 
335
    'test'
 
336
    >>> fileBaseOf(fn,1)
 
337
    'd:/dev/telepath/tvapp/code/test'
 
338
    >>> fileBaseOf(fn,0)
 
339
    'test'
 
340
    >>> fn = 'abcdef'
 
341
    >>> fileBaseOf(fn)
 
342
    'abcdef'
 
343
    >>> fileBaseOf(fn,1)
 
344
    'abcdef'
 
345
    >>> fn = "abcdef."
 
346
    >>> fileBaseOf(fn)
 
347
    'abcdef'
 
348
    >>> fileBaseOf(fn,1)
 
349
    'abcdef'
 
350
    """            
 
351
    pos = filename.rfind('.')             
 
352
    if pos > 0:
 
353
        filename = filename[:pos]
 
354
    if withPath:
 
355
        return filename
 
356
    else:
 
357
        return os.path.basename(filename)
 
358
# -----------------------------------------------------------------------------
 
359
# m k d i r ( )   -- Create a directory (and possibly the entire tree) --
 
360
# ^^^^^^^^^^^^^
 
361
 
362
def mkdir(directory) :
 
363
    """Create a directory (and possibly the entire tree).
 
364
 
 
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
 
371
    under windows).
 
372
    """ 
 
373
    # translate the path separators
 
374
    directory = unixpath(directory)
 
375
 
 
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)
 
379
 
 
380
    # if the first element is a Windows-style disk drive
 
381
    # concatenate it with the first directory
 
382
    if elem_list[0].endswith(':'):
 
383
        if the_len > 1:
 
384
            elem_list[1] = elem_list[0] + '/' + elem_list[1]
 
385
            del elem_list[0]      
 
386
            the_len -= 1     
 
387
 
 
388
    # if the original directory starts at root,
 
389
    # make sure the first element of the list 
 
390
    # starts at root too
 
391
    if directory[0] == '/':     
 
392
        elem_list[0] = '/' + elem_list[0]
 
393
 
 
394
    # Now iterate through the list, check if the 
 
395
    # directory exists and if not create it
 
396
    the_dir = ''
 
397
    for i in range(the_len):
 
398
        the_dir += elem_list[i]
 
399
        if not os.path.exists(the_dir):
 
400
            os.mkdir(the_dir)
 
401
        the_dir += '/'   
 
402
      
 
403
# -----------------------------------------------------------------------------
 
404
# u n i x p a t h ( ) -- Return a path name that contains Unix separator. --
 
405
# ^^^^^^^^^^^^^^^^^^^
 
406
 
407
def unixpath(path) :
 
408
    r"""Return a path name that contains Unix separator.
 
409
 
 
410
    [Example]
 
411
    >>> unixpath(r"d:\test")
 
412
    'd:/test'
 
413
    >>> unixpath("d:/test/file.txt")
 
414
    'd:/test/file.txt'
 
415
    >>> 
 
416
    """
 
417
    path = os.path.normpath(path)
 
418
    if os.sep == '/':
 
419
        return path
 
420
    else:
 
421
        return path.replace(os.sep, '/')
 
422
 
 
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
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
426
 
427
if __name__ == "__main__":
 
428
    import getopt     # command line parsing
 
429
    argc = len(sys.argv)
 
430
    if argc == 1:
 
431
        printUsage('Missing argument: specify at least one of -m or -p '
 
432
                   '(or both).')
 
433
        sys.exit(1)
 
434
    # If there is some arguments, parse the command line
 
435
    valid_opts = "ehmpv"
 
436
    valid_lopts = ['domain=', 'moTarget=']             
 
437
    option = {}
 
438
    option['forceEnglish'] = 0
 
439
    option['mo'] = 0
 
440
    option['po'] = 0        
 
441
    option['verbose'] = 0
 
442
    option['domain'] = None
 
443
    option['moTarget'] = None
 
444
    try:
 
445
        optionList, pargs = getopt.getopt(sys.argv[1:], valid_opts, valid_lopts)
 
446
    except getopt.GetoptError, e:
 
447
        printUsage(e[0])
 
448
        sys.exit(1)       
 
449
    for (opt, val) in optionList:
 
450
        if  (opt == '-h'):    
 
451
            printUsage()
 
452
            sys.exit(0) 
 
453
        elif (opt == '-e'):
 
454
            option['forceEnglish'] = 1
 
455
        elif (opt == '-m'):
 
456
            option['mo'] = 1
 
457
        elif (opt == '-p'):
 
458
            option['po'] = 1
 
459
        elif (opt == '-v'):
 
460
            option['verbose'] = 1
 
461
        elif (opt == '--domain'):
 
462
            option['domain'] = val
 
463
        elif (opt == '--moTarget'):
 
464
            option['moTarget'] = val
 
465
    if len(pargs) == 0:
 
466
        app_dir_path = os.getcwd()
 
467
        if option['verbose']:
 
468
            print "No project directory given. Using current one:  %s" % \
 
469
                                                                    app_dir_path
 
470
    elif len(pargs) == 1:
 
471
        app_dir_path = pargs[0]
 
472
    else:
 
473
        printUsage(('Too many arguments (%u). Use double quotes if you have '
 
474
                   'space in directory name') % len(pargs))
 
475
        sys.exit(1)
 
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']
 
481
    if option['po']:
 
482
        try:
 
483
            makePO(app_dir_path, option['domain'], option['verbose'])
 
484
        except IOError, e:
 
485
            printUsage(e[1] + ('\n   You must write a file app.fil that '
 
486
                              'containsthe list of all files to parse.'))
 
487
    if option['mo']:
 
488
        makeMO(app_dir_path, option['moTarget'], option['domain'], 
 
489
               option['verbose'], option['forceEnglish'])
 
490
    sys.exit(1)            
 
491
            
 
492
# -----------------------------------------------------------------------------