source: virtaal/trunk/fuentes/setup.py @ 4787

Last change on this file since 4787 was 250, checked in by mabarracus, 4 years ago

Ported trusty code

  • Property svn:executable set to *
File size: 26.2 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2008-2009 Zuza Software Foundation
5#
6# This file is part of Virtaal.
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, see <http://www.gnu.org/licenses/>.
20
21from distutils.core import setup, Distribution, Command
22from virtaal.__version__ import ver as virtaal_version
23from glob import glob
24import os
25import os.path as path
26import sys
27
28try:
29    import py2exe
30    build_exe = py2exe.build_exe.py2exe
31    Distribution = py2exe.Distribution
32except ImportError:
33    py2exe = None
34    build_exe = Command
35
36try:
37    import py2app
38except ImportError:
39    py2app = None
40
41PRETTY_NAME = "Virtaal"
42SOURCE_DATA_DIR = 'share'
43TARGET_DATA_DIR = 'share'
44
45virtaal_description="A tool to create program translations."
46
47classifiers = [
48    "Development Status :: 5 - Production/Stable",
49    "Environment :: Console",
50    "Intended Audience :: Developers",
51    "Intended Audience :: End Users/Desktop",
52    "Intended Audience :: Information Technology",
53    "License :: OSI Approved :: GNU General Public License (GPL)",
54    "Programming Language :: Python",
55    "Topic :: Software Development :: Localization",
56    "Topic :: Text Processing :: Linguistic"
57    "Operating System :: OS Independent",
58    "Operating System :: Microsoft :: Windows",
59    "Operating System :: Unix"
60]
61#TODO: add Natural Language classifiers
62
63# Compile .mo files from available .po files
64from translate.tools.pocompile import convertmo
65mo_files = []
66
67for lang in open(path.join('po', 'LINGUAS')):
68    lang = lang.rstrip()
69    po_filename = path.join('po', lang+'.po')
70    mo_filename = path.join('mo', lang, 'virtaal.mo')
71
72    if not path.exists(path.join('mo', lang)):
73        os.makedirs(path.join('mo', lang))
74
75    convertmo(open(po_filename), open(mo_filename, 'w'), None)
76
77    mo_files.append(
78        ( path.join(TARGET_DATA_DIR, 'locale', lang, 'LC_MESSAGES'), [mo_filename])
79    )
80
81# Build lite files as needed on Win32 and OS X
82if os.name == 'nt' or sys.platform == 'darwin':
83    for lang in open(path.join('po', 'LINGUAS-lite')):
84        app, lang = lang.rstrip().split('/')
85        po_filename = path.join('po', 'lite', app, lang+'.po')
86        mo_filename = path.join('mo', lang, app+'.mo')
87   
88        if not path.exists(path.join('mo', lang)):
89            os.makedirs(path.join('mo', lang))
90   
91        convertmo(open(po_filename), open(mo_filename, 'w'), None)
92   
93        mo_files.append(
94            ( path.join(TARGET_DATA_DIR, 'locale', lang, 'LC_MESSAGES'), [mo_filename])
95        )
96
97# Some of these depend on some files to be built externally before running
98# setup.py, like the .xml and .desktop files
99options = {
100    'data_files': [
101        (path.join(TARGET_DATA_DIR, "virtaal"), glob(path.join(SOURCE_DATA_DIR, "virtaal", "*.*"))),
102        (path.join(TARGET_DATA_DIR, "icons"), glob(path.join(SOURCE_DATA_DIR, "icons", "*.*"))),
103    ] + mo_files,
104    'scripts': [
105        "bin/virtaal",
106    ],
107    'packages': [
108        "virtaal",
109        "virtaal.common",
110        "virtaal.controllers",
111        "virtaal.models",
112        "virtaal.modes",
113        "virtaal.plugins",
114        "virtaal.plugins.lookup",
115        "virtaal.plugins.lookup.models",
116        "virtaal.plugins.terminology",
117        "virtaal.plugins.terminology.models",
118        "virtaal.plugins.terminology.models.localfile",
119        "virtaal.plugins.tm",
120        "virtaal.plugins.tm.models",
121        "virtaal.support",
122        "virtaal.support.libi18n",
123        "virtaal.views",
124        "virtaal.views.widgets"
125    ],
126}
127
128# For innosetup and py2app, we need to treat the plug-ins as data files.
129if os.name == 'nt' or sys.platform == 'darwin':
130    noplugins = []
131    for pkg in options['packages']:
132        if 'plugins' not in pkg:
133            noplugins.append(pkg)
134    options['packages'] = noplugins
135
136    plugin_src = path.join('virtaal', 'plugins')
137    plugin_dest = 'virtaal_plugins'
138    options['data_files'] += [
139        (plugin_dest, glob(path.join(plugin_src, '*.py'))),
140        (path.join(plugin_dest, 'lookup'), glob(path.join(plugin_src, 'lookup', '*.py'))),
141        (path.join(plugin_dest, 'lookup', 'models'), glob(path.join(plugin_src, 'lookup', 'models', '*.py'))),
142        (path.join(plugin_dest, 'terminology'), glob(path.join(plugin_src, 'terminology', '*.py'))),
143        (path.join(plugin_dest, 'terminology', 'models'), glob(path.join(plugin_src, 'terminology', 'models', '*.py'))),
144        (path.join(plugin_dest, 'terminology', 'models', 'localfile'), glob(path.join(plugin_src, 'terminology', 'models', 'localfile', '*.py'))),
145        (path.join(plugin_dest, 'tm'), glob(path.join(plugin_src, 'tm', '*.py'))),
146        (path.join(plugin_dest, 'tm', 'models'), glob(path.join(plugin_src, 'tm', 'models', '*.py'))),
147    ]
148
149no_install_files = [
150    ['LICENSE', 'maketranslations', path.join('devsupport', 'virtaal_innosetup.bmp')]
151]
152
153no_install_dirs = ['po', 'share/virtaal/autocorr']
154
155#############################
156# WIN 32 specifics
157
158def get_compile_command():
159    try:
160        import _winreg
161        compile_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, "innosetupscriptfile\\shell\\compile\\command")
162        compilecommand = _winreg.QueryValue(compile_key, "")
163        compile_key.Close()
164
165    except:
166        compilecommand = "compil32.exe"
167    return compilecommand
168
169def chop(dist_dir, pathname):
170    """returns the path relative to dist_dir"""
171    assert pathname.startswith(dist_dir)
172    return pathname[len(dist_dir):]
173
174def create_inno_script(name, _lib_dir, dist_dir, exe_files, other_files, version = "1.0"):
175    if not dist_dir.endswith(os.sep):
176        dist_dir += os.sep
177    exe_files = [chop(dist_dir, p) for p in exe_files]
178    other_files = [chop(dist_dir, p) for p in other_files]
179    pathname = path.join(dist_dir, name + os.extsep + "iss")
180
181# See http://www.jrsoftware.org/isfaq.php for more InnoSetup config options.
182    ofi = open(pathname, "w")
183    print >> ofi, r'''; WARNING: This script has been created by py2exe. Changes to this script
184; will be overwritten the next time py2exe is run!
185
186[Languages]
187Name: "en"; MessagesFile: "compiler:Default.isl"
188Name: "eu"; MessagesFile: "compiler:Languages\Basque.isl"
189Name: "ca"; MessagesFile: "compiler:Languages\Catalan.isl"
190Name: "cz"; MessagesFile: "compiler:Languages\Czech.isl"
191Name: "da"; MessagesFile: "compiler:Languages\Danish.isl"
192Name: "nl"; MessagesFile: "compiler:Languages\Dutch.isl"
193Name: "fi"; MessagesFile: "compiler:Languages\Finnish.isl"
194Name: "fr"; MessagesFile: "compiler:Languages\French.isl"
195Name: "de"; MessagesFile: "compiler:Languages\German.isl"
196Name: "he"; MessagesFile: "compiler:Languages\Hebrew.isl"
197Name: "hu"; MessagesFile: "compiler:Languages\Hungarian.isl"
198Name: "it"; MessagesFile: "compiler:Languages\Italian.isl"
199Name: "nb"; MessagesFile: "compiler:Languages\Norwegian.isl"
200Name: "pl"; MessagesFile: "compiler:Languages\Polish.isl"
201Name: "pt_BR"; MessagesFile: "compiler:Languages\BrazilianPortuguese.isl"
202Name: "pt"; MessagesFile: "compiler:Languages\Portuguese.isl"
203Name: "ru"; MessagesFile: "compiler:Languages\Russian.isl"
204Name: "sk"; MessagesFile: "compiler:Languages\Slovak.isl"
205Name: "sl"; MessagesFile: "compiler:Languages\Slovenian.isl"
206Name: "es"; MessagesFile: "compiler:Languages\Spanish.isl"
207
208[Setup]
209AppName=%(name)s
210AppVerName=%(name)s %(version)s
211AppPublisher=Zuza Software Foundation
212AppPublisherURL=http://www.translate.org.za/
213AppVersion=%(version)s
214AppSupportURL=http://translate.sourceforge.net/
215;AppComments=
216;AppCopyright=Copyright (C) 2007-2009 Zuza Software Foundation
217DefaultDirName={pf}\%(name)s
218DefaultGroupName=%(name)s
219LanguageDetectionMethod=locale
220OutputBaseFilename=%(name)s-%(version)s-setup
221ChangesAssociations=yes
222SetupIconFile=%(icon_path)s
223;WizardSmallImageFile=compiler:images\WizModernSmallImage13.bmp
224WizardImageFile=%(wizard_image)s
225
226[Files]''' % {
227    'name': name,
228    'version': version,
229    'icon_path': path.join(TARGET_DATA_DIR, "icons", "virtaal.ico"),
230    'wizard_image': path.join(os.pardir, "devsupport", "virtaal_innosetup.bmp")
231}
232    for fpath in exe_files + other_files:
233        print >> ofi, r'Source: "%s"; DestDir: "{app}\%s"; Flags: ignoreversion' % (fpath, os.path.dirname(fpath))
234    print >> ofi, r'''
235[Icons]
236Name: "{group}\%(name)s Translation Editor"; Filename: "{app}\virtaal.exe";
237Name: "{group}\%(name)s (uninstall)"; Filename: "{uninstallexe}"''' % {'name': name}
238
239#    For now we don't worry about install scripts
240#    if install_scripts:
241#        print >> ofi, r"[Run]"
242#
243#        for fpath in install_scripts:
244#            print >> ofi, r'Filename: "{app}\%s"; WorkingDir: "{app}"; Parameters: "-install"' % fpath
245#
246#        print >> ofi
247#        print >> ofi, r"[UninstallRun]"
248#
249#        for fpath in install_scripts:
250#            print >> ofi, r'Filename: "{app}\%s"; WorkingDir: "{app}"; Parameters: "-remove"' % fpath
251
252    # File associations. Note the directive "ChangesAssociations=yes" above
253    # that causes the installer to tell Explorer to refresh associations.
254    # This part might cause the created installer to need administrative
255    # privileges. An alternative might be to rather write to
256    # HKCU\Software\Classes, but this won't be system usable then. Didn't
257    # see a way to test and alter the behaviour.
258
259    # For each file type we should have something like this:
260    #
261    #;File extension:
262    #Root: HKCR; Subkey: ".po"; ValueType: string; ValueName: ""; ValueData: "virtaal_po"; Flags: uninsdeletevalue
263    #;Description of the file type
264    #Root: HKCR; Subkey: "virtaal_po"; ValueType: string; ValueName: ""; ValueData: "Gettext PO"; Flags: uninsdeletekey
265    #;Icon to use in Explorer
266    #Root: HKCR; Subkey: "virtaal_po\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\share\icons\virtaal.ico"
267    #;The command to open the file
268    #Root: HKCR; Subkey: "virtaal_po\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\virtaal.exe"" ""%1"""
269
270    print >> ofi, "[Registry]"
271    from translate.storage import factory
272    for description, extentions, _mimetypes in factory.supported_files():
273        # We skip those types where we depend on mime types, not extentions
274        if not extentions:
275            continue
276        # Form a key from the first extention for internal only
277        key = extentions[0]
278        # Associate each extention with the file type
279        for extention in extentions:
280            # We don't want to associate with all .txt or .pot (PowerPoint template) files, so let's skip it
281            if extention in ["txt", "pot", "csv"]:
282                continue
283            print >> ofi, r'Root: HKCR; Subkey: ".%(extention)s"; ValueType: string; ValueName: ""; ValueData: "virtaal_%(key)s"; Flags: uninsdeletevalue' % {'extention': extention, 'key': key}
284        print >> ofi, r'''Root: HKCR; Subkey: "virtaal_%(key)s"; ValueType: string; ValueName: ""; ValueData: "%(description)s"; Flags: uninsdeletekey
285Root: HKCR; Subkey: "virtaal_%(key)s\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\share\icons\x-translation.ico"
286Root: HKCR; Subkey: "virtaal_%(key)s\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\virtaal.exe"" ""%%1"""''' % {'key': key, 'description': description}
287
288    # Show a "Launch Virtaal" checkbox on the last installer screen
289    print >> ofi, r'''
290[Run]
291Filename: "{app}\virtaal.exe"; Description: "{cm:LaunchProgram,%(name)s}"; Flags: nowait postinstall skipifsilent''' % {'name': name}
292    print >> ofi
293    ofi.close()
294    return pathname
295
296def compile_inno_script(script_path):
297    """compiles the script using InnoSetup"""
298    shell_compile_command = get_compile_command()
299    compile_command = shell_compile_command.replace('"%1"', script_path)
300    result = os.system(compile_command)
301    if result:
302        print "Error compiling iss file"
303        print "Opening iss file, use InnoSetup GUI to compile manually"
304        os.startfile(script_path)
305
306class BuildWin32Installer(build_exe):
307    """distutils class that first builds the exe file(s), then creates a Windows installer using InnoSetup"""
308    description = "create an executable installer for MS Windows using InnoSetup and py2exe"
309    user_options = getattr(build_exe, 'user_options', []) + \
310        [('install-script=', None,
311          "basename of installation script to be run after installation or before deinstallation")]
312
313    def initialize_options(self):
314        build_exe.initialize_options(self)
315
316    def run(self):
317        # First, let py2exe do it's work.
318        build_exe.run(self)
319        # create the Installer, using the files py2exe has created.
320        exe_files = self.windows_exe_files + self.console_exe_files
321        print "*** creating the inno setup script***"
322        script_path = create_inno_script(PRETTY_NAME, self.lib_dir, self.dist_dir, exe_files, self.lib_files,
323                                         version=self.distribution.metadata.version)
324        print "*** compiling the inno setup script***"
325        compile_inno_script(script_path)
326        # Note: By default the final setup.exe will be in an Output subdirectory.
327
328def find_gtk_bin_directory():
329    GTK_NAME = "libgtk"
330    # Look for GTK in the user's Path as well as in some familiar locations
331    paths = os.environ['Path'].split(';') + [r'C:\GTK\bin', r'C:\Program Files\GTK\bin' r'C:\Program Files\GTK2-Runtime']
332    for p in paths:
333        if not os.path.exists(p):
334            continue
335        files = [path.join(p, f) for f in os.listdir(p) if path.isfile(path.join(p, f)) and f.startswith(GTK_NAME)]
336        if len(files) > 0:
337            return p
338    raise Exception("""Could not find the GTK runtime.
339Please place bin directory of your GTK installation in the program path.""")
340
341def find_gtk_files():
342    def parent(dir_path):
343        return path.abspath(path.join(path.abspath(dir_path), '..'))
344
345    def strip_leading_path(leadingPath, p):
346        return p[len(leadingPath) + 1:]
347
348    def wanted(data_file):
349        """We don't want all the GTK files for the installer. Let's strip out a
350        few ones that are taking too much space."""
351        name = os.path.basename(data_file)
352        if name in no_package_names_dict:
353            return False
354        _base, ext = os.path.splitext(name)
355        if ext in no_package_extensions_dict:
356            return False
357        return True
358
359    #file names that we don't want
360    no_package_names = [
361            #We want some .mo files, but we won't use these ones
362            'libiconv.mo',
363            'iso_15924.mo',
364            'iso_3166_2.mo',
365            'iso_4217.mo',
366            'iso_639_3.mo',
367            'gtk20-properties.mo',
368            'gtkspell.mo', # This isn't picked up, so our code does the i18n
369            'gettext-tools.mo',
370            'gettext-runtime.mo',
371            'gtkspell.mo',
372    ]
373    #extensions of files we don't want
374    no_package_extensions = [
375            '.log',
376            '.m4',
377            #package config
378            '.pc',
379            #man pages
380            '.1',
381            '.3',
382            '.5',
383            #source code
384            '.h',
385            '.c',
386            '.tcl',
387            #library files
388            '.a',
389            '.def',
390            '.lib',
391            #emacs files
392            '.el',
393            '.elc',
394    ]
395
396    #Let's make some dictionaries so that we are not too slow
397    no_package_names_dict = {}
398    no_package_extensions_dict = {}
399    for name in no_package_names:
400        no_package_names_dict[name] = None
401    for extension in no_package_extensions:
402        no_package_extensions_dict[extension] = None
403
404
405    data_files = []
406    gtk_path = parent(find_gtk_bin_directory())
407    for dir_path in [path.join(gtk_path, p) for p in ('etc', 'share', 'lib')]:
408        for dir_name, _, files in os.walk(dir_path):
409            files = [path.abspath(path.join(dir_name, f)) for f in files if wanted(f)]
410            if len(files) > 0:
411                data_files.append((strip_leading_path(gtk_path, dir_name), files))
412    return data_files
413
414def find_enchant_files():
415    data_files = []
416    import enchant
417    en = enchant.Dict('en')
418    # This should give us something like
419    # C:\Python25\Lib\site-packages\enchant\lib\enchant\libenchant_myspell.dll
420    data_files.append(('lib/enchant', [en.provider.file]))
421    # Our version of gtkspell expects libenchant.dll, but enchant itselfs needs
422    # libenchant-1.dll
423    libenchant = enchant.utils.get_resource_filename("libenchant.dll")
424    libenchant1 = enchant.utils.get_resource_filename("libenchant-1.dll")
425    data_files.append(('',[libenchant, libenchant1]))
426    return data_files
427
428def find_langmodel_files():
429    from translate.misc.file_discovery import get_abs_data_filename
430    lmdir = path.abspath(get_abs_data_filename('langmodels'))
431    if not path.isdir(lmdir):
432        return []
433
434    return [(path.join(TARGET_DATA_DIR, 'langmodels'), glob(path.join(lmdir, '*.*')))]
435
436def add_win32_options(options):
437    """This function is responsible for finding data files and setting options necessary
438    to build executables and installers under Windows.
439
440    @return: A 2-tuple (data_files, options), where data_files is a list of Windows
441             specific data files (this would include the GTK binaries) and where
442             options are the options required by py2exe."""
443    if py2exe != None and ('py2exe' in sys.argv or 'innosetup' in sys.argv):
444        options['data_files'].extend(find_gtk_files())
445        options['data_files'].extend(find_enchant_files())
446        options['data_files'].extend(find_langmodel_files())
447        options['data_files'].extend([(
448            path.join(TARGET_DATA_DIR, "icons", "hicolor", "24x24", "mimetypes"),
449            [path.join(SOURCE_DATA_DIR, "icons", "hicolor", "24x24", "mimetypes", "x-translation.png")]
450        )])
451        #This depends on setup.py being run from a checkout with the translate
452        #toolkit in place.
453        options['scripts'].append("../translate/services/tmserver")
454
455        py2exe_options = {
456            # translate.lang and translate.storage contain classes that are
457            # imported dynamically, therefore we need to add them here,
458            # otherwise py2exe doesn't find them.
459            "packages":   ["encodings", "translate.lang", "translate.storage._factory_classes", "virtaal"],
460            "compressed": True,
461            "excludes":   ["PyLucene", "Tkconstants", "Tkinter", "tcl",
462                # strange things unnecessarily included with some versions of pyenchant:
463                "win32ui", "_win32sysloader", "win32pipe", "py2exe", "pywin", "isapi", "_tkinter", "win32api",
464            ],
465            "dist_dir":   "virtaal-win32",
466            "includes":   [
467                    # some of these are needed by plugins and are therefore not detected
468                    "lxml", "lxml._elementpath", "psyco", "cairo", "pango",
469                    "pangocairo", "atk", "gobject", "gtk.keysyms",
470                    "gtkspell",
471                    "tarfile",
472                    "translate.storage.placeables.terminology", # terminology
473                    "xmlrpclib", # Moses
474                ],
475            "optimize":   2,
476        }
477        py2exe_options['includes'] += ["bsddb", "zipfile"] # Dependencies for the migration and auto-correction plug-ins, respectively.
478        innosetup_options = py2exe_options.copy()
479        options.update({
480            "windows": [
481                {
482                    'script': 'bin/virtaal',
483                    'icon_resources': [(1, path.join(SOURCE_DATA_DIR, "icons", "virtaal.ico"))],
484                },
485                { 'script': "../translate/services/tmserver"}
486            ],
487            'zipfile':  "virtaal.zip",
488            "options": {
489                "py2exe":    py2exe_options,
490                "innosetup": innosetup_options
491            },
492            'cmdclass':  {
493                "py2exe":    build_exe,
494                "innosetup": BuildWin32Installer
495            }
496        })
497    return options
498
499def add_mac_options(options):
500    # http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html#tweaking-your-info-plist
501    # http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/PListKeys.html
502    if py2app is None:
503        return options
504    options['data_files'].extend([('share/OSX_Leopard_theme', glob(path.join('devsupport', 'OSX_Leopard_theme', '*')))])
505    options['data_files'].extend([('', ['devsupport/virtaal.icns'])])
506
507    # For some reason py2app can't handle bin/virtaal since it doesn't end in .py
508    import shutil
509    shutil.copy2('bin/virtaal', 'bin/run_virtaal.py')
510
511    from translate.storage import factory
512    options.update({
513        "app": ["bin/run_virtaal.py"],
514        "options": {
515            "py2app": {
516            "packages": ["CoreFoundation", "objc"],
517            "includes":   ["lxml", "lxml._elementpath", "lxml.etree", "glib", "gio", "psyco", "cairo", "pango", "pangocairo", "atk", "gobject", "gtk.keysyms", "pycurl", "translate.services", "translate.services.tmclient", "translate.services.opentranclient", "CoreFoundation"],
518                #"semi_standalone": True,
519                "compressed": True,
520                "argv_emulation": True,
521                "plist":  {
522                    "CFBundleGetInfoString": virtaal_description,
523                    "CFBundleName": PRETTY_NAME,
524                    "CFBundleIconFile": "virtaal.icns",
525                    "CFBundleShortVersionString": virtaal_version,
526                    #"LSHasLocalizedDisplayName": "1",
527                    #"LSMinimumSystemVersion": ???,
528                    "NSHumanReadableCopyright": "Copyright (C) 2007-2009 Zuza Software Foundation",
529                    "CFBundleDocumentTypes": [{
530                        "CFBundleTypeExtensions": [extention.lstrip("*.") for extention in extentions],
531                        "CFBundleTypeIconFile": "virtaal.icns",
532                        "CFBundleTypeMIMETypes": mimetypes,
533                        "CFBundleTypeName": description, #????
534                        } for description, extentions, mimetypes in factory.supported_files()]
535                    }
536                }
537            }})
538    return options
539
540def add_freedesktop_options(options):
541    options['data_files'].extend([
542        (path.join(TARGET_DATA_DIR, "mime", "packages"), glob(path.join(SOURCE_DATA_DIR, "mime", "packages", "*.xml"))),
543        (path.join(TARGET_DATA_DIR, "applications"), glob(path.join(SOURCE_DATA_DIR, "applications", "*.desktop"))),
544    ])
545    for dir in ("16x16", "24x24", "32x32", "48x48", "64x64", "128x128", "scalable"):
546        options['data_files'].extend([
547            (path.join(TARGET_DATA_DIR, "icons", "hicolor", dir, "mimetypes"),
548            glob(path.join(SOURCE_DATA_DIR, "icons", "hicolor", dir, "mimetypes", "*.*"))),
549        ])
550    return options
551
552#############################
553# General functions
554
555def add_platform_specific_options(options):
556    if sys.platform == 'win32':
557        return add_win32_options(options)
558    if sys.platform == 'darwin':
559        return add_mac_options(options)
560    return add_freedesktop_options(options)
561
562def create_manifest(data_files, extra_files, extra_dirs):
563    f = open('MANIFEST.in', 'w+')
564    f.write("# informational files")
565    for infofile in ("README", "TODO", "ChangeLog", "COPYING", "LICENSE", "*.txt"):
566        f.write("global-include %s\n" % infofile)
567    for data_file_list in [d[1] for d in data_files] + extra_files:
568        if not data_file_list:
569            continue
570        f.write("include %s\n" % (" ".join( data_file_list )))
571    for dir in extra_dirs:
572        f.write("graft %s\n" % (dir))
573    f.close()
574
575import distutils.command.install
576class DepCheckInstall(distutils.command.install.install):
577    user_options = distutils.command.install.install.user_options + [
578        ('nodepcheck', None, "don't check dependencies"),
579    ]
580
581    def initialize_options(self):
582        distutils.command.install.install.initialize_options(self)
583        self.nodepcheck = False
584
585    def run(self, *args, **kwargs):
586        if not self.nodepcheck:
587            from virtaal.support import depcheck
588            failed = depcheck.check_dependencies()
589            if failed:
590                print 'Failed dependencies: %s' % (', '.join(failed))
591                print 'Use the --nodepcheck option to ignore dependencies.'
592                exit(1)
593        distutils.command.install.install.run(self, *args, **kwargs)
594
595def main(options):
596    options = add_platform_specific_options(options)
597    if not 'cmdclass' in options:
598        options['cmdclass'] = {}
599    options['cmdclass']['install'] = DepCheckInstall
600    create_manifest(options['data_files'], no_install_files, no_install_dirs)
601    setup(name="virtaal",
602          version=virtaal_version,
603          license="GNU General Public License (GPL)",
604          description=virtaal_description,
605          long_description="""Virtaal is used to create program translations.
606
607It uses the Translate Toolkit to get access to translation files and therefore
608can edit a variety of files (including PO and XLIFF files).""",
609          author="Translate.org.za",
610          author_email="translate-devel@lists.sourceforge.net",
611          url="http://translate.sourceforge.net/wiki/virtaal/index",
612          download_url="http://sourceforge.net/project/showfiles.php?group_id=91920&package_id=270877",
613          platforms=["any"],
614          classifiers=classifiers,
615          **options)
616
617if __name__ == '__main__':
618    main(options)
619    # For some reason, Resources/lib/python2.5/lib-dynload is not in the Python
620    # path. We need to get it in, therefore this hack.
621    if sys.platform == 'darwin':
622        f = open('dist/virtaal.app/Contents/Resources/__boot__.py', "r+")
623        s = f.read()
624        f.truncate(0)
625        s = s.replace("base = os.environ['RESOURCEPATH']", r"""
626    base = os.environ['RESOURCEPATH']
627    sys.path = [os.path.join(base, "lib", "python2.5", "lib-dynload")] + sys.path
628    sys.path = [os.path.join(base, "lib", "python2.5")] + sys.path
629""")
630        f.seek(0)
631        f.write(s)
632        f.close()
633        # hdiutil create -imagekey zlib-level=9 -srcfolder dist/virtaal.app dist/virtaal.dmg
634        # hdiutil create -fs HFS+ -volname "RUR-PLE" -srcfolder dist dist_mac/RUR-PLE.dmg
Note: See TracBrowser for help on using the repository browser.