~ubuntuone-control-tower/ubuntu-sso-client/stable-13-10

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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/python
# setup.py - Build system for Ubuntu SSO Client package
#
# Copyright 2010-2012 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/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Setup.py: build, distribute, clean."""

# pylint: disable=W0404, W0511

import distutils
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 ubuntu_sso.utils import get_cert_dir

PROJECT_NAME = 'ubuntu-sso-client'
VERSION = '13.05'

POT_FILE = 'po/ubuntu-sso-client.pot'
SERVICE_FILE = 'data/com.ubuntu.sso.service'
CONSTANTS = 'ubuntu_sso/constants.py'

CLEANFILES = [SERVICE_FILE, POT_FILE, CONSTANTS, 'MANIFEST']
QT_UI_DIR = os.path.join('ubuntu_sso', 'qt', 'ui')


def replace_version(*args, **kwargs):
    """Replace the @VERSION@ in the constants file with the actual version."""
    with open(CONSTANTS + '.in') as in_file:
        content = in_file.read()
        with open(CONSTANTS, 'w') as out_file:
            content = content.replace('@VERSION@', VERSION)
            content = content.replace('@PROJECT_NAME@', PROJECT_NAME)
            out_file.write(content)


def replace_prefix(prefix):
    """Replace every '@prefix@' with prefix within 'filename' content."""
    with open(SERVICE_FILE + '.in') as in_file:
        content = in_file.read()
        with open(SERVICE_FILE, 'w') as out_file:
            out_file.write(content.replace('@prefix@', prefix))


class SSOInstall(DistUtilsExtra.auto.install_auto):
    """Class to install proper files."""

    def run(self):
        """Do the install.

        Read from *.service.in and generate .service files by replacing
        @prefix@ by self.prefix.

        """
        prefix = self.install_data.replace(
            self.root if self.root is not None else '', '')
        replace_prefix(prefix)
        DistUtilsExtra.auto.install_auto.run(self)
        # Replace the CONSTANTS prefix here, so that we can do it directly in
        # the installed copy, rather than the lcoal copy. This allows us to
        # have a semi-generated version for use in tests, and a full version
        # for use in installed systems.
        with open(CONSTANTS) as in_file:
            content = in_file.read()
            with open(os.path.join(self.install_purelib,
                                   PROJECT_NAME,
                                   CONSTANTS), 'w') as out_file:
                out_file.write(content.replace('@prefix@', prefix))


class SSOBuild(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(QT_UI_DIR, 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(QT_UI_DIR, py_file)
        path = os.getenv('PATH')
        os.putenv('PATH', path + os.path.pathsep + os.path.join(
                  os.path.dirname(PyQt4.__file__), 'bin'))
        if os.system('pyrcc4 -no-compress "%s" -o "%s"' %
                     (qrc_file, py_file)) > 0:
            self.warn('Unable to generate python module {py_file}'
                      ' for resource file {qrc_file}'.format(
                      py_file=py_file, qrc_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')
            import cgi
            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."""
        replace_version()
        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))

        build_extra.build_extra.run(self)


class SSOClean(DistUtilsExtra.auto.clean_build_tree):
    """Class to clean up after the build."""

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

        for dirpath, _, filenames in os.walk(os.path.join(QT_UI_DIR)):
            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))

        DistUtilsExtra.auto.clean_build_tree.run(self)


def set_py2exe_paths():
    """Set the path so that py2exe finds the required modules."""
    # Pylint does not understand same spaced imports
    # pylint: disable=F0401
    import win32com
    # pylint: enable=F0401
    try:
        # pylint: disable=F0401
        import py2exe.mf as modulefinder
        # pylint: enable=F0401
    except ImportError:
        import modulefinder

    # 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
    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)


# pylint: disable=C0103

cmdclass = {
    'install': SSOInstall,
    'build': SSOBuild,
    'clean': SSOClean,
}


sso_executables = [
    'bin/ubuntu-sso-login',
    'bin/ubuntu-sso-login-qt',
    'bin/ubuntu-sso-proxy-creds-qt',
    'bin/ubuntu-sso-ssl-certificate-qt',
]


class dummy_build_i18n(distutils.cmd.Command):

    """Dummy for windows."""

    def initialize_options(self, *args):
        """Dummy."""

    def finalize_options(self, *args):
        """Dummy."""

    def run(self, *args):
        """Dummy."""


if sys.platform == 'win32':
    cmdclass['build_i18n'] = dummy_build_i18n


data_files = [(get_cert_dir(),
              ['data/UbuntuOne-Go_Daddy_CA.pem',
               'data/UbuntuOne-ValiCert_Class_2_VA.pem',
               'data/UbuntuOne-Go_Daddy_Class_2_CA.pem'])]

if sys.platform == 'win32':
    set_py2exe_paths()
    # for PyQt, see http://www.py2exe.org/index.cgi/Py2exeAndPyQt
    _includes = ['sip', 'email', 'ubuntu_sso.qt.gui',
                 'ubuntu_sso.qt.controllers', 'PyQt4.QtNetwork', 'PIL']
    extra = {
        'options': {
            'py2exe': {
                'bundle_files': 1,
                'skip_archive': 0,
                'includes': _includes,
                'optimize': 1,
                'dll_excludes': ["mswsock.dll", "powrprof.dll"],
            },
        },
        # add the console script so that py2exe compiles it
        'console': sso_executables,
        'zipfile': None,
    }
else:
    data_files.extend([
        ('lib/ubuntu-sso-client', sso_executables),
        ('share/dbus-1/services', ['data/com.ubuntu.sso.service']),
    ])
    extra = {}

DistUtilsExtra.auto.setup(
    name=PROJECT_NAME,
    version=VERSION,
    license='GPL v3',
    author='Ubuntu One Developers',
    author_email='ubuntuone-users@lists.launchpad.net',
    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',
    extra_path=PROJECT_NAME,
    data_files=data_files,
    packages=[
        'ubuntu_sso',
        'ubuntu_sso.tests',
        'ubuntu_sso.keyring',
        'ubuntu_sso.keyring.tests',
        'ubuntu_sso.main',
        'ubuntu_sso.main.tests',
        'ubuntu_sso.networkstate',
        'ubuntu_sso.networkstate.tests',
        'ubuntu_sso.qt',
        'ubuntu_sso.qt.main',
        'ubuntu_sso.qt.ui',
        'ubuntu_sso.utils',
        'ubuntu_sso.utils.tests',
        'ubuntu_sso.utils.runner',
        'ubuntu_sso.utils.runner.tests',
        'ubuntu_sso.utils.webclient',
        'ubuntu_sso.utils.webclient.tests',
    ],
    cmdclass=cmdclass,
    **extra)