test_for_imports()   C
last analyzed

Complexity

Conditions 7

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
c 2
b 0
f 0
dl 0
loc 27
rs 5.5
1
#!/usr/bin/env python
2
"""
3
4
@todo:
5
 - Identify minimum dependency versions properly.
6
 - Figure out how to mark optional packages as optional.
7
 - Is there a more idiomatic way to handle install_requires for things which
8
   don't always install the requisite metadata for normal detection?
9
"""
10
11
from __future__ import print_function
12
13
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
14
__license__ = "GNU GPL 2.0 or later"
15
16
import io, os, re, sys
17
from setuptools import setup
18
19
# Requirements adapter for packages which may not be PyPI-installable
20
REQUIRES = []
21
22
# TODO: Look up how to make this a setuptools feature
23
# REQUIRES = ['python-xlib',]
24
25
# Look outside the virtualenv for PyGTK
26
# Source: https://stackoverflow.com/a/27471354/435253
27
try:
28
    # pylint: disable=unused-import
29
    import gtk  # NOQA
30
except ImportError:
31
    print('--------------')
32
    import subprocess
33
    instdir = subprocess.check_output([
34
        '/usr/bin/python',
35
        '-c',
36
        'import os, pygtk; print os.path.dirname(pygtk.__file__)',
37
    ]).strip()
38
    for dst_base in sys.path:
39
        if dst_base.strip():
40
            break
41
        for d in ['pygtk.pth', 'pygtk.py', 'gtk-2.0', 'gobject', 'glib',
42
                  'cairo']:
43
            src = os.path.join(instdir, d)
44
            dst = os.path.join(dst_base, d)
45
            if os.path.exists(src) and not os.path.exists(dst):
46
                print('linking', d, 'to', dst_base)
47
                os.symlink(src, dst)
48
49
def test_for_imports(choices, package_name, human_package_name):
50
    """Detect packages without requiring egg metadata
51
52
    Fallback to either adding an install_requires entry or exiting with
53
    an error message.
54
    """
55
    if os.environ.get("IS_BUILDING_PACKAGE", None):
56
        return  # Allow packaging without runtime-only deps installed
57
58
    if isinstance(choices, basestring):
59
        choices = [choices]
60
61
    while choices:
62
        # Detect package without requiring egg metadata
63
        try:
64
            current = choices.pop(0)
65
            __import__(current)
66
        except ImportError:
67
            if choices:  # Allow a fallback chain
68
                continue
69
70
            if package_name:
71
                REQUIRES.append(package_name)
72
            else:
73
                print("Could not import '%s'. Please make sure you have %s "
74
                      "installed." % (current, human_package_name))
75
                sys.exit(1)
76
77
test_for_imports("gtk", "pygtk", "PyGTK")
78
test_for_imports("wnck", "python-wnck", "python-wnck")
79
80
# TODO: Look up how to make this a setuptools feature
81
# test_for_imports("dbus", "dbus-python", "python-dbus")
82
83
# Get the version from the program rather than duplicating it here
84
# Source: https://packaging.python.org/en/latest/single_source_version.html
85
def read(*names, **kwargs):
86
    """Convenience wrapper for read()ing a file"""
87
    with io.open(os.path.join(os.path.dirname(__file__), *names),
88
              encoding=kwargs.get("encoding", "utf8")) as fobj:
89
        return fobj.read()
90
91
def find_version(*file_paths):
92
    """Extract the value of __version__ from the given file"""
93
    version_file = read(*file_paths)
94
    version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]",
95
                              version_file, re.M)
96
    if version_match:
97
        return version_match.group(1)
98
    raise RuntimeError("Unable to find version string.")
99
100
if __name__ == '__main__':
101
    setup(
102
        name='QuickTile',
103
        version=find_version("quicktile", "version.py"),
104
        author='Stephan Sokolow (deitarion/SSokolow)',
105
        author_email='http://ssokolow.com/ContactMe',
106
        description='Add keyboard-driven window-tiling to any X11 window '
107
                    'manager (inspired by WinSplit Revolution)',
108
        long_description=read("README.rst"),
109
        url="http://ssokolow.com/quicktile/",
110
111
        classifiers=[
112
            'Development Status :: 4 - Beta',
113
            'Environment :: X11 Applications :: GTK',
114
            'Intended Audience :: End Users/Desktop',
115
            'License :: OSI Approved :: GNU General Public License v2 or later'
116
            ' (GPLv2+)',
117
            'Natural Language :: English',
118
            'Operating System :: POSIX',
119
            'Programming Language :: Python :: 2 :: Only',
120
            'Topic :: Desktop Environment :: Window Managers',
121
            'Topic :: Utilities',
122
        ],
123
        keywords=('x11 desktop window tiling wm utility addon extension tile '
124
                  'layout positioning helper keyboard hotkey hotkeys shortcut '
125
                  'shortcuts tool'),
126
        license="GPL-2.0+",
127
128
        install_requires=REQUIRES,
129
130
        packages=['quicktile'],
131
        entry_points={
132
            'console_scripts': ['quicktile=quicktile.__main__:main']
133
        },
134
        data_files=[('share/applications', ['quicktile.desktop'])]
135
    )
136
137
# vim: set sw=4 sts=4 expandtab :
138