-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.py
423 lines (349 loc) · 13.1 KB
/
setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"""Setup that is responsible for building the C++ python extensions.
"""
import os
import platform
import subprocess
import shutil
import glob
import signal
from typing import Callable
from setuptools import setup, find_packages, Extension, Command
from setuptools.command.test import test
import pybind11
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
def get_build_dir() -> str:
"""Get the build directory that will store all C/C++ extension by-products.
Returns:
str: build directory path.
"""
return os.path.join(ROOT_DIR, "build")
# pylint: disable=no-self-use
# pylint: disable=unnecessary-pass
# pylint: disable=attribute-defined-outside-init
class CleanProject(Command):
"""Clean the project directory of temporary files involved with
building the C extension and python module.
This will also uninstall the development version of musher.
"""
user_options = []
def initialize_options(self):
"""Initialize user options
"""
pass
def finalize_options(self):
"""Finalize user options
"""
pass
def run(self):
"""Run the clean
"""
cleanup_list = [
# Cmake
os.path.join(ROOT_DIR, "build"),
# Python
os.path.join(ROOT_DIR, "dist"),
os.path.join(ROOT_DIR, "musher.egg-info"),
os.path.join(ROOT_DIR, ".eggs"),
os.path.join(ROOT_DIR, ".pytest_cache"),
os.path.join(ROOT_DIR, ".tox"),
*glob.glob(os.path.join(ROOT_DIR, "musher", "*.so")),
# Doxygen
os.path.join(ROOT_DIR, "docs", "html"),
os.path.join(ROOT_DIR, "docs", "latex"),
os.path.join(ROOT_DIR, "docs", "xml"),
# Sphinx
os.path.join(ROOT_DIR, "docs", "build")
]
for item in cleanup_list:
try: # If item is a dir then remove it
shutil.rmtree(item)
print("deleted {}".format(item))
except OSError:
try: # If item is a file then remove it
os.remove(item)
print("deleted {}".format(item))
except OSError:
pass
print(u'\u2713', "cleaning done")
class PublishDocs(Command):
"""Publish the generated documentation to Github pages
You must install the python module and generate the docs BEFORE running this command.
1. pip install -e .
2. python setup.py cmake --docs
Example usage:
python setup.py publish_docs -m "Added docs for new function"
Helpful reads:
https://discourse.gohugo.io/t/simple-deployment-to-gh-pages/5003
"""
user_options = [
('message=', 'm', "Commit message when publishing docs."),
]
def initialize_options(self):
"""Initialize user options
"""
self.message = "Updated docs"
def finalize_options(self):
"""Finalize user options
"""
pass
def copytree(self, src: str, dst: str, ignore: Callable = None):
"""copytree for older python versions that don't have the latest
version of shutil.copytree(dirs_exist_ok=True)
"""
if os.path.isdir(src):
if not os.path.isdir(dst):
os.makedirs(dst)
files = os.listdir(src)
if ignore is not None:
ignored = ignore(src, files)
else:
ignored = set()
for _file in files:
if _file not in ignored:
self.copytree(os.path.join(src, _file),
os.path.join(dst, _file),
ignore)
else:
shutil.copyfile(src, dst)
def run(self):
"""Publish to github pages
"""
sphinx_build_dir = os.path.join(ROOT_DIR, 'build', 'docs', 'sphinx')
temp_gh_pages_dir = os.path.join(ROOT_DIR, 'temp_gh_pages')
git_worktree = os.path.join(
ROOT_DIR, '.git', 'worktrees', "temp_gh_pages")
nojekyll = os.path.join(temp_gh_pages_dir, ".nojekyll")
# Cleanup to ensure we are starting fresh.
try:
shutil.rmtree(temp_gh_pages_dir)
except OSError:
pass
subprocess.run(['git', 'worktree', 'prune'], cwd=ROOT_DIR, check=True)
try:
shutil.rmtree(git_worktree)
except OSError:
pass
print("\nAdding gh-pages branch as a worktree...")
subprocess.run(['git', 'worktree', 'add', '-B', 'gh-pages',
temp_gh_pages_dir, 'origin/gh-pages'], cwd=ROOT_DIR, check=True)
# Pull to ensure we are up to date.
subprocess.run(['git', 'pull'], cwd=temp_gh_pages_dir, check=True)
# Copy newly generated docs
print("\nCopying newly generated docs to git branch...")
try:
shutil.copytree(sphinx_build_dir, temp_gh_pages_dir,
dirs_exist_ok=True)
except TypeError:
# Not using python3.8+
self.copytree(sphinx_build_dir, temp_gh_pages_dir)
# Add a .nojekyll files to ensure gh-pages uses index.html as the root of the site.
open(nojekyll, 'w').close()
subprocess.run(['git', 'add', '--all'],
cwd=temp_gh_pages_dir, check=True)
try:
print("\nCommitting changes...")
subprocess.run(['git', 'commit', '-m', self.message],
cwd=temp_gh_pages_dir, check=True)
print("\nPushing to github...")
subprocess.run(['git', 'push', 'origin', 'gh-pages'],
cwd=temp_gh_pages_dir, check=True)
except subprocess.CalledProcessError as err:
if err.returncode != 1:
# returncode == 1 means the branch is up to date.
raise err
shutil.rmtree(temp_gh_pages_dir)
subprocess.run(['git', 'worktree', 'prune'], cwd=ROOT_DIR, check=True)
class CMakeBuild(Command):
"""
Debug (with tests): python setup.py cmake --debug
Release (no tests): python setup.py cmake
Generate docs: python setup.py cmake --docs
"""
description = 'Build the C++ code with various options.'
user_options = [
('debug', 'd', "Compile in debug mode."),
('docs', 'r', "Generate documenation for C++ and Python."),
]
def initialize_options(self):
"""Initialize user options
"""
self.debug = False
self.docs = False
def finalize_options(self):
"""Finalize user options
"""
pass
def run(self):
"""Build the C++ code.
Raises:
RuntimeError: Error if Cmake is not installed.
"""
try:
subprocess.check_output(["cmake", "--version"])
except OSError as err:
raise RuntimeError(
"CMake must be installed to build musher") from err
build_dir = get_build_dir()
cmake_args = []
if self.debug:
cmake_args += ["-DCMAKE_BUILD_TYPE=Debug", "-DENABLE_TESTS=On"]
else:
cmake_args += ["-DCMAKE_BUILD_TYPE=Release"]
if self.docs:
cmake_args += ["-DGENERATE_DOCS=On"]
else:
cmake_args += ["-DGENERATE_DOCS=Off"]
if not os.path.exists(build_dir):
os.makedirs(build_dir)
subprocess.run(['cmake', ROOT_DIR] + cmake_args,
cwd=build_dir,
check=True)
subprocess.run(['cmake', '--build', '.'],
cwd=build_dir,
check=True)
class CTest(test):
"""Run tests if compiled (only through DEBUG)
python setup.py cmake --debug
python setup.py ctest
"""
def run(self):
build_dir = get_build_dir()
if platform.system().lower() == "windows":
build_dir_win_debug = os.path.join(build_dir, "Debug")
if os.path.isdir(build_dir_win_debug):
build_dir = build_dir_win_debug
try:
result = subprocess.run(['ctest', "--output-on-failure"],
cwd=build_dir,
check=True,
stderr=subprocess.PIPE)
except FileNotFoundError:
# cwd was not found.
print("HINT: Did you compile the code first? "
"(python setup.py cmake --debug)")
raise
if result.stderr:
print(result.stderr.decode("utf-8"))
print("HINT: Did you compile the code in debug mode first? "
"(python setup.py cmake --debug)")
if result.returncode == -signal.SIGSEGV:
print("C++ Seg fault.")
class GTest(test):
r"""Run tests if compiled (only through DEBUG)
python setup.py cmake --debug
python setup.py gtest
example using filters:
python setup.py gtest --g=--gtest_filter=HPCP.\*
Attributes:
gtest_options (str): Any gtest options that should be used when running the tests.
"""
description = 'Run google tests for c++ library'
user_options = [
('gtest-options=', 'g',
'Any google test args that need to be passed through when building tests.'),
]
def initialize_options(self):
self.gtest_options = ""
def finalize_options(self):
pass
def run(self):
bin_dir = os.path.join(get_build_dir(), "bin")
if platform.system().lower() == "windows":
bin_dir_win_debug = os.path.join(bin_dir, "Debug")
if os.path.isdir(bin_dir_win_debug):
bin_dir = bin_dir_win_debug
try:
result = subprocess.run(['./musher-core-test', self.gtest_options],
cwd=bin_dir,
check=True)
except FileNotFoundError:
# Test executable not found / cwd not found.
print("HINT: Did you compile the code in debug mode first? "
"(python setup.py cmake --debug)")
raise
if result.returncode == -11:
print("C++ Seg fault.")
def extra_compile_args() -> list:
"""Platform dependent extras
Returns:
list: Extra compile arguments
"""
args = []
if platform.system() == 'Darwin':
# Something with OS X Mojave causes libstd not to be found
args += ['-mmacosx-version-min=10.12']
if os.name != 'nt':
if platform.machine() == 'i686':
# This makes GCC generate modern SSE2 instructions
# that give the exact IEEE 754 floating-point semantics.
# Basically ensures that calculations using produce the
# same results on all 32bit linux architecture.
args += ['-msse2']
args += ['-std=c++14']
return args
def extra_link_args() -> list:
"""Platform dependent extras
Returns:
list: Extra link arguments
"""
args = []
if platform.system() == 'Darwin':
# Something with OS X Mojave causes libstd not to be found
args += ['-stdlib=libc++', '-mmacosx-version-min=10.12']
return args
setup(
ext_modules=[
Extension(
'musher.musher_python', # Destination of .so
include_dirs=[
# https://caligari.dartmouth.edu/doc/ibmcxx/en_US/doc/complink/tasks/tuinclud.htm
# Allows for root level imports within C++
ROOT_DIR,
# 3rd party libraries
"src/third-party",
pybind11.get_include()
],
sources=[
'src/python/module.cpp',
'src/python/wrapper.cpp',
'src/python/utils.cpp',
'src/core/audio_decoders.cpp',
'src/core/utils.cpp',
'src/core/key.cpp',
'src/core/hpcp.cpp',
'src/core/framecutter.cpp',
'src/core/windowing.cpp',
'src/core/peak_detect.cpp',
'src/core/spectral_peaks.cpp',
'src/core/spectrum.cpp',
'src/core/mono_mixer.cpp'
],
depends=[
'src/python/module.h',
'src/python/wrapper.h',
'src/python/utils.h',
'src/core/audio_decoders.h',
'src/core/utils.h',
'src/core/key.h'
'src/core/hpcp.h',
'src/core/framecutter.h',
'src/core/windowing.h',
'src/core/peak_detect.h',
'src/core/spectral_peaks.h',
'src/core/spectrum.h',
'src/core/mono_mixer.h'
],
extra_compile_args=extra_compile_args(),
extra_link_args=extra_link_args(),
)
],
cmdclass={
"cmake": CMakeBuild,
"ctest": CTest,
"gtest": GTest,
"clean": CleanProject,
"publish_docs": PublishDocs
},
setup_requires=['wheel', 'cython', 'setuptools_scm>=4.1.2', 'pybind11>=2.6.0', 'numpy>=1.18.5'],
use_scm_version=True
)