build.setup.read_requirements()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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