-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetup.py
309 lines (254 loc) · 9.7 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
"""
setuptools setup script for pylass using CMake
This setup script will build pylass using CMake and install it in
site-packages:
python setup.py install
Requires CMake and a proper environment for the compiler.
"""
import os
import re
import subprocess
import sys
from distutils import ccompiler, log, sysconfig, util
from distutils.command.build import build as _build
from setuptools import Command, setup
from setuptools.command.install import install as _install
class build(_build):
"""
patched build command to add build_cmake as sub command
"""
sub_commands = _build.sub_commands + [
("build_cmake", lambda _: True),
]
def initialize_options(self):
_build.initialize_options(self)
def finalize_options(self):
_build.finalize_options(self)
self.build_lib = self.build_platlib # force it to use build_platlib
class install(_install):
"""
patched install command to allways run install_lib
"""
sub_commands = [
("install_lib", lambda _: True) if cmd == "install_lib" else (cmd, pred)
for cmd, pred in _install.sub_commands
]
class build_cmake(Command):
"""A custom command to run a CMake build."""
description = "run cmake build"
user_options = [
# The format is (long option, short option, description).
("build-lib=", "b", "directory for compiled extension modules"),
("build-temp=", "t", "directory for temporary files (build by-products)"),
(
"plat-name=",
"p",
"platform name to cross-compile for, if supported "
"(default: %s)" % util.get_platform(),
),
("debug", "g", "compile with debugging information"),
("force", "f", "forcibly build everything (ignore file timestamps)"),
("compiler=", "c", "specify the compiler type"),
]
boolean_options = ["debug", "force"]
help_options = [
("help-compiler", None, "list available compilers", ccompiler.show_compilers),
]
def initialize_options(self):
"""Set default values for options."""
# Each user option must be listed here with their default value.
self.build_lib = None
self.build_temp = None
self.plat_name = None
self.debug = None
self.force = 0
self.compiler = None
def finalize_options(self):
"""Post-process options."""
self.set_undefined_options(
"build",
("build_lib", "build_lib"),
("build_temp", "build_temp"),
("plat_name", "plat_name"),
("debug", "debug"),
("force", "force"),
("compiler", "compiler"),
)
if not self.compiler:
self.compiler = ccompiler.get_default_compiler()
def run(self):
env = self._get_env()
self._configure(env)
self._build(env)
self._copy()
def _configure(self, env):
generator = "NMake Makefiles" if sys.platform == "win32" else "Unix Makefiles"
if hasattr(sys, "gettotalrefcount"):
cmake_build_type = "Debug" # https://stackoverflow.com/a/647312
else:
cmake_build_type = "RelWithDebInfo" if self.debug else "Release"
print("cmake_build_type: {}".format(cmake_build_type))
python_version = ".".join(map(str, sys.version_info[:2]))
python_executable = sys.executable
python_library = get_python_library()
python_include_dir = sysconfig.get_python_inc()
command = [
"cmake",
"-G",
generator,
"-DBUILD_SHARED_LIBS=OFF",
"-DBUILD_TESTING=OFF",
"-DCMAKE_POSITION_INDEPENDENT_CODE=ON",
"-DCMAKE_BUILD_TYPE={}".format(cmake_build_type),
"-DLass_PYTHON_VERSION={}".format(python_version),
"-DPython_EXECUTABLE={}".format(fwdslash(python_executable)),
"-DPython_LIBRARY_RELEASE={}".format(fwdslash(python_library)),
"-DPython_LIBRARY_DEBUG={}".format(fwdslash(python_library)),
"-DPython_INCLUDE_DIR={}".format(fwdslash(python_include_dir)),
os.getcwd(),
]
self.mkpath(self.build_temp)
self._check_call(command, env=env, cwd=self.build_temp)
def _build(self, env):
command = ["cmake", "--build", os.curdir, "--target", "pylass"]
if self._cmake_version and self._cmake_version >= (3, 12):
command += ["--parallel"]
self._check_call(command, cwd=self.build_temp, env=env)
def _copy(self):
self.copy_tree(os.path.join(self.build_temp, "bin"), self.build_lib)
def _check_call(self, command, **kwargs):
self.announce("Running command: {}".format(command), level=log.INFO)
if not self.dry_run:
subprocess.check_call(command, **kwargs)
def _get_env(self):
compiler = ccompiler.new_compiler(
compiler=self.compiler, dry_run=self.dry_run, force=self.force
)
try:
compiler.initialize() # MSVCCompiler
except AttributeError:
pass
sysconfig.customize_compiler(compiler)
env = os.environ.copy()
try:
cc = compiler.compiler[0]
except AttributeError:
cc = compiler.cc # MSVCCompiler
print(cc)
env.setdefault("CC", cc)
try:
cxx = compiler.compiler_cxx[0]
except AttributeError:
cxx = compiler.cc # MSVCCompiler
print(cxx)
env.setdefault("CXX", cxx)
try:
env["PATH"] = compiler._paths
except AttributeError:
pass
if compiler.include_dirs:
env["INCLUDE"] = os.pathsep.join(compiler.include_dirs)
if compiler.library_dirs:
env["LIB"] = os.pathsep.join(compiler.library_dirs)
return env
@property
def _cmake_version(self):
try:
return self.__cmake_version
except AttributeError:
out = subprocess.check_output(
["cmake", "--version"], universal_newlines=True
)
match = re.match(r"^cmake version (\d+)\.(\d+)", out)
if match:
self.__cmake_version = int(match.group(1)), int(match.group(2))
else:
self.__cmake_version = None
return self.__cmake_version
def fwdslash(path):
"Convert backslashes to forward slashes"
return path.replace("\\", "/")
def get_python_library():
"return path to python link library (e.g. pythonXY.lib on Windows)"
prefix = get_exec_prefix()
if sys.platform == "win32":
template = "python{}{}"
# if self.debug:
# template = template + '_d'
template += ".lib"
pythonlib = template.format(sys.hexversion >> 24, (sys.hexversion >> 16) & 0xFF)
return os.path.join(prefix, "libs", pythonlib)
libpl = sysconfig.get_config_var("LIBPL")
ldlibrary = sysconfig.get_config_var("LDLIBRARY")
return os.path.join(libpl, ldlibrary)
def get_exec_prefix():
"""
Return the prefix that should house the link library.
Virtual environments usually don't include it, so you need to go back
to the original installation.
"""
# venv:
try:
return sys.base_exec_prefix
except AttributeError:
pass
# virtualenv:
try:
return sys.real_prefix # virtualenv telling original location
except AttributeError:
pass
return sys.exec_prefix
def get_version():
self_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(self_dir, "CMakeLists.txt")) as fp:
content = fp.read()
match = re.search(r"project\(Lass VERSION (\d+\.\d+\.\d+)\)", content)
assert match
version = match.group(1)
version_tag = "lass-{}".format(version)
try:
describe = subprocess.check_output(
["git", "describe", "--dirty=.dirty", "--tags", "--match", version_tag],
cwd=self_dir,
universal_newlines=True,
).strip()
except subprocess.CalledProcessError:
pass # release tag doesn't exist yet, it's a pre-release.
else:
assert describe == version_tag, (
"Post-release builds are not allowed. Set base_tag to {!r} and "
+ "increment project(Lass VERSION X.Y.Z) in CMakeLists.txt."
).format(version_tag)
return version
# It's not a release version, so we want to add a pre-release number to the semver.
# We can use describe to get an increasing number from a previous tag. To get a
# stable number we need to fix that base tag, which is obviously not the current
# version since that tag doesn't exist yet.
# NOTE: you can only update this base tag _at_the_same_time_ you update
# project(Lass VERSION ...) in CMakeLists. Otherwise, the prerelease numbers will
# not properly increase.
base_tag = "lass-1.10.0"
describe = subprocess.check_output(
["git", "describe", "--dirty=.dirty", "--tags", "--match", base_tag],
cwd=self_dir,
universal_newlines=True,
).strip()
assert describe.startswith(base_tag), "{!r} does not start with {!r}".format(
describe, base_tag
)
match = re.search(
r"{}-(\d+)-(g\w+(\.dirty)?)$".format(re.escape(base_tag)), describe
)
assert match, "unexpected describe format: {!r}".format(describe)
pre_release, rev = match.group(1), match.group(2)
return "{}.dev{}+{}".format(version, pre_release, rev)
setup(
name="pylass",
version=get_version(),
author="Cocamware",
author_email="[email protected]",
description="Python bindings to Lass",
url="https://lass.cocamware.com/",
cmdclass={"build": build, "build_cmake": build_cmake, "install": install,},
zip_safe=False,
)