Passed
Pull Request — master (#176)
by Humberto
02:44
created

build.setup.CITest.run()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
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 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
if 'VIRTUAL_ENV' in os.environ:
23
    BASE_ENV = Path(os.environ['VIRTUAL_ENV'])
24
else:
25
    BASE_ENV = Path('/')
26
27
NAPP_NAME = 'mef_eline'
28
NAPP_VERSION = '2.3.1'
29
30
# Kytos var folder
31
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
32
# Path for enabled NApps
33
ENABLED_PATH = VAR_PATH / 'napps'
34
# Path to install NApps
35
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
36
CURRENT_DIR = Path('.').resolve()
37
38
# NApps enabled by default
39
CORE_NAPPS = ['of_core']
40
41
42
class SimpleCommand(Command):
43
    """Make Command implementation simpler."""
44
45
    user_options = []
46
47
    @abstractmethod
48
    def run(self):
49
        """Run when command is invoked.
50
51
        Use *call* instead of *check_call* to ignore failures.
52
        """
53
54
    def initialize_options(self):
55
        """Set default values for options."""
56
57
    def finalize_options(self):
58
        """Post-process options."""
59
60
61
class Cleaner(SimpleCommand):
62
    """Custom clean command to tidy up the project root."""
63
64
    description = 'clean build, dist, pyc and egg from package and docs'
65
66
    def run(self):
67
        """Clean build, dist, pyc and egg from package and docs."""
68
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
69
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
70
        call('make -C docs/ clean', shell=True)
71
72
73
class TestCoverage(SimpleCommand):
74
    """Display test coverage."""
75
76
    description = 'run unit tests and display code coverage'
77
78
    def run(self):
79
        """Run unittest quietly and display coverage report."""
80
        # cmd = 'coverage3 run -m unittest discover -qs src' \
81
        #       ' && coverage3 report'
82
83
        cmd = 'coverage3 run -m unittest && coverage3 report'
84
        call(cmd, shell=True)
85
86
87
class Linter(SimpleCommand):
88
    """Code linters."""
89
90
    description = 'lint Python source code'
91
92
    def run(self):
93
        """Run Yala."""
94
        print('Yala is running. It may take several seconds...')
95
        try:
96
            cmd = 'yala *.py tests/*.py tests/models/*.py'
97
            check_call(cmd, shell=True)
98
            print('No linter error found.')
99
        except RuntimeError as error:
100
            print('Linter check failed. Fix the error(s) above and try again.')
101
            print(error)
102
            exit(-1)
103
104
105
class CITest(SimpleCommand):
106
    """Run all CI tests."""
107
108
    description = 'run all CI tests: unit and doc tests, linter'
109
110
    def run(self):
111
        """Run unit tests with coverage, doc tests and linter."""
112
        cmds = ['python3.6 setup.py ' + cmd
113
                for cmd in ('coverage', 'lint')]
114
        cmd = ' && '.join(cmds)
115
        check_call(cmd, shell=True)
116
117
118
class KytosInstall:
119
    """Common code for all install types."""
120
121
    @staticmethod
122
    def enable_core_napps():
123
        """Enable a NAPP by creating a symlink."""
124
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
125
        for napp in CORE_NAPPS:
126
            napp_path = Path('kytos', napp)
127
            src = ENABLED_PATH / napp_path
128
            dst = INSTALLED_PATH / napp_path
129
            symlink_if_different(src, dst)
130
131
132
class InstallMode(install):
133
    """Create files in var/lib/kytos."""
134
135
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
136
137
    def run(self):
138
        """Direct users to use kytos-utils to install NApps."""
139
        print(self.description)
140
141
142
class EggInfo(egg_info):
143
    """Prepare files to be packed."""
144
145
    def run(self):
146
        """Build css."""
147
        self._install_deps_wheels()
148
        super().run()
149
150
    @staticmethod
151
    def _install_deps_wheels():
152
        """Python wheels are much faster (no compiling)."""
153
        print('Installing dependencies...')
154
        check_call([sys.executable, '-m', 'pip', 'install', '-r',
155
                    'requirements/run.in'])
156
157
158
class DevelopMode(develop):
159
    """Recommended setup for kytos-napps developers.
160
161
    Instead of copying the files to the expected directories, a symlink is
162
    created on the system aiming the current source code.
163
    """
164
165
    description = 'Install NApps in development mode'
166
167
    def run(self):
168
        """Install the package in a developer mode."""
169
        super().run()
170
        if self.uninstall:
171
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
172
        else:
173
            self._create_folder_symlinks()
174
            self._create_file_symlinks()
175
            KytosInstall.enable_core_napps()
176
177
    @staticmethod
178
    def _create_folder_symlinks():
179
        """Symlink to all Kytos NApps folders.
180
181
        ./napps/kytos/napp_name will generate a link in
182
        var/lib/kytos/napps/.installed/kytos/napp_name.
183
        """
184
        links = INSTALLED_PATH / 'kytos'
185
        links.mkdir(parents=True, exist_ok=True)
186
        code = CURRENT_DIR
187
        src = links / NAPP_NAME
188
        symlink_if_different(src, code)
189
190
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
191
        dst = ENABLED_PATH / Path('kytos', NAPP_NAME)
192
        symlink_if_different(dst, src)
193
194
    @staticmethod
195
    def _create_file_symlinks():
196
        """Symlink to required files."""
197
        src = ENABLED_PATH / '__init__.py'
198
        dst = CURRENT_DIR / 'napps' / '__init__.py'
199
        symlink_if_different(src, dst)
200
201
202
def symlink_if_different(path, target):
203
    """Force symlink creation if it points anywhere else."""
204
    # print(f"symlinking {path} to target: {target}...", end=" ")
205
    if not path.exists():
206
        # print(f"path doesn't exist. linking...")
207
        path.symlink_to(target)
208
    elif not path.samefile(target):
209
        # print(f"path exists, but is different. removing and linking...")
210
        # Exists but points to a different file, so let's replace it
211
        path.unlink()
212
        path.symlink_to(target)
213
214
215
setup(name=f'kytos_{NAPP_NAME}',
216
      version=NAPP_VERSION,
217
      description='Core NApps developed by Kytos Team',
218
      url='http://github.com/kytos/{NAPP_NAME}',
219
      author='Kytos Team',
220
      author_email='[email protected]',
221
      license='MIT',
222
      install_requires=['setuptools >= 36.0.1'],
223
      extras_require={
224
          'dev': [
225
              'coverage',
226
              'pip-tools',
227
              'yala',
228
              'tox',
229
          ],
230
      },
231
      cmdclass={
232
          'clean': Cleaner,
233
          'ci': CITest,
234
          'coverage': TestCoverage,
235
          'develop': DevelopMode,
236
          'install': InstallMode,
237
          'lint': Linter,
238
          'egg_info': EggInfo,
239
      },
240
      zip_safe=False,
241
      classifiers=[
242
          'License :: OSI Approved :: MIT License',
243
          'Operating System :: POSIX :: Linux',
244
          'Programming Language :: Python :: 3.6',
245
          'Topic :: System :: Networking',
246
      ])
247