~shanepatrickfagan/ubuntu-sso-client/refactoring_mandel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python
# setup.py - Build system for Ubuntu SSO Client package
#
# Author: Natalia B. Bidart <natalia.bidart@canonical.com>
# Author: Manuel de la Pena <manuel@canonical.com>
#
# Copyright 2010 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
"""setup.py"""

import cgi
import os
import sys

try:
    import DistUtilsExtra.auto
    from DistUtilsExtra.command import build_extra
except ImportError:
    print >> sys.stderr, 'To build this program you need '\
                         'https://launchpad.net/python-distutils-extra'
    sys.exit(1)
assert DistUtilsExtra.auto.__version__ >= '2.18', \
       'needs DistUtilsExtra.auto >= 2.18'

from distutils import log
from distutils.command import clean
from distutils.spawn import find_executable

# Defining variables for various rules here, similar to a Makefile.am
LINUX_CLEANFILES = ['data/com.ubuntu.sso.service', 'po/ubuntu-sso-client.pot',
              'MANIFEST']


# pylint: disable=W0511
# This needs some serious cleanup
class SSOLinuxBuild(build_extra.build_extra):
    """Build  the extra files required on Linux.."""

    description = 'build extra files needed by ubuntu-sso-client'

    def run(self):
        """Do the build."""
        sed = find_executable('sed')
        if sed is None:
            sys.stderr.write('Cannont find sed; required to build')
            sys.exit(-1)

        in_file = 'data/com.ubuntu.sso.service.in'
        out_file = 'data/com.ubuntu.sso.service'
        replaced_path = '/usr/lib/ubuntu-sso-client'

        cmd = "%(cmd)s -e 's|\@libexecdir\@|%(rep)s|g' < %(in)s > %(out)s"
        os.system( cmd %
                  {'cmd' : sed,
                   'rep' : replaced_path,
                   'in' : in_file,
                   'out' : out_file,
                   }
                  )

        # Run the parent build command
        build_extra.build_extra.run(self)


class SSOLinuxClean(clean.clean):
    """Class to clean up after the build."""

    description = 'Clean up built files.'

    def run(self):
        """Clean up the built files."""
        for built_file in LINUX_CLEANFILES:
            if os.path.exists(built_file):
                os.unlink(built_file)

        # Run the parent clean command
        clean.clean.run(self)


class SSOWindowsBuild(build_extra.build_extra):
    """Build PyQt (.ui) files and resources."""

    description = "build PyQt GUIs (.ui) and resources (.qrc)"

    def compile_ui(self, ui_file, py_file=None):
        """Compile the .ui files to python modules."""
        # Search for pyuic4 in python bin dir, then in the $Path.
        if py_file is None:
            # go from the ui_file in the data folder to the
            # python file in the qt moodule
            py_file = os.path.split(ui_file)[1]
            py_file = os.path.splitext(py_file)[0] + '_ui.py'
            py_file = os.path.join('ubuntu_sso', 'qt', py_file)
        # we indeed want to catch Exception, is ugly but we need it
        # pylint: disable=W0703
        try:
            # import the uic compiler from pyqt and generate the .py files
            # something similar could be done with pyside but that is left
            # as an exercise for the reader.
            from PyQt4 import uic
            fp = open(py_file, 'w')
            uic.compileUi(ui_file, fp)
            fp.close()
            log.info('Compiled %s into %s', ui_file, py_file)
        except Exception, e:
            self.warn('Unable to compile user interface %s: %s', py_file, e)
            if not os.path.exists(py_file) or not file(py_file).read():
                raise SystemExit(1)
            return
        # pylint: enable=W0703

    def compile_rc(self, qrc_file, py_file=None):
        """Compile the resources that will be included with the project."""
        import PyQt4
        # Search for pyuic4 in python bin dir, then in the $Path.
        if py_file is None:
            py_file = os.path.split(qrc_file)[1]
            py_file = os.path.splitext(py_file)[0] + '_rc.py'
            py_file = os.path.join('ubuntu_sso', 'qt', py_file)
        path = os.getenv('PATH')
        os.putenv('PATH', path + ';' + os.path.join(
                  os.path.dirname(PyQt4.__file__),'bin'))
        if os.system('pyrcc4 "%s" -o "%s"' % (qrc_file, py_file)) > 0:
            self.warn('Unable to generate python module %s '
                      + 'for resource file %s', py_file, qrc_file)
            if not os.path.exists(py_file) or not file(py_file).read():
                raise SystemExit(1)
        else:
            log.info('compiled %s into %s' % (qrc_file, py_file))
        os.putenv('PATH', path)

    def _generate_qrc(self, qrc_file, srcfiles, prefix):
        """Generate the qrc file for the given src files."""
        basedir = os.path.dirname(qrc_file)
        f = open(qrc_file, 'w')
        try:
            f.write('<!DOCTYPE RCC><RCC version="1.0">\n')
            f.write('  <qresource prefix="%s">\n' % cgi.escape(prefix))
            for e in srcfiles:
                relpath = e[len(basedir) + 1:]
                f.write('    <file>%s</file>\n'
                        % cgi.escape(relpath.replace(os.path.sep, '/')))
            f.write('  </qresource>\n')
            f.write('</RCC>\n')
        finally:
            f.close()

    def build_rc(self, py_file, basedir, prefix='/'):
        """Generate compiled resource including any files under basedir"""
        # For details, see http://doc.qt.nokia.com/latest/resources.html
        qrc_file = os.path.join(basedir, '%s.qrc' % os.path.basename(basedir))
        srcfiles = [os.path.join(root, e)
                    for root, _dirs, files in os.walk(basedir) for e in files]
        # NOTE: Here we cannot detect deleted files. In such cases, we need
        # to remove .qrc manually.
        try:
            self._generate_qrc(qrc_file, srcfiles, prefix)
            self.compile_rc(qrc_file, py_file)
        finally:
            os.unlink(qrc_file)

    def run(self):
        """Execute the command."""
        self._wrapuic()
        basepath = os.path.join('data',  'qt')
        # TODO: build the resource files so that we can include them
        #self.build_rc(os.path.join(basepath, 'icons_rc.py'),
        #              os.path.join(os.path.dirname(__file__), 'icons'),
        #              '/icons')
        for dirpath, _, filenames in os.walk(basepath):
            for filename in filenames:
                if filename.endswith('.ui'):
                    self.compile_ui(os.path.join(dirpath, filename))
                elif filename.endswith('.qrc'):
                    self.compile_rc(os.path.join(dirpath, filename))

    # pylint: disable=E1002
    _wrappeduic = False
    @classmethod
    def _wrapuic(cls):
        """Wrap uic to use gettext's _() in place of tr()"""
        if cls._wrappeduic:
            return

        from PyQt4.uic.Compiler import compiler, qtproxies, indenter

        # pylint: disable=C0103
        class _UICompiler(compiler.UICompiler):
            """Speciallized compiler for qt .ui files."""
            def createToplevelWidget(self, classname, widgetname):
                o = indenter.getIndenter()
                o.level = 0
                o.write('from ubuntu_sso.utils.ui import _')
                return super(_UICompiler, self).createToplevelWidget(classname,
                    widgetname)
        compiler.UICompiler = _UICompiler

        class _i18n_string(qtproxies.i18n_string):
            """Provide a trnalated text."""

            def __str__(self):
                return "_('%s')" % self.string.encode('string-escape')

        qtproxies.i18n_string = _i18n_string

        cls._wrappeduic = True
        # pylint: enable=C0103
    # pylint: enable=E1002

class SSOWindowsClean(clean.clean):
    """Clean the files from a Windows build."""

    description = 'Clean up built files.'

    def run(self):
        """Clean up the built files."""
        # remove the generated ui files
        for dirpath, _, filenames in os.walk(os.path.join('ubuntu_sso', 'qt')):
            for current_file in filenames:
                if current_file.endswith('_ui.py') or\
                                current_file.endswith('_rc.py'):
                    os.unlink(os.path.join(dirpath, current_file))

# pylint: disable=W0621
def setup_windows():
    """Provide the required info to setup the project on windows."""
    scripts = []
    data_files = []
    packages = ['ubuntu_sso', 'ubuntu_sso.qt', 'ubuntu_sso.utils',
                'ubuntu_sso.keyring', 'ubuntu_sso.networkstate',
                'ubuntu_sso.main']
    extra = {}
    cmdclass = {'build' : SSOWindowsBuild,
                'clean' : SSOWindowsClean}

    # for PyQt, see http://www.py2exe.org/index.cgi/Py2exeAndPyQt
    includes = ['sip',]

    # Qt4 plugins, see http://stackoverflow.com/questions/2206406/
    def qt4_plugins(subdir, *dlls):
        """Add the required plugins so that we can package them."""
        import PyQt4
        pluginsdir = os.path.join(os.path.dirname(PyQt4.__file__), 'plugins')
        return (subdir, [os.path.join(pluginsdir, subdir, e) for e in dlls])

    data_files.append(qt4_plugins('imageformats', 'qico4.dll',
                                       'qsvg4.dll'))
    # ModuleFinder can't handle runtime changes to __path__,
    # but win32com uses them
    try:
        # py2exe 0.6.4 introduced a replacement modulefinder.
        # This means we have to add package paths there,
        # not to the built-in one.  If this new modulefinder gets
        # integrated into Python, then we might be able to revert
        # this some day. If this doesn't work, try import modulefinder
        # pylint: disable=F0401
        try:
            import py2exe.mf as modulefinder
        except ImportError:
            import modulefinder

        import win32com
        # pylint: enable=F0401
        for package_path in win32com.__path__[1:]:
            modulefinder.AddPackagePath("win32com", package_path)
        for extra_mod in ["win32com.server" ,"win32com.client"]: 
            __import__(extra_mod)
            module = sys.modules[extra_mod]
            for module_path in module.__path__[1:]:
                modulefinder.AddPackagePath(extra_mod, module_path)
    except ImportError:
        # no build path setup, no worries.
        pass

    extra['options'] = {
           'py2exe' : {
               'skip_archive' : 0,
               'includes' : includes,
               'optimize' : 1
           }
        }
    return scripts, data_files, packages, extra, cmdclass

def setup_linux():
    """Provide the required info to setup the project on linux."""
    scripts = []
    data_files = [('share/dbus-1/services', ['data/com.ubuntu.sso.service']),
                   ('lib/ubuntu-sso-client', ['bin/ubuntu-sso-login']),
                   ('share/ubuntu-sso-client/data/gtk', ['data/gtk/ui.glade'])]
    packages = ['ubuntu_sso', 'ubuntu_sso.gtk', 'ubuntu_sso.utils',
                'ubuntu_sso.keyring', 'ubuntu_sso.networkstate',
                'ubuntu_sso.main']
    extra = {}
    cmdclass = {'build' : SSOLinuxBuild,
                'clean' : SSOLinuxClean}
    return scripts, data_files, packages, extra, cmdclass

if __name__ == "__main__":

    # pylint: disable=C0103
    scripts = data_files = packages = extra = cmdclass = None
    if sys.platform == 'win32':
        scripts, data_files, packages, extra, cmdclass = setup_windows()
    else:
        scripts, data_files, packages, extra, cmdclass = setup_linux()

    DistUtilsExtra.auto.setup(
        name='ubuntu-sso-client',
        version='1.1.11',
        license='GPL v3',
        author='Natalia Bidart',
        author_email='natalia.bidart@canonical.com',
        description='Ubuntu Single Sign-On client',
        long_description='Desktop service to allow applications to sign in' \
            'to Ubuntu services via SSO',
        url='https://launchpad.net/ubuntu-sso-client',
        scripts=scripts,
        data_files = data_files,
        packages=packages,
        cmdclass=cmdclass,
        **extra)