Passed
Push — master ( 00c642...f9df13 )
by Vinicius
01:46 queued 13s
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
eloc 4
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 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 = 'flow_stats'
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 = ['of_core']
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
            check_call('yala *.py tests', shell=True)
136
            print('No linter error found.')
137
        except CalledProcessError:
138
            print('Linter check failed. Fix the error(s) above and try again.')
139
            sys.exit(-1)
140
141
142
class KytosInstall:
143
    """Common code for all install types."""
144
145
    @staticmethod
146
    def enable_core_napps():
147
        """Enable a NAPP by creating a symlink."""
148
        (ENABLED_PATH / NAPP_USERNAME).mkdir(parents=True, exist_ok=True)
149
        for napp in CORE_NAPPS:
150
            napp_path = Path('kytos', napp)
151
            src = ENABLED_PATH / napp_path
152
            dst = INSTALLED_PATH / napp_path
153
            symlink_if_different(src, dst)
154
155
    def __str__(self):
156
        return self.__class__.__name__
157
158
159
class InstallMode(install):
160
    """Create files in var/lib/kytos."""
161
162
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
163
164
    def run(self):
165
        """Direct users to use kytos-utils to install NApps."""
166
        print(self.description)
167
168
169
class EggInfo(egg_info):
170
    """Prepare files to be packed."""
171
172
    def run(self):
173
        """Build css."""
174
        self._install_deps_wheels()
175
        super().run()
176
177
    @staticmethod
178
    def _install_deps_wheels():
179
        """Python wheels are much faster (no compiling)."""
180
        print("Installing dependencies...")
181
        check_call(
182
            [
183
                sys.executable,
184
                "-m",
185
                "pip",
186
                "install",
187
                "-r",
188
                "requirements/run.txt",
189
            ]
190
        )
191
192
193
class DevelopMode(develop):
194
    """Recommended setup for kytos-napps developers.
195
196
    Instead of copying the files to the expected directories, a symlink is
197
    created on the system aiming the current source code.
198
    """
199
200
    description = 'Install NApps in development mode'
201
202
    def run(self):
203
        """Install the package in a developer mode."""
204
        super().run()
205
        if self.uninstall:
206
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
207
        else:
208
            self._create_folder_symlinks()
209
            # self._create_file_symlinks()
210
            KytosInstall.enable_core_napps()
211
212
    @staticmethod
213
    def _create_folder_symlinks():
214
        """Symlink to all Kytos NApps folders.
215
216
        ./napps/kytos/napp_name will generate a link in
217
        var/lib/kytos/napps/.installed/kytos/napp_name.
218
        """
219
        links = INSTALLED_PATH / NAPP_USERNAME
220
        links.mkdir(parents=True, exist_ok=True)
221
        code = CURRENT_DIR
222
        src = links / NAPP_NAME
223
        symlink_if_different(src, code)
224
225
        (ENABLED_PATH / NAPP_USERNAME).mkdir(parents=True, exist_ok=True)
226
        dst = ENABLED_PATH / Path(NAPP_USERNAME, NAPP_NAME)
227
        symlink_if_different(dst, src)
228
229
    @staticmethod
230
    def _create_file_symlinks():
231
        """Symlink to required files."""
232
        src = ENABLED_PATH / '__init__.py'
233
        dst = CURRENT_DIR / '__init__.py'
234
        symlink_if_different(src, dst)
235
236
237
def symlink_if_different(path, target):
238
    """Force symlink creation if it points anywhere else."""
239
    # print(f"symlinking {path} to target: {target}...", end=" ")
240
    if not path.exists():
241
        # print(f"path doesn't exist. linking...")
242
        path.symlink_to(target)
243
    elif not path.samefile(target):
244
        # print(f"path exists, but is different. removing and linking...")
245
        # Exists but points to a different file, so let's replace it
246
        path.unlink()
247
        path.symlink_to(target)
248
249
250
def read_version_from_json():
251
    """Read the NApp version from NApp kytos.json file."""
252
    file = Path('kytos.json')
253
    metadata = json.loads(file.read_text(encoding="utf8"))
254
    return metadata['version']
255
256
257
def read_requirements(path="requirements/run.txt"):
258
    """Read requirements file and return a list."""
259
    with open(path, "r", encoding="utf8") as file:
260
        return [
261
            line.strip()
262
            for line in file.readlines()
263
            if not line.startswith("#")
264
        ]
265
266
267
setup(name=f'{NAPP_USERNAME}_{NAPP_NAME}',
268
      version=read_version_from_json(),
269
      description='Store flow information and show statistics about them.',
270
      url='http://github.com/kytos-ng/flow_stats',
271
      author='FIU/AmLight team',
272
      author_email='[email protected]',
273
      license='MIT',
274
      install_requires=read_requirements() + ["setuptools >= 59.6.0"],
275
      packages=[],
276
      extras_require={
277
          'dev': [
278
              'pytest==7.0.0',
279
              'pytest-cov==3.0.0',
280
              'pip-tools',
281
              'yala',
282
              'tox',
283
          ],
284
      },
285
      cmdclass={
286
          'clean': Cleaner,
287
          'coverage': TestCoverage,
288
          'develop': DevelopMode,
289
          'install': InstallMode,
290
          'lint': Linter,
291
          'egg_info': EggInfo,
292
          'test': Test,
293
      },
294
      zip_safe=False,
295
      classifiers=[
296
          'License :: OSI Approved :: MIT License',
297
          'Operating System :: POSIX :: Linux',
298
          'Programming Language :: Python :: 3.9',
299
          'Topic :: System :: Networking',
300
      ])
301