build.setup.DevelopMode._create_file_symlinks()   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 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
25
NAPP_NAME = 'topology'
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
        ("k=", None, "Specify a pytest -k expression."),
64
    ]
65
66
    def get_args(self):
67
        """Return args to be used in test command."""
68
        if self.k:
69
            return f"-k '{self.k}'"
70
        return ""
71
72
    def initialize_options(self):
73
        """Set default size and type args."""
74
        self.k = ""
75
76
    def finalize_options(self):
77
        """Post-process."""
78
        pass
79
80
81
class Cleaner(SimpleCommand):
82
    """Custom clean command to tidy up the project root."""
83
84
    description = 'clean build, dist, pyc and egg from package and docs'
85
86
    def run(self):
87
        """Clean build, dist, pyc and egg from package and docs."""
88
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
89
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
90
        call('make -C docs/ clean', shell=True)
91
92
93
class Test(TestCommand):
94
    """Run all tests."""
95
96
    description = "run tests and display results"
97
98
    def run(self):
99
        """Run tests."""
100
        cmd = "python3 -m pytest tests/ --cov-report term-missing"
101
        cmd += f" {self.get_args()}"
102
        try:
103
            check_call(cmd, shell=True)
104
        except CalledProcessError as exc:
105
            print(exc)
106
            print('Unit tests failed. Fix the errors above and try again.')
107
            sys.exit(-1)
108
109
110
class TestCoverage(Test):
111
    """Display test coverage."""
112
113
    description = "run tests and display code coverage"
114
115
    def run(self):
116
        """Run tests quietly and display coverage report."""
117
        cmd = "python3 -m pytest --cov=. tests/ --cov-report term-missing"
118
        cmd += f" {self.get_args()}"
119
        try:
120
            check_call(cmd, shell=True)
121
        except CalledProcessError as exc:
122
            print(exc)
123
            print('Coverage tests failed. Fix the errors above and try again.')
124
            sys.exit(-1)
125
126
127
class Linter(SimpleCommand):
128
    """Code linters."""
129
130
    description = 'lint Python source code'
131
132
    def run(self):
133
        """Run yala."""
134
        print('Yala is running. It may take several seconds...')
135
        try:
136
            check_call('yala *.py controllers db tests', shell=True)
137
            print('No linter error found.')
138
        except CalledProcessError:
139
            print('Linter check failed. Fix the error(s) above and try again.')
140
            sys.exit(-1)
141
142
143
class KytosInstall:
144
    """Common code for all install types."""
145
146
    @staticmethod
147
    def enable_core_napps():
148
        """Enable a NAPP by creating a symlink."""
149
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
150
        for napp in CORE_NAPPS:
151
            napp_path = Path('kytos', napp)
152
            src = ENABLED_PATH / napp_path
153
            dst = INSTALLED_PATH / napp_path
154
            symlink_if_different(src, dst)
155
156
157
class InstallMode(install):
158
    """Create files in var/lib/kytos."""
159
160
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
161
162
    def run(self):
163
        """Direct users to use kytos-utils to install NApps."""
164
        print(self.description)
165
166
167
class EggInfo(egg_info):
168
    """Prepare files to be packed."""
169
170
    def run(self):
171
        """Build css."""
172
        self._install_deps_wheels()
173
        super().run()
174
175
    @staticmethod
176
    def _install_deps_wheels():
177
        """Python wheels are much faster (no compiling)."""
178
        print('Installing dependencies...')
179
        check_call([sys.executable, '-m', 'pip', 'install', '-r',
180
                    'requirements/run.txt'])
181
182
183
class DevelopMode(develop):
184
    """Recommended setup for kytos-napps developers.
185
186
    Instead of copying the files to the expected directories, a symlink is
187
    created on the system aiming the current source code.
188
    """
189
190
    description = 'Install NApps in development mode'
191
192
    def run(self):
193
        """Install the package in a developer mode."""
194
        super().run()
195
        if self.uninstall:
196
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
197
        else:
198
            self._create_folder_symlinks()
199
            # self._create_file_symlinks()
200
            KytosInstall.enable_core_napps()
201
202
    @staticmethod
203
    def _create_folder_symlinks():
204
        """Symlink to all Kytos NApps folders.
205
206
        ./napps/kytos/napp_name will generate a link in
207
        var/lib/kytos/napps/.installed/kytos/napp_name.
208
        """
209
        links = INSTALLED_PATH / 'kytos'
210
        links.mkdir(parents=True, exist_ok=True)
211
        code = CURRENT_DIR
212
        src = links / NAPP_NAME
213
        symlink_if_different(src, code)
214
215
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
216
        dst = ENABLED_PATH / Path('kytos', NAPP_NAME)
217
        symlink_if_different(dst, src)
218
219
    @staticmethod
220
    def _create_file_symlinks():
221
        """Symlink to required files."""
222
        src = ENABLED_PATH / '__init__.py'
223
        dst = CURRENT_DIR / 'napps' / '__init__.py'
224
        symlink_if_different(src, dst)
225
226
227
def symlink_if_different(path, target):
228
    """Force symlink creation if it points anywhere else."""
229
    # print(f"symlinking {path} to target: {target}...", end=" ")
230
    if not path.exists():
231
        # print(f"path doesn't exist. linking...")
232
        path.symlink_to(target)
233
    elif not path.samefile(target):
234
        # print(f"path exists, but is different. removing and linking...")
235
        # Exists but points to a different file, so let's replace it
236
        path.unlink()
237
        path.symlink_to(target)
238
239
240
def read_version_from_json():
241
    """Read the NApp version from NApp kytos.json file."""
242
    file = Path('kytos.json')
243
    metadata = json.loads(file.read_text(encoding="utf8"))
244
    return metadata['version']
245
246
247
def read_requirements(path="requirements/run.txt"):
248
    """Read requirements file and return a list."""
249
    with open(path, "r", encoding="utf8") as file:
250
        return [
251
            line.strip()
252
            for line in file.readlines()
253
            if not line.startswith("#")
254
        ]
255
256
257
setup(name=f'kytos_{NAPP_NAME}',
258
      version=read_version_from_json(),
259
      description='Core NApps developed by the Kytos Team',
260
      url=f'http://github.com/kytos/{NAPP_NAME}',
261
      author='Kytos Team',
262
      author_email='[email protected]',
263
      license='MIT',
264
      install_requires=read_requirements(),
265
      packages=[],
266
      cmdclass={
267
          'clean': Cleaner,
268
          'coverage': TestCoverage,
269
          'develop': DevelopMode,
270
          'install': InstallMode,
271
          'lint': Linter,
272
          'egg_info': EggInfo,
273
          'test': Test,
274
      },
275
      zip_safe=False,
276
      classifiers=[
277
          'License :: OSI Approved :: MIT License',
278
          'Operating System :: POSIX :: Linux',
279
          'Topic :: System :: Networking',
280
      ])
281