Debian Codegraph @

setup.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 from setuptools import setup, find_packages
2 from setuptools.extension import Extension
3 from os import path, environ
4 import sys
5 import sysconfig
6 from pathlib import Path
7
8 # needed for isolated environment
9 sys.path.insert(0, str(Path(__file__).parent.resolve()))
10 from scalene.scalene_config import scalene_version
11
12 sys.path.pop(0)
13
14
15 if sys.platform == "darwin":
16 import sysconfig
17
18 mdt = "MACOSX_DEPLOYMENT_TARGET"
19 target = environ[mdt] if mdt in environ else sysconfig.get_config_var(mdt)
20 # target >= 10.9 is required for gcc/clang to find libstdc++ headers
21 if [int(n) for n in target.split(".")] < [10, 9]:
22 from os import execve
23
24 newenv = environ.copy()
25 newenv[mdt] = "10.9"
26 execve(sys.executable, [sys.executable] + sys.argv, newenv)
27
28
29 def compiler_archs(compiler: str):
30 """Discovers what platforms the given compiler supports; intended for MacOS use"""
31 import tempfile
32 import subprocess
33
34 print(f"Compiler: {compiler}")
35 arch_flags = []
36
37 # see also the architectures tested for in .github/workflows/build-and-upload.yml
38 for arch in ["x86_64", "arm64", "arm64e"]:
39 with tempfile.TemporaryDirectory() as tmpdir:
40 cpp = Path(tmpdir) / "test.cxx"
41 cpp.write_text("int main() {return 0;}\n")
42 out = Path(tmpdir) / "a.out"
43 p = subprocess.run(
44 [compiler, "-arch", arch, str(cpp), "-o", str(out)], capture_output=True
45 )
46 if p.returncode == 0:
47 arch_flags += ["-arch", arch]
48
49 print(f"Discovered {compiler} arch flags: {arch_flags}")
50 return arch_flags
51
52
53 def extra_compile_args():
54 """Returns extra compiler args for platform."""
55 if sys.platform == "win32":
56 return ["/std:c++14"] # for Visual Studio C++
57
58 return ["-std=c++14"]
59
60
61 def make_command():
62 # return 'nmake' if sys.platform == 'win32' else 'make' # 'nmake' isn't found on github actions' VM
63 return "make"
64
65
66 def dll_suffix():
67 """Returns the file suffix ("extension") of a DLL"""
68 if sys.platform == "win32":
69 return ".dll"
70 if sys.platform == "darwin":
71 return ".dylib"
72 return ".so"
73
74
75 def read_file(name):
76 """Returns a file's contents"""
77 with open(path.join(path.dirname(__file__), name), encoding="utf-8") as f:
78 return f.read()
79
80
81 import setuptools.command.egg_info
82
83
84 class EggInfoCommand(setuptools.command.egg_info.egg_info):
85 """Custom command to download vendor libs before creating the egg_info."""
86
87 def run(self):
88 if sys.platform != "win32":
•89 # self.spawn([make_command(), "vendor-deps"])
90 pass
91 super().run()
92
93
94 # Force building platform-specific wheel to avoid the Windows wheel
95 # (which doesn't include libscalene, and thus would be considered "pure")
96 # being used for other platforms.
97 try:
98 from wheel.bdist_wheel import bdist_wheel
99
100 class BdistWheelCommand(bdist_wheel):
101 def finalize_options(self):
102 super().finalize_options()
103 self.root_is_pure = False
104
105 except (ImportError, ModuleNotFoundError):
106 # Disable wheel if `wheel` not installed.
107 print(
108 "If this installation does not work, run `pip install setuptools wheel` and try again."
109 )
110 BdistWheelCommand = None
111
112 import setuptools.command.build_ext
113
114
115 class BuildExtCommand(setuptools.command.build_ext.build_ext):
116 """Custom command that runs 'make' to generate libscalene, and also does MacOS
117 supported --arch flag discovery."""
118
119 def build_extensions(self):
120 arch_flags = []
121 if sys.platform == "darwin":
122 # The only sure way to tell which compiler build_ext is going to use
123 # seems to be to customize a build_ext and look at its internal flags :(
124 # Also, note that self.plat_name here isn't "...-universal2" even if that
125 # is what we're building; that's only in bdist_wheel.plat_name.
126 arch_flags += compiler_archs(self.compiler.compiler_cxx[0])
127 for ext in self.extensions:
128 # While the flags _could_ be different between the programs used for
129 # C and C++ compilation and linking, we have no way to adapt them here,
130 # so it seems best to just use them and let it error out if not recognized.
131 ext.extra_compile_args += arch_flags
132 ext.extra_link_args += arch_flags
133
134 super().build_extensions()
135
136 # No build of DLL for Windows currently.
137 if sys.platform != "win32":
138 self.build_libscalene(arch_flags) # XXX should we pass compiler_cxx here?
139
140 def build_libscalene(self, arch_flags):
141 scalene_temp = path.join(self.build_temp, "scalene")
142 scalene_lib = path.join(self.build_lib, "scalene")
143 libscalene = "libscalene" + dll_suffix()
144 self.mkpath(scalene_temp)
145 self.mkpath(scalene_lib)
146 self.spawn(
147 [make_command(), "OUTDIR=" + scalene_temp, "ARCH=" + " ".join(arch_flags)]
148 )
149 self.copy_file(
150 path.join(scalene_temp, libscalene), path.join(scalene_lib, libscalene)
151 )
152
153 def copy_extensions_to_source(self):
154 # self.inplace is temporarily overridden while running build_extensions,
155 # so inplace copying (for pip install -e, setup.py develop) must be done here.
156
157 super().copy_extensions_to_source()
158
159 if sys.platform != "win32":
160 scalene_lib = path.join(self.build_lib, "scalene")
161 inplace_dir = self.get_finalized_command("build_py").get_package_dir(
162 "scalene"
163 )
164 libscalene = "libscalene" + dll_suffix()
165 self.copy_file(
166 path.join(scalene_lib, libscalene), path.join(inplace_dir, libscalene)
167 )
168
169
170 get_line_atomic = Extension(
171 "scalene.get_line_atomic",
172 include_dirs=[".", "vendor/Heap-Layers", "vendor/Heap-Layers/utility"],
173 sources=["src/source/get_line_atomic.cpp"],
174 extra_compile_args=extra_compile_args(),
175 py_limited_api=True, # for binary compatibility
176 language="c++",
177 )
178
179 pywhere = Extension(
180 "scalene.pywhere",
181 include_dirs=[".", "src", "src/include"],
182 depends=["src/include/traceconfig.hpp"],
183 sources=["src/source/pywhere.cpp", "src/source/traceconfig.cpp"],
184 extra_compile_args=extra_compile_args(),
185 py_limited_api=False,
186 language="c++",
187 )
188
189 # If we're testing packaging, build using a ".devN" suffix in the version number,
190 # so that we can upload new files (as testpypi/pypi don't allow re-uploading files with
191 # the same name as previously uploaded).
192 # Numbering scheme: https://www.python.org/dev/peps/pep-0440
193 dev_build = (".dev" + environ["DEV_BUILD"]) if "DEV_BUILD" in environ else ""
194
195
196 def bdist_wheel_options():
197 if sys.platform == "darwin":
198 # Build universal wheels on MacOS.
199 # ---
200 # On MacOS >= 11, all builds are compatible within a major MacOS version, so Python "floors"
201 # all minor versions to 0, leading to tags like like "macosx_11_0_universal2". If you use
202 # the actual (non-0) minor name in the build platform, it isn't recognized.
203 # ---
204 # It would be nice to check whether we're actually building multi-architecture,
205 # but that depends on the platforms supported by the compiler build_ext wants to use,
206 # which is hard to obtain (see BuildExtCommand above).
207 import platform
208
209 v = platform.mac_ver()[0]
210 major = int(v.split(".")[0])
211 if major >= 11:
212 v = f"{major}.0"
213 return {"plat_name": f"macosx-{v}-universal2"}
214
215 return {}
216
217
218 setup(
219 version=scalene_version + dev_build,
220 packages=find_packages(),
221 cmdclass={
222 "bdist_wheel": BdistWheelCommand,
223 "egg_info": EggInfoCommand,
224 "build_ext": BuildExtCommand,
225 },
226 ext_modules=([get_line_atomic, pywhere] if sys.platform != "win32" else []),
227 include_package_data=True,
228 options={"bdist_wheel": bdist_wheel_options()},
229 )