Passed
Push — master ( 2117f0...6ee0f8 )
by Vinicius
02:01 queued 12s
created

build.setup.read_version_from_json()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 0
dl 0
loc 5
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 = 'sdntrace_cp'
26
NAPP_USERNAME = 'amlight'
27
28
# Kytos var folder
29
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
30
# Path for enabled NApps
31
ENABLED_PATH = VAR_PATH / 'napps'
32
# Path to install NApps
33
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
34
CURRENT_DIR = Path('.').resolve()
35
36
# NApps enabled by default
37
CORE_NAPPS = []
38
39
40
class SimpleCommand(Command):
41
    """Make Command implementation simpler."""
42
43
    user_options = []
44
45
    @abstractmethod
46
    def run(self):
47
        """Run when command is invoked.
48
49
        Use *call* instead of *check_call* to ignore failures.
50
        """
51
52
    def initialize_options(self):
53
        """Set default values for options."""
54
55
    def finalize_options(self):
56
        """Post-process options."""
57
58
59
# pylint: disable=attribute-defined-outside-init, abstract-method
60
class TestCommand(Command):
61
    """Test tags decorators."""
62
63
    user_options = [
64
        ("k=", None, "Specify a pytest -k expression."),
65
    ]
66
67
    def get_args(self):
68
        """Return args to be used in test command."""
69
        if self.k:
70
            return f"-k '{self.k}'"
71
        return ""
72
73
    def initialize_options(self):
74
        """Set default size and type args."""
75
        self.k = ""
76
77
    def finalize_options(self):
78
        """Post-process."""
79
        pass
80
81
82
class Cleaner(SimpleCommand):
83
    """Custom clean command to tidy up the project root."""
84
85
    description = 'clean build, dist, pyc and egg from package and docs'
86
87
    def run(self):
88
        """Clean build, dist, pyc and egg from package and docs."""
89
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
90
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
91
        call('make -C docs/ clean', shell=True)
92
93
94
class Test(TestCommand):
95
    """Run all tests."""
96
97
    description = "run tests and display results"
98
99
    def run(self):
100
        """Run tests."""
101
        cmd = f"python3 -m pytest tests/ {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 = f"python3 -m pytest --cov=. tests/ {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
        try:
135
            cmd = "yala *.py tests"
136
            check_call(cmd, 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 / NAPP_USERNAME).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
    def __str__(self):
157
        return self.__class__.__name__
158
159
160
class InstallMode(install):
161
    """Create files in var/lib/kytos."""
162
163
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
164
165
    def run(self):
166
        """Direct users to use kytos-utils to install NApps."""
167
        print(self.description)
168
169
170
class EggInfo(egg_info):
171
    """Prepare files to be packed."""
172
173
    def run(self):
174
        """Build css."""
175
        self._install_deps_wheels()
176
        super().run()
177
178
    @staticmethod
179
    def _install_deps_wheels():
180
        """Python wheels are much faster (no compiling)."""
181
        print('Installing dependencies...')
182
        check_call(
183
            [
184
                sys.executable,
185
                "-m",
186
                "pip",
187
                "install",
188
                "-r",
189
                "requirements/run.txt",
190
            ]
191
        )
192
193
194
class DevelopMode(develop):
195
    """Recommended setup for kytos-napps developers.
196
197
    Instead of copying the files to the expected directories, a symlink is
198
    created on the system aiming the current source code.
199
    """
200
201
    description = 'Install NApps in development mode'
202
203
    def run(self):
204
        """Install the package in a developer mode."""
205
        super().run()
206
        if self.uninstall:
207
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
208
        else:
209
            self._create_folder_symlinks()
210
            # self._create_file_symlinks()
211
            KytosInstall.enable_core_napps()
212
213
    @staticmethod
214
    def _create_folder_symlinks():
215
        """Symlink to all Kytos NApps folders.
216
217
        ./napps/kytos/napp_name will generate a link in
218
        var/lib/kytos/napps/.installed/kytos/napp_name.
219
        """
220
        links = INSTALLED_PATH / NAPP_USERNAME
221
        links.mkdir(parents=True, exist_ok=True)
222
        code = CURRENT_DIR
223
        src = links / NAPP_NAME
224
        symlink_if_different(src, code)
225
226
        (ENABLED_PATH / NAPP_USERNAME).mkdir(parents=True, exist_ok=True)
227
        dst = ENABLED_PATH / Path(NAPP_USERNAME, NAPP_NAME)
228
        symlink_if_different(dst, src)
229
230
    @staticmethod
231
    def _create_file_symlinks():
232
        """Symlink to required files."""
233
        src = ENABLED_PATH / '__init__.py'
234
        dst = CURRENT_DIR / '__init__.py'
235
        symlink_if_different(src, dst)
236
237
238
def symlink_if_different(path, target):
239
    """Force symlink creation if it points anywhere else."""
240
    # print(f"symlinking {path} to target: {target}...", end=" ")
241
    if not path.exists():
242
        # print(f"path doesn't exist. linking...")
243
        path.symlink_to(target)
244
    elif not path.samefile(target):
245
        # print(f"path exists, but is different. removing and linking...")
246
        # Exists but points to a different file, so let's replace it
247
        path.unlink()
248
        path.symlink_to(target)
249
250
251
def read_version_from_json():
252
    """Read the NApp version from NApp kytos.json file."""
253
    file = Path('kytos.json')
254
    metadata = json.loads(file.read_text(encoding="utf8"))
255
    return metadata['version']
256
257
258
def read_requirements(path="requirements/run.txt"):
259
    """Read requirements file and return a list."""
260
    with open(path, "r", encoding="utf8") as file:
261
        return [
262
            line.strip()
263
            for line in file.readlines()
264
            if not line.startswith("#")
265
        ]
266
267
268
setup(name=f'{NAPP_USERNAME}_{NAPP_NAME}',
269
      version=read_version_from_json(),
270
      description='Run tracepaths on OpenFlow in the Control Plane',
271
      url='http://github.com/kytos-ng/sdntrace_cp',
272
      author='FIU/AmLight team',
273
      author_email='[email protected]',
274
      license='MIT',
275
      install_requires=read_requirements() + ["setuptools >= 59.6.0"],
276
      packages=[],
277
      extras_require={
278
          'dev': [
279
              'pytest==7.0.0',
280
              'pytest-cov==3.0.0',
281
              'coverage',
282
              'pip-tools',
283
              'yala',
284
              'tox',
285
          ],
286
      },
287
      cmdclass={
288
          'clean': Cleaner,
289
          'coverage': TestCoverage,
290
          'develop': DevelopMode,
291
          'install': InstallMode,
292
          'lint': Linter,
293
          'egg_info': EggInfo,
294
          'test': Test,
295
      },
296
      zip_safe=False,
297
      classifiers=[
298
          'License :: OSI Approved :: MIT License',
299
          'Operating System :: POSIX :: Linux',
300
          'Programming Language :: Python :: 3.9',
301
          'Topic :: System :: Networking',
302
      ])
303