Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

build_ext.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import os
  2. import sys
  3. import itertools
  4. import imp
  5. from distutils.command.build_ext import build_ext as _du_build_ext
  6. from distutils.file_util import copy_file
  7. from distutils.ccompiler import new_compiler
  8. from distutils.sysconfig import customize_compiler, get_config_var
  9. from distutils.errors import DistutilsError
  10. from distutils import log
  11. from setuptools.extension import Library
  12. from setuptools.extern import six
  13. try:
  14. # Attempt to use Cython for building extensions, if available
  15. from Cython.Distutils.build_ext import build_ext as _build_ext
  16. # Additionally, assert that the compiler module will load
  17. # also. Ref #1229.
  18. __import__('Cython.Compiler.Main')
  19. except ImportError:
  20. _build_ext = _du_build_ext
  21. # make sure _config_vars is initialized
  22. get_config_var("LDSHARED")
  23. from distutils.sysconfig import _config_vars as _CONFIG_VARS
  24. def _customize_compiler_for_shlib(compiler):
  25. if sys.platform == "darwin":
  26. # building .dylib requires additional compiler flags on OSX; here we
  27. # temporarily substitute the pyconfig.h variables so that distutils'
  28. # 'customize_compiler' uses them before we build the shared libraries.
  29. tmp = _CONFIG_VARS.copy()
  30. try:
  31. # XXX Help! I don't have any idea whether these are right...
  32. _CONFIG_VARS['LDSHARED'] = (
  33. "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup")
  34. _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
  35. _CONFIG_VARS['SO'] = ".dylib"
  36. customize_compiler(compiler)
  37. finally:
  38. _CONFIG_VARS.clear()
  39. _CONFIG_VARS.update(tmp)
  40. else:
  41. customize_compiler(compiler)
  42. have_rtld = False
  43. use_stubs = False
  44. libtype = 'shared'
  45. if sys.platform == "darwin":
  46. use_stubs = True
  47. elif os.name != 'nt':
  48. try:
  49. import dl
  50. use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
  51. except ImportError:
  52. pass
  53. if_dl = lambda s: s if have_rtld else ''
  54. def get_abi3_suffix():
  55. """Return the file extension for an abi3-compliant Extension()"""
  56. for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):
  57. if '.abi3' in suffix: # Unix
  58. return suffix
  59. elif suffix == '.pyd': # Windows
  60. return suffix
  61. class build_ext(_build_ext):
  62. def run(self):
  63. """Build extensions in build directory, then copy if --inplace"""
  64. old_inplace, self.inplace = self.inplace, 0
  65. _build_ext.run(self)
  66. self.inplace = old_inplace
  67. if old_inplace:
  68. self.copy_extensions_to_source()
  69. def copy_extensions_to_source(self):
  70. build_py = self.get_finalized_command('build_py')
  71. for ext in self.extensions:
  72. fullname = self.get_ext_fullname(ext.name)
  73. filename = self.get_ext_filename(fullname)
  74. modpath = fullname.split('.')
  75. package = '.'.join(modpath[:-1])
  76. package_dir = build_py.get_package_dir(package)
  77. dest_filename = os.path.join(package_dir,
  78. os.path.basename(filename))
  79. src_filename = os.path.join(self.build_lib, filename)
  80. # Always copy, even if source is older than destination, to ensure
  81. # that the right extensions for the current Python/platform are
  82. # used.
  83. copy_file(
  84. src_filename, dest_filename, verbose=self.verbose,
  85. dry_run=self.dry_run
  86. )
  87. if ext._needs_stub:
  88. self.write_stub(package_dir or os.curdir, ext, True)
  89. def get_ext_filename(self, fullname):
  90. filename = _build_ext.get_ext_filename(self, fullname)
  91. if fullname in self.ext_map:
  92. ext = self.ext_map[fullname]
  93. use_abi3 = (
  94. six.PY3
  95. and getattr(ext, 'py_limited_api')
  96. and get_abi3_suffix()
  97. )
  98. if use_abi3:
  99. so_ext = get_config_var('EXT_SUFFIX')
  100. filename = filename[:-len(so_ext)]
  101. filename = filename + get_abi3_suffix()
  102. if isinstance(ext, Library):
  103. fn, ext = os.path.splitext(filename)
  104. return self.shlib_compiler.library_filename(fn, libtype)
  105. elif use_stubs and ext._links_to_dynamic:
  106. d, fn = os.path.split(filename)
  107. return os.path.join(d, 'dl-' + fn)
  108. return filename
  109. def initialize_options(self):
  110. _build_ext.initialize_options(self)
  111. self.shlib_compiler = None
  112. self.shlibs = []
  113. self.ext_map = {}
  114. def finalize_options(self):
  115. _build_ext.finalize_options(self)
  116. self.extensions = self.extensions or []
  117. self.check_extensions_list(self.extensions)
  118. self.shlibs = [ext for ext in self.extensions
  119. if isinstance(ext, Library)]
  120. if self.shlibs:
  121. self.setup_shlib_compiler()
  122. for ext in self.extensions:
  123. ext._full_name = self.get_ext_fullname(ext.name)
  124. for ext in self.extensions:
  125. fullname = ext._full_name
  126. self.ext_map[fullname] = ext
  127. # distutils 3.1 will also ask for module names
  128. # XXX what to do with conflicts?
  129. self.ext_map[fullname.split('.')[-1]] = ext
  130. ltd = self.shlibs and self.links_to_dynamic(ext) or False
  131. ns = ltd and use_stubs and not isinstance(ext, Library)
  132. ext._links_to_dynamic = ltd
  133. ext._needs_stub = ns
  134. filename = ext._file_name = self.get_ext_filename(fullname)
  135. libdir = os.path.dirname(os.path.join(self.build_lib, filename))
  136. if ltd and libdir not in ext.library_dirs:
  137. ext.library_dirs.append(libdir)
  138. if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
  139. ext.runtime_library_dirs.append(os.curdir)
  140. def setup_shlib_compiler(self):
  141. compiler = self.shlib_compiler = new_compiler(
  142. compiler=self.compiler, dry_run=self.dry_run, force=self.force
  143. )
  144. _customize_compiler_for_shlib(compiler)
  145. if self.include_dirs is not None:
  146. compiler.set_include_dirs(self.include_dirs)
  147. if self.define is not None:
  148. # 'define' option is a list of (name,value) tuples
  149. for (name, value) in self.define:
  150. compiler.define_macro(name, value)
  151. if self.undef is not None:
  152. for macro in self.undef:
  153. compiler.undefine_macro(macro)
  154. if self.libraries is not None:
  155. compiler.set_libraries(self.libraries)
  156. if self.library_dirs is not None:
  157. compiler.set_library_dirs(self.library_dirs)
  158. if self.rpath is not None:
  159. compiler.set_runtime_library_dirs(self.rpath)
  160. if self.link_objects is not None:
  161. compiler.set_link_objects(self.link_objects)
  162. # hack so distutils' build_extension() builds a library instead
  163. compiler.link_shared_object = link_shared_object.__get__(compiler)
  164. def get_export_symbols(self, ext):
  165. if isinstance(ext, Library):
  166. return ext.export_symbols
  167. return _build_ext.get_export_symbols(self, ext)
  168. def build_extension(self, ext):
  169. ext._convert_pyx_sources_to_lang()
  170. _compiler = self.compiler
  171. try:
  172. if isinstance(ext, Library):
  173. self.compiler = self.shlib_compiler
  174. _build_ext.build_extension(self, ext)
  175. if ext._needs_stub:
  176. cmd = self.get_finalized_command('build_py').build_lib
  177. self.write_stub(cmd, ext)
  178. finally:
  179. self.compiler = _compiler
  180. def links_to_dynamic(self, ext):
  181. """Return true if 'ext' links to a dynamic lib in the same package"""
  182. # XXX this should check to ensure the lib is actually being built
  183. # XXX as dynamic, and not just using a locally-found version or a
  184. # XXX static-compiled version
  185. libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
  186. pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
  187. return any(pkg + libname in libnames for libname in ext.libraries)
  188. def get_outputs(self):
  189. return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
  190. def __get_stubs_outputs(self):
  191. # assemble the base name for each extension that needs a stub
  192. ns_ext_bases = (
  193. os.path.join(self.build_lib, *ext._full_name.split('.'))
  194. for ext in self.extensions
  195. if ext._needs_stub
  196. )
  197. # pair each base with the extension
  198. pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
  199. return list(base + fnext for base, fnext in pairs)
  200. def __get_output_extensions(self):
  201. yield '.py'
  202. yield '.pyc'
  203. if self.get_finalized_command('build_py').optimize:
  204. yield '.pyo'
  205. def write_stub(self, output_dir, ext, compile=False):
  206. log.info("writing stub loader for %s to %s", ext._full_name,
  207. output_dir)
  208. stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
  209. '.py')
  210. if compile and os.path.exists(stub_file):
  211. raise DistutilsError(stub_file + " already exists! Please delete.")
  212. if not self.dry_run:
  213. f = open(stub_file, 'w')
  214. f.write(
  215. '\n'.join([
  216. "def __bootstrap__():",
  217. " global __bootstrap__, __file__, __loader__",
  218. " import sys, os, pkg_resources, imp" + if_dl(", dl"),
  219. " __file__ = pkg_resources.resource_filename"
  220. "(__name__,%r)"
  221. % os.path.basename(ext._file_name),
  222. " del __bootstrap__",
  223. " if '__loader__' in globals():",
  224. " del __loader__",
  225. if_dl(" old_flags = sys.getdlopenflags()"),
  226. " old_dir = os.getcwd()",
  227. " try:",
  228. " os.chdir(os.path.dirname(__file__))",
  229. if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
  230. " imp.load_dynamic(__name__,__file__)",
  231. " finally:",
  232. if_dl(" sys.setdlopenflags(old_flags)"),
  233. " os.chdir(old_dir)",
  234. "__bootstrap__()",
  235. "" # terminal \n
  236. ])
  237. )
  238. f.close()
  239. if compile:
  240. from distutils.util import byte_compile
  241. byte_compile([stub_file], optimize=0,
  242. force=True, dry_run=self.dry_run)
  243. optimize = self.get_finalized_command('install_lib').optimize
  244. if optimize > 0:
  245. byte_compile([stub_file], optimize=optimize,
  246. force=True, dry_run=self.dry_run)
  247. if os.path.exists(stub_file) and not self.dry_run:
  248. os.unlink(stub_file)
  249. if use_stubs or os.name == 'nt':
  250. # Build shared libraries
  251. #
  252. def link_shared_object(
  253. self, objects, output_libname, output_dir=None, libraries=None,
  254. library_dirs=None, runtime_library_dirs=None, export_symbols=None,
  255. debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
  256. target_lang=None):
  257. self.link(
  258. self.SHARED_LIBRARY, objects, output_libname,
  259. output_dir, libraries, library_dirs, runtime_library_dirs,
  260. export_symbols, debug, extra_preargs, extra_postargs,
  261. build_temp, target_lang
  262. )
  263. else:
  264. # Build static libraries everywhere else
  265. libtype = 'static'
  266. def link_shared_object(
  267. self, objects, output_libname, output_dir=None, libraries=None,
  268. library_dirs=None, runtime_library_dirs=None, export_symbols=None,
  269. debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
  270. target_lang=None):
  271. # XXX we need to either disallow these attrs on Library instances,
  272. # or warn/abort here if set, or something...
  273. # libraries=None, library_dirs=None, runtime_library_dirs=None,
  274. # export_symbols=None, extra_preargs=None, extra_postargs=None,
  275. # build_temp=None
  276. assert output_dir is None # distutils build_ext doesn't pass this
  277. output_dir, filename = os.path.split(output_libname)
  278. basename, ext = os.path.splitext(filename)
  279. if self.library_filename("x").startswith('lib'):
  280. # strip 'lib' prefix; this is kludgy if some platform uses
  281. # a different prefix
  282. basename = basename[3:]
  283. self.create_static_lib(
  284. objects, basename, output_dir, debug, target_lang
  285. )