~nataliabidart/ubuntuone-control-panel/handle-credentials-error

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
#!/usr/bin/env python
# setup.py - Build system for Ubuntu One Control Panel package
#
# Authors: Natalia B. Bidart <natalia.bidart@canonical.com>
#          Manuel de la Pena <manuel@canonical.com>
#          Alejandro J. Cura <alecu@canonical.com>
#
# Copyright 2010-2011 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: build, distribute, clean."""

# pylint: disable=W0404

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

POT_FILE = 'po/ubuntuone-control-panel.pot'
SERVICE_FILE = 'com.ubuntuone.controlpanel.service'
MESSAGE_ENTRY = 'ubuntuone-control-panel'
CONSTANTS = 'ubuntuone/controlpanel/constants.py'

CLEANFILES = [
    SERVICE_FILE, MESSAGE_ENTRY, CONSTANTS, POT_FILE,
    'MANIFEST']
QT_UI_DIR = os.path.join('ubuntuone', 'controlpanel', 'gui', 'qt', 'ui')


def replace_prefix(prefix):
    """Replace every '@prefix@' with prefix within 'filename' content."""
    # replace .service file, DATA_DIR constant
    for filename in (SERVICE_FILE, MESSAGE_ENTRY, CONSTANTS):
        with open(filename + '.in') as in_file:
            content = in_file.read()
            with open(filename, 'w') as out_file:
                out_file.write(content.replace('@prefix@', prefix))


class ControlPanelInstall(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.

        """
        replace_prefix(self.prefix)
        DistUtilsExtra.auto.install_auto.run(self)


class ControlPanelBuild(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."""
        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 ControlPanelClean(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)


DistUtilsExtra.auto.setup(
    name='ubuntuone-control-panel',
    version='3.1',
    license='GPL v3',
    author='Natalia Bidart',
    author_email='natalia.bidart@canonical.com',
    description='Ubuntu One Control Panel',
    long_description='Application to manage an Ubuntu One account.',
    url='https://launchpad.net/ubuntuone-control-panel',
    packages=[
        'ubuntuone',
        'ubuntuone.controlpanel',
        'ubuntuone.controlpanel.gui',
        'ubuntuone.controlpanel.gui.qt',
        'ubuntuone.controlpanel.gui.qt.main',
        'ubuntuone.controlpanel.gui.qt.ui',
        'ubuntuone.controlpanel.gui.qt.uniqueapp',
        'ubuntuone.controlpanel.sd_client',
        'ubuntuone.controlpanel.utils',
    ],
    extra_path='ubuntuone-control-panel',
    data_files=[
        ('lib/ubuntuone-control-panel',
         ['bin/ubuntuone-control-panel-backend']),
        ('share/dbus-1/services/', [SERVICE_FILE]),
        ('share/indicators/messages/applications/', [MESSAGE_ENTRY]),
        ('share/apport/package-hooks/',
         ['data/source_ubuntuone-control-panel.py']),
    ],
    cmdclass={
        'install': ControlPanelInstall,
        'build': ControlPanelBuild,
        'clean': ControlPanelClean,
    },
)