Passed
Pull Request — master (#69)
by Humberto
01:53
created

build.setup.DevelopMode.run()   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
rs 10
c 0
b 0
f 0
ccs 0
cts 6
cp 0
cc 2
nop 1
crap 6
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 = 'flow_manager'
28
NAPP_VERSION = '2.2.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 && coverage3 report'
81
        call(cmd, shell=True)
82
83
84
class Linter(SimpleCommand):
85
    """Code linters."""
86
87
    description = 'lint Python source code'
88
89
    def run(self):
90
        """Run yala."""
91
        print('Yala is running. It may take several seconds...')
92
        check_call('yala setup.py', shell=True)
93
94
95
class CITest(SimpleCommand):
96
    """Run all CI tests."""
97
98
    description = 'run all CI tests: unit and doc tests, linter'
99
100
    def run(self):
101
        """Run unit tests with coverage, doc tests and linter."""
102
        cmds = ['python3.6 setup.py ' + cmd
103
                for cmd in ('coverage', 'lint')]
104
        cmd = ' && '.join(cmds)
105
        check_call(cmd, shell=True)
106
107
108
class KytosInstall:
109
    """Common code for all install types."""
110
111
    @staticmethod
112
    def enable_core_napps():
113
        """Enable a NAPP by creating a symlink."""
114
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
115
        for napp in CORE_NAPPS:
116
            napp_path = Path('kytos', napp)
117
            src = ENABLED_PATH / napp_path
118
            dst = INSTALLED_PATH / napp_path
119
            symlink_if_different(src, dst)
120
121
122
class InstallMode(install):
123
    """Create files in var/lib/kytos."""
124
125
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
126
127
    def run(self):
128
        """Direct users to use kytos-utils to install NApps."""
129
        print(self.description)
130
131
132
class EggInfo(egg_info):
133
    """Prepare files to be packed."""
134
135
    def run(self):
136
        """Build css."""
137
        self._install_deps_wheels()
138
        super().run()
139
140
    @staticmethod
141
    def _install_deps_wheels():
142
        """Python wheels are much faster (no compiling)."""
143
        print('Installing dependencies...')
144
        check_call([sys.executable, '-m', 'pip', 'install', '-r',
145
                    'requirements/run.in'])
146
147
148
class DevelopMode(develop):
149
    """Recommended setup for kytos-napps developers.
150
151
    Instead of copying the files to the expected directories, a symlink is
152
    created on the system aiming the current source code.
153
    """
154
155
    description = 'Install NApps in development mode'
156
157
    def run(self):
158
        """Install the package in a developer mode."""
159
        super().run()
160
        if self.uninstall:
161
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
162
        else:
163
            self._create_folder_symlinks()
164
            # self._create_file_symlinks()
165
            KytosInstall.enable_core_napps()
166
167
    @staticmethod
168
    def _create_folder_symlinks():
169
        """Symlink to all Kytos NApps folders.
170
171
        ./napps/kytos/napp_name will generate a link in
172
        var/lib/kytos/napps/.installed/kytos/napp_name.
173
        """
174
        links = INSTALLED_PATH / 'kytos'
175
        links.mkdir(parents=True, exist_ok=True)
176
        code = CURRENT_DIR
177
        src = links / NAPP_NAME
178
        symlink_if_different(src, code)
179
180
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
181
        dst = ENABLED_PATH / Path('kytos', NAPP_NAME)
182
        symlink_if_different(dst, src)
183
184
    @staticmethod
185
    def _create_file_symlinks():
186
        """Symlink to required files."""
187
        src = ENABLED_PATH / '__init__.py'
188
        dst = CURRENT_DIR / 'napps' / '__init__.py'
189
        symlink_if_different(src, dst)
190
191
192
def symlink_if_different(path, target):
193
    """Force symlink creation if it points anywhere else."""
194
    # print(f"symlinking {path} to target: {target}...", end=" ")
195
    if not path.exists():
196
        # print(f"path doesn't exist. linking...")
197
        path.symlink_to(target)
198
    elif not path.samefile(target):
199
        # print(f"path exists, but is different. removing and linking...")
200
        # Exists but points to a different file, so let's replace it
201
        path.unlink()
202
        path.symlink_to(target)
203
204
205
setup(name=f'kytos_{NAPP_NAME}',
206
      version=NAPP_VERSION,
207
      description='Core NApps developed by the Kytos Team',
208
      url=f'http://github.com/kytos/{NAPP_NAME}',
209
      author='Kytos Team',
210
      author_email='[email protected]',
211
      license='MIT',
212
      install_requires=['setuptools >= 36.0.1'],
213
      extras_require={
214
          'dev': [
215
              'coverage',
216
              'pip-tools',
217
              'yala',
218
              'tox',
219
          ],
220
      },
221
      cmdclass={
222
          'clean': Cleaner,
223
          'ci': CITest,
224
          'coverage': TestCoverage,
225
          'develop': DevelopMode,
226
          'install': InstallMode,
227
          'lint': Linter,
228
          'egg_info': EggInfo,
229
      },
230
      zip_safe=False,
231
      classifiers=[
232
          'License :: OSI Approved :: MIT License',
233
          'Operating System :: POSIX :: Linux',
234
          'Programming Language :: Python :: 3.6',
235
          'Topic :: System :: Networking',
236
      ])
237