Completed
Pull Request — master (#62)
by Gleyberson
01:25
created

build.setup   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 108
dl 0
loc 243
rs 10
c 0
b 0
f 0
wmc 15
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, shell=True)
90
91
92
class CITest(SimpleCommand):
93
    """Run all CI tests."""
94
95
    description = 'run all CI tests: unit and doc tests, linter'
96
97
    def run(self):
98
        """Run unit tests with coverage, doc tests and linter."""
99
        cmds = ['python3.6 setup.py ' + cmd
100
                for cmd in ('coverage', 'lint')]
101
        cmd = ' && '.join(cmds)
102
        check_call(cmd, shell=True)
103
104
105
# class KytosInstall:
106
#     """Common code for all install types."""
107
#
108
#     @staticmethod
109
#     def enable_core_napps():
110
#         """Enable a NAPP by creating a symlink."""
111
#         (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
112
#         for napp in CORE_NAPPS:
113
#             napp_path = Path('kytos', napp)
114
#             src = ENABLED_PATH / napp_path
115
#             dst = INSTALLED_PATH / napp_path
116
#             src.symlink_to(dst)
117
118
119
class InstallMode(install):
120
    """Create files in var/lib/kytos."""
121
122
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
123
124
    def run(self):
125
        """Create of_core as default napps enabled."""
126
        print(self.description)
127
128
129
# class EggInfo(egg_info):
130
#     """Prepare files to be packed."""
131
#
132
#     def run(self):
133
#         """Build css."""
134
#         self._install_deps_wheels()
135
#         super().run()
136
#
137
#     @staticmethod
138
#     def _install_deps_wheels():
139
#         """Python wheels are much faster (no compiling)."""
140
#         print('Installing dependencies...')
141
#         check_call([sys.executable, '-m', 'pip', 'install', '-r',
142
#                     'requirements/run.in'])
143
144
145
class DevelopMode(develop):
146
    """Recommended setup for kytos-napps developers.
147
148
    Instead of copying the files to the expected directories, a symlink is
149
    created on the system aiming the current source code.
150
    """
151
152
    description = 'install NApps in development mode'
153
154
    def run(self):
155
        """Install the package in a developer mode."""
156
        super().run()
157
        if self.uninstall:
158
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
159
        else:
160
            self._create_folder_symlinks()
161
            # self._create_file_symlinks()
162
            # KytosInstall.enable_core_napps()
163
164
    @staticmethod
165
    def _create_folder_symlinks():
166
        """Symlink to all Kytos NApps folders.
167
168
        ./napps/kytos/napp_name will generate a link in
169
        var/lib/kytos/napps/.installed/kytos/napp_name.
170
        """
171
        links = INSTALLED_PATH / 'kytos'
172
        links.mkdir(parents=True, exist_ok=True)
173
        code = CURRENT_DIR
174
        src = links / 'of_core'
175
        symlink_if_different(src, code)
176
177
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
178
        dst = ENABLED_PATH / Path('kytos', 'of_core')
179
        symlink_if_different(dst, src)
180
181
    # @staticmethod
182
    # def _create_file_symlinks():
183
    #     """Symlink to required files."""
184
    #     src = ENABLED_PATH / '__init__.py'
185
    #     dst = CURRENT_DIR / 'napps' / '__init__.py'
186
    #     symlink_if_different(src, dst)
187
188
189
def symlink_if_different(path, target):
190
    """Force symlink creation if it points anywhere else."""
191
    # print(f"symlinking {path} to target: {target}...", end=" ")
192
    if not path.exists():
193
        # print(f"path doesn't exist. linking...")
194
        path.symlink_to(target)
195
    elif not path.samefile(target):
196
        # print(f"path exists, but is different. removing and linking...")
197
        # Exists but points to a different file, so let's replace it
198
        path.unlink()
199
        path.symlink_to(target)
200
201
202
def read_version_from_json():
203
    """Read the NApp version from NApp kytos.json file."""
204
    file = Path('kytos.json')
205
    metadata = json.loads(file.read_text())
206
    return metadata['version']
207
208
209
setup(name='kytos_of_core',
210
      version=read_version_from_json(),
211
      description='Core NApps developed by Kytos Team',
212
      url='http://github.com/kytos/of_core',
213
      author='Kytos Team',
214
      author_email='[email protected]',
215
      license='MIT',
216
      install_requires=['setuptools >= 36.0.1'],
217
      extras_require={
218
          'dev': [
219
              'coverage',
220
              'pip-tools',
221
              'yala',
222
              'tox',
223
          ],
224
      },
225
      cmdclass={
226
          'clean': Cleaner,
227
          'ci': CITest,
228
          'coverage': TestCoverage,
229
230
          'develop': DevelopMode,
231
          'install': InstallMode,
232
          'lint': Linter,
233
          # 'egg_info': EggInfo,
234
      },
235
      zip_safe=False,
236
      classifiers=[
237
          'License :: OSI Approved :: MIT License',
238
          'Operating System :: POSIX :: Linux',
239
          'Programming Language :: Python :: 3.6',
240
          'Topic :: System :: Networking',
241
      ])
242