build.setup   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 301
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 27
eloc 158
dl 0
loc 301
rs 10
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A SimpleCommand.initialize_options() 0 2 1
A SimpleCommand.run() 0 3 1
A SimpleCommand.finalize_options() 0 2 1
A Cleaner.run() 0 5 1
A TestCommand.finalize_options() 0 10 2
A TestCommand.get_args() 0 3 1
A TestCommand.initialize_options() 0 4 1
A Test.get_args() 0 7 3
A InstallMode.run() 0 3 1
A CITest.run() 0 6 1
A Linter.run() 0 4 1
A DevelopMode._create_folder_symlinks() 0 16 1
A EggInfo._install_deps_wheels() 0 6 1
A DevelopMode.run() 0 7 2
A EggInfo.run() 0 4 1
A Test.run() 0 9 2
A TestCoverage.run() 0 10 2

2 Functions

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