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