build.setup.EggInfo._install_deps_wheels()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
"""Setup script.
2
3
Run "python3 setup.py --help-commands" to list all available commands and their
4
descriptions.
5
"""
6
import os
7
import shutil
8
import sys
9
from abc import abstractmethod
10
from pathlib import Path
11
from subprocess import CalledProcessError, call, check_call
12
13
from setuptools import Command, setup
14
from setuptools.command.develop import develop
15
from setuptools.command.egg_info import egg_info
16
from setuptools.command.install import install
17
18
if 'bdist_wheel' in sys.argv:
19
    raise RuntimeError("This setup.py does not support wheels")
20
21
# Paths setup with virtualenv detection
22
BASE_ENV = Path(os.environ.get('VIRTUAL_ENV', '/'))
23
24
NAPP_NAME = 'mef_eline'
25
NAPP_VERSION = '2.5.1'
26
27
# Kytos var folder
28
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
29
# Path for enabled NApps
30
ENABLED_PATH = VAR_PATH / 'napps'
31
# Path to install NApps
32
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
33
CURRENT_DIR = Path('.').resolve()
34
35
# NApps enabled by default
36
CORE_NAPPS = ['of_core']
37
38
39
class SimpleCommand(Command):
40
    """Make Command implementation simpler."""
41
42
    user_options = []
43
44
    @abstractmethod
45
    def run(self):
46
        """Run when command is invoked.
47
48
        Use *call* instead of *check_call* to ignore failures.
49
        """
50
51
    def initialize_options(self):
52
        """Set default values for options."""
53
54
    def finalize_options(self):
55
        """Post-process options."""
56
57
58
# pylint: disable=attribute-defined-outside-init, abstract-method
59
class TestCommand(Command):
60
    """Test tags decorators."""
61
62
    user_options = [
63
        ('size=', None, 'Specify the size of tests to be executed.'),
64
        ('type=', None, 'Specify the type of tests to be executed.'),
65
    ]
66
67
    sizes = ('small', 'medium', 'large', 'all')
68
    types = ('unit', 'integration', 'e2e')
69
70
    def get_args(self):
71
        """Return args to be used in test command."""
72
        return '--size %s --type %s' % (self.size, self.type)
73
74
    def initialize_options(self):
75
        """Set default size and type args."""
76
        self.size = 'all'
77
        self.type = 'unit'
78
79
    def finalize_options(self):
80
        """Post-process."""
81
        try:
82
            assert self.size in self.sizes, ('ERROR: Invalid size:'
83
                                             f':{self.size}')
84
            assert self.type in self.types, ('ERROR: Invalid type:'
85
                                             f':{self.type}')
86
        except AssertionError as exc:
87
            print(exc)
88
            sys.exit(-1)
89
90
91
class Cleaner(SimpleCommand):
92
    """Custom clean command to tidy up the project root."""
93
94
    description = 'clean build, dist, pyc and egg from package and docs'
95
96
    def run(self):
97
        """Clean build, dist, pyc and egg from package and docs."""
98
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
99
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
100
        call('make -C docs/ clean', shell=True)
101
102
103
class Test(TestCommand):
104
    """Run all tests."""
105
106
    description = 'run tests and display results'
107
108
    def get_args(self):
109
        """Return args to be used in test command."""
110
        markers = self.size
111
        if markers == "small":
112
            markers = 'not medium and not large'
113
        size_args = "" if self.size == "all" else "-m '%s'" % markers
114
        return '--addopts="tests/%s %s"' % (self.type, size_args)
115
116
    def run(self):
117
        """Run tests."""
118
        cmd = 'python setup.py pytest %s' % self.get_args()
119
        try:
120
            check_call(cmd, shell=True)
121
        except CalledProcessError as exc:
122
            print(exc)
123
            print('Unit tests failed. Fix the errors above and try again.')
124
            sys.exit(-1)
125
126
127
class TestCoverage(Test):
128
    """Display test coverage."""
129
130
    description = 'run tests and display code coverage'
131
132
    def run(self):
133
        """Run tests quietly and display coverage report."""
134
        cmd = 'coverage3 run setup.py pytest %s' % self.get_args()
135
        cmd += '&& coverage3 report'
136
        try:
137
            check_call(cmd, shell=True)
138
        except CalledProcessError as exc:
139
            print(exc)
140
            print('Coverage tests failed. Fix the errors above and try again.')
141
            sys.exit(-1)
142
143
144
class Linter(SimpleCommand):
145
    """Code linters."""
146
147
    description = 'lint Python source code'
148
149
    def run(self):
150
        """Run Yala."""
151
        print('Yala is running. It may take several seconds...')
152
        try:
153
            cmd = 'yala *.py tests'
154
            check_call(cmd, shell=True)
155
            print('No linter error found.')
156
        except CalledProcessError:
157
            print('Linter check failed. Fix the error(s) above and try again.')
158
            sys.exit(-1)
159
160
161
class CITest(TestCommand):
162
    """Run all CI tests."""
163
164
    description = 'run all CI tests: unit and doc tests, linter'
165
166
    def run(self):
167
        """Run unit tests with coverage, doc tests and linter."""
168
        coverage_cmd = 'python3.6 setup.py coverage %s' % self.get_args()
169
        lint_cmd = 'python3.6 setup.py lint'
170
        cmd = '%s && %s' % (coverage_cmd, lint_cmd)
171
        check_call(cmd, shell=True)
172
173
174
class KytosInstall:
175
    """Common code for all install types."""
176
177
    @staticmethod
178
    def enable_core_napps():
179
        """Enable a NAPP by creating a symlink."""
180
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
181
        for napp in CORE_NAPPS:
182
            napp_path = Path('kytos', napp)
183
            src = ENABLED_PATH / napp_path
184
            dst = INSTALLED_PATH / napp_path
185
            symlink_if_different(src, dst)
186
187
188
class InstallMode(install):
189
    """Create files in var/lib/kytos."""
190
191
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
192
193
    def run(self):
194
        """Direct users to use kytos-utils to install NApps."""
195
        print(self.description)
196
197
198
class EggInfo(egg_info):
199
    """Prepare files to be packed."""
200
201
    def run(self):
202
        """Build css."""
203
        self._install_deps_wheels()
204
        super().run()
205
206
    @staticmethod
207
    def _install_deps_wheels():
208
        """Python wheels are much faster (no compiling)."""
209
        print('Installing dependencies...')
210
        check_call([sys.executable, '-m', 'pip', 'install', '-r',
211
                    'requirements/run.in'])
212
213
214
class DevelopMode(develop):
215
    """Recommended setup for kytos-napps developers.
216
217
    Instead of copying the files to the expected directories, a symlink is
218
    created on the system aiming the current source code.
219
    """
220
221
    description = 'Install NApps in development mode'
222
223
    def run(self):
224
        """Install the package in a developer mode."""
225
        super().run()
226
        if self.uninstall:
227
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
228
        else:
229
            self._create_folder_symlinks()
230
            # self._create_file_symlinks()
231
            KytosInstall.enable_core_napps()
232
233
    @staticmethod
234
    def _create_folder_symlinks():
235
        """Symlink to all Kytos NApps folders.
236
237
        ./napps/kytos/napp_name will generate a link in
238
        var/lib/kytos/napps/.installed/kytos/napp_name.
239
        """
240
        links = INSTALLED_PATH / 'kytos'
241
        links.mkdir(parents=True, exist_ok=True)
242
        code = CURRENT_DIR
243
        src = links / NAPP_NAME
244
        symlink_if_different(src, code)
245
246
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
247
        dst = ENABLED_PATH / Path('kytos', NAPP_NAME)
248
        symlink_if_different(dst, src)
249
250
    @staticmethod
251
    def _create_file_symlinks():
252
        """Symlink to required files."""
253
        src = ENABLED_PATH / '__init__.py'
254
        dst = CURRENT_DIR / 'napps' / '__init__.py'
255
        symlink_if_different(src, dst)
256
257
258
def symlink_if_different(path, target):
259
    """Force symlink creation if it points anywhere else."""
260
    # print(f"symlinking {path} to target: {target}...", end=" ")
261
    if not path.exists():
262
        # print(f"path doesn't exist. linking...")
263
        path.symlink_to(target)
264
    elif not path.samefile(target):
265
        # print(f"path exists, but is different. removing and linking...")
266
        # Exists but points to a different file, so let's replace it
267
        path.unlink()
268
        path.symlink_to(target)
269
270
271
setup(name=f'kytos_{NAPP_NAME}',
272
      version=NAPP_VERSION,
273
      description='Core NApps developed by Kytos Team',
274
      url='http://github.com/kytos/{NAPP_NAME}',
275
      author='Kytos Team',
276
      author_email='[email protected]',
277
      license='MIT',
278
      install_requires=['setuptools >= 36.0.1'],
279
      setup_requires=['pytest-runner'],
280
      tests_require=['pytest'],
281
      extras_require={
282
          'dev': [
283
              'coverage',
284
              'pip-tools',
285
              'yala',
286
              'tox',
287
          ],
288
      },
289
      cmdclass={
290
          'clean': Cleaner,
291
          'ci': CITest,
292
          'coverage': TestCoverage,
293
          'develop': DevelopMode,
294
          'install': InstallMode,
295
          'lint': Linter,
296
          'egg_info': EggInfo,
297
          'test': Test,
298
      },
299
      zip_safe=False,
300
      classifiers=[
301
          'License :: OSI Approved :: MIT License',
302
          'Operating System :: POSIX :: Linux',
303
          'Programming Language :: Python :: 3.6',
304
          'Topic :: System :: Networking',
305
      ])
306