Passed
Push — master ( 88b074...8301e9 )
by Humberto
01:23 queued 11s
created

build.setup.symlink_if_different()   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nop 2
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 12
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 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
if 'VIRTUAL_ENV' in os.environ:
24
    BASE_ENV = Path(os.environ['VIRTUAL_ENV'])
25
else:
26
    BASE_ENV = Path('/')
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
    def initialize_options(self):
52
        """Set default values for options."""
53
54
    def finalize_options(self):
55
        """Post-process options."""
56
57
58
class Cleaner(SimpleCommand):
59
    """Custom clean command to tidy up the project root."""
60
61
    description = 'clean build, dist, pyc and egg from package and docs'
62
63
    def run(self):
64
        """Clean build, dist, pyc and egg from package and docs."""
65
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
66
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
67
        call('make -C docs/ clean', shell=True)
68
69
70
class TestCoverage(SimpleCommand):
71
    """Display test coverage."""
72
73
    description = 'run unit tests and display code coverage'
74
75
    def run(self):
76
        """Run unittest quietly and display coverage report."""
77
        cmd = 'coverage3 run -m unittest && coverage3 report'
78
        call(cmd, shell=True)
79
80
81
class Linter(SimpleCommand):
82
    """Code linters."""
83
84
    description = 'lint Python source code'
85
86
    def run(self):
87
        """Run yala."""
88
        print('Yala is running. It may take several seconds...')
89
        check_call('yala *.py',
90
                   shell=True)
91
92
93
class CITest(SimpleCommand):
94
    """Run all CI tests."""
95
96
    description = 'run all CI tests: unit and doc tests, linter'
97
98
    def run(self):
99
        """Run unit tests with coverage, doc tests and linter."""
100
        cmds = ['python3.6 setup.py ' + cmd
101
                for cmd in ('coverage', 'lint')]
102
        cmd = ' && '.join(cmds)
103
        check_call(cmd, shell=True)
104
105
106
# class KytosInstall:
107
#     """Common code for all install types."""
108
#
109
#     @staticmethod
110
#     def enable_core_napps():
111
#         """Enable a NAPP by creating a symlink."""
112
#         (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
113
#         for napp in CORE_NAPPS:
114
#             napp_path = Path('kytos', napp)
115
#             src = ENABLED_PATH / napp_path
116
#             dst = INSTALLED_PATH / napp_path
117
#             src.symlink_to(dst)
118
119
120
class InstallMode(install):
121
    """Create files in var/lib/kytos."""
122
123
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
124
125
    def run(self):
126
        """Create of_stats as default napps enabled."""
127
        print(self.description)
128
129
130
# class EggInfo(egg_info):
131
#     """Prepare files to be packed."""
132
#
133
#     def run(self):
134
#         """Build css."""
135
#         self._install_deps_wheels()
136
#         super().run()
137
#
138
#     @staticmethod
139
#     def _install_deps_wheels():
140
#         """Python wheels are much faster (no compiling)."""
141
#         print('Installing dependencies...')
142
#         check_call([sys.executable, '-m', 'pip', 'install', '-r',
143
#                     'requirements/run.in'])
144
145
146
class DevelopMode(develop):
147
    """Recommended setup for kytos-napps developers.
148
149
    Instead of copying the files to the expected directories, a symlink is
150
    created on the system aiming the current source code.
151
    """
152
153
    description = 'install NApps in development mode'
154
155
    def run(self):
156
        """Install the package in a developer mode."""
157
        super().run()
158
        if self.uninstall:
159
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
160
        else:
161
            self._create_folder_symlinks()
162
            # self._create_file_symlinks()
163
            # KytosInstall.enable_core_napps()
164
165
    @staticmethod
166
    def _create_folder_symlinks():
167
        """Symlink to all Kytos NApps folders.
168
169
        ./napps/kytos/napp_name will generate a link in
170
        var/lib/kytos/napps/.installed/kytos/napp_name.
171
        """
172
        links = INSTALLED_PATH / 'kytos'
173
        links.mkdir(parents=True, exist_ok=True)
174
        code = CURRENT_DIR
175
        src = links / 'of_stats'
176
        symlink_if_different(src, code)
177
178
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
179
        dst = ENABLED_PATH / Path('kytos', 'of_stats')
180
        symlink_if_different(dst, src)
181
182
    # @staticmethod
183
    # def _create_file_symlinks():
184
    #     """Symlink to required files."""
185
    #     src = ENABLED_PATH / '__init__.py'
186
    #     dst = CURRENT_DIR / 'napps' / '__init__.py'
187
    #     symlink_if_different(src, dst)
188
189
190
def symlink_if_different(path, target):
191
    """Force symlink creation if it points anywhere else."""
192
    # print(f"symlinking {path} to target: {target}...", end=" ")
193
    if not path.exists():
194
        # print(f"path doesn't exist. linking...")
195
        path.symlink_to(target)
196
    elif not path.samefile(target):
197
        # print(f"path exists, but is different. removing and linking...")
198
        # Exists but points to a different file, so let's replace it
199
        path.unlink()
200
        path.symlink_to(target)
201
202
203
def read_version_from_json():
204
    """Read the NApp version from NApp kytos.json file."""
205
    file = Path('kytos.json')
206
    metadata = json.loads(file.read_text())
207
    return metadata['version']
208
209
210
setup(name='kytos_of_stats',
211
      version=read_version_from_json(),
212
      description='Core NApps developed by Kytos Team',
213
      url='http://github.com/kytos/of_stats',
214
      author='Kytos Team',
215
      author_email='[email protected]',
216
      license='MIT',
217
      install_requires=['setuptools >= 36.0.1'],
218
      extras_require={
219
          'dev': [
220
              'coverage',
221
              'pip-tools',
222
              'yala',
223
              'tox',
224
          ],
225
      },
226
      cmdclass={
227
          'clean': Cleaner,
228
          'ci': CITest,
229
          'coverage': TestCoverage,
230
231
          'develop': DevelopMode,
232
          'install': InstallMode,
233
          'lint': Linter,
234
          # 'egg_info': EggInfo,
235
      },
236
      zip_safe=False,
237
      classifiers=[
238
          'License :: OSI Approved :: MIT License',
239
          'Operating System :: POSIX :: Linux',
240
          'Programming Language :: Python :: 3.6',
241
          'Topic :: System :: Networking',
242
      ])
243