ยปCore Development>Code coverage>Lib/distutils/command/build_ext.py

Python code coverage for Lib/distutils/command/build_ext.py

#countcontent
1n/a"""distutils.command.build_ext
2n/a
3n/aImplements the Distutils 'build_ext' command, for building extension
4n/amodules (currently limited to C extensions, should accommodate C++
5n/aextensions ASAP)."""
6n/a
7n/aimport contextlib
8n/aimport os
9n/aimport re
10n/aimport sys
11n/afrom distutils.core import Command
12n/afrom distutils.errors import *
13n/afrom distutils.sysconfig import customize_compiler, get_python_version
14n/afrom distutils.sysconfig import get_config_h_filename
15n/afrom distutils.dep_util import newer_group
16n/afrom distutils.extension import Extension
17n/afrom distutils.util import get_platform
18n/afrom distutils import log
19n/a
20n/afrom site import USER_BASE
21n/a
22n/a# An extension name is just a dot-separated list of Python NAMEs (ie.
23n/a# the same as a fully-qualified module name).
24n/aextension_name_re = re.compile \
25n/a (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
26n/a
27n/a
28n/adef show_compilers ():
29n/a from distutils.ccompiler import show_compilers
30n/a show_compilers()
31n/a
32n/a
33n/aclass build_ext(Command):
34n/a
35n/a description = "build C/C++ extensions (compile/link to build directory)"
36n/a
37n/a # XXX thoughts on how to deal with complex command-line options like
38n/a # these, i.e. how to make it so fancy_getopt can suck them off the
39n/a # command line and make it look like setup.py defined the appropriate
40n/a # lists of tuples of what-have-you.
41n/a # - each command needs a callback to process its command-line options
42n/a # - Command.__init__() needs access to its share of the whole
43n/a # command line (must ultimately come from
44n/a # Distribution.parse_command_line())
45n/a # - it then calls the current command class' option-parsing
46n/a # callback to deal with weird options like -D, which have to
47n/a # parse the option text and churn out some custom data
48n/a # structure
49n/a # - that data structure (in this case, a list of 2-tuples)
50n/a # will then be present in the command object by the time
51n/a # we get to finalize_options() (i.e. the constructor
52n/a # takes care of both command-line and client options
53n/a # in between initialize_options() and finalize_options())
54n/a
55n/a sep_by = " (separated by '%s')" % os.pathsep
56n/a user_options = [
57n/a ('build-lib=', 'b',
58n/a "directory for compiled extension modules"),
59n/a ('build-temp=', 't',
60n/a "directory for temporary files (build by-products)"),
61n/a ('plat-name=', 'p',
62n/a "platform name to cross-compile for, if supported "
63n/a "(default: %s)" % get_platform()),
64n/a ('inplace', 'i',
65n/a "ignore build-lib and put compiled extensions into the source " +
66n/a "directory alongside your pure Python modules"),
67n/a ('include-dirs=', 'I',
68n/a "list of directories to search for header files" + sep_by),
69n/a ('define=', 'D',
70n/a "C preprocessor macros to define"),
71n/a ('undef=', 'U',
72n/a "C preprocessor macros to undefine"),
73n/a ('libraries=', 'l',
74n/a "external C libraries to link with"),
75n/a ('library-dirs=', 'L',
76n/a "directories to search for external C libraries" + sep_by),
77n/a ('rpath=', 'R',
78n/a "directories to search for shared C libraries at runtime"),
79n/a ('link-objects=', 'O',
80n/a "extra explicit link objects to include in the link"),
81n/a ('debug', 'g',
82n/a "compile/link with debugging information"),
83n/a ('force', 'f',
84n/a "forcibly build everything (ignore file timestamps)"),
85n/a ('compiler=', 'c',
86n/a "specify the compiler type"),
87n/a ('parallel=', 'j',
88n/a "number of parallel build jobs"),
89n/a ('swig-cpp', None,
90n/a "make SWIG create C++ files (default is C)"),
91n/a ('swig-opts=', None,
92n/a "list of SWIG command line options"),
93n/a ('swig=', None,
94n/a "path to the SWIG executable"),
95n/a ('user', None,
96n/a "add user include, library and rpath")
97n/a ]
98n/a
99n/a boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
100n/a
101n/a help_options = [
102n/a ('help-compiler', None,
103n/a "list available compilers", show_compilers),
104n/a ]
105n/a
106n/a def initialize_options(self):
107n/a self.extensions = None
108n/a self.build_lib = None
109n/a self.plat_name = None
110n/a self.build_temp = None
111n/a self.inplace = 0
112n/a self.package = None
113n/a
114n/a self.include_dirs = None
115n/a self.define = None
116n/a self.undef = None
117n/a self.libraries = None
118n/a self.library_dirs = None
119n/a self.rpath = None
120n/a self.link_objects = None
121n/a self.debug = None
122n/a self.force = None
123n/a self.compiler = None
124n/a self.swig = None
125n/a self.swig_cpp = None
126n/a self.swig_opts = None
127n/a self.user = None
128n/a self.parallel = None
129n/a
130n/a def finalize_options(self):
131n/a from distutils import sysconfig
132n/a
133n/a self.set_undefined_options('build',
134n/a ('build_lib', 'build_lib'),
135n/a ('build_temp', 'build_temp'),
136n/a ('compiler', 'compiler'),
137n/a ('debug', 'debug'),
138n/a ('force', 'force'),
139n/a ('parallel', 'parallel'),
140n/a ('plat_name', 'plat_name'),
141n/a )
142n/a
143n/a if self.package is None:
144n/a self.package = self.distribution.ext_package
145n/a
146n/a self.extensions = self.distribution.ext_modules
147n/a
148n/a # Make sure Python's include directories (for Python.h, pyconfig.h,
149n/a # etc.) are in the include search path.
150n/a py_include = sysconfig.get_python_inc()
151n/a plat_py_include = sysconfig.get_python_inc(plat_specific=1)
152n/a if self.include_dirs is None:
153n/a self.include_dirs = self.distribution.include_dirs or []
154n/a if isinstance(self.include_dirs, str):
155n/a self.include_dirs = self.include_dirs.split(os.pathsep)
156n/a
157n/a # If in a virtualenv, add its include directory
158n/a # Issue 16116
159n/a if sys.exec_prefix != sys.base_exec_prefix:
160n/a self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
161n/a
162n/a # Put the Python "system" include dir at the end, so that
163n/a # any local include dirs take precedence.
164n/a self.include_dirs.append(py_include)
165n/a if plat_py_include != py_include:
166n/a self.include_dirs.append(plat_py_include)
167n/a
168n/a self.ensure_string_list('libraries')
169n/a self.ensure_string_list('link_objects')
170n/a
171n/a # Life is easier if we're not forever checking for None, so
172n/a # simplify these options to empty lists if unset
173n/a if self.libraries is None:
174n/a self.libraries = []
175n/a if self.library_dirs is None:
176n/a self.library_dirs = []
177n/a elif isinstance(self.library_dirs, str):
178n/a self.library_dirs = self.library_dirs.split(os.pathsep)
179n/a
180n/a if self.rpath is None:
181n/a self.rpath = []
182n/a elif isinstance(self.rpath, str):
183n/a self.rpath = self.rpath.split(os.pathsep)
184n/a
185n/a # for extensions under windows use different directories
186n/a # for Release and Debug builds.
187n/a # also Python's library directory must be appended to library_dirs
188n/a if os.name == 'nt':
189n/a # the 'libs' directory is for binary installs - we assume that
190n/a # must be the *native* platform. But we don't really support
191n/a # cross-compiling via a binary install anyway, so we let it go.
192n/a self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
193n/a if sys.base_exec_prefix != sys.prefix: # Issue 16116
194n/a self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
195n/a if self.debug:
196n/a self.build_temp = os.path.join(self.build_temp, "Debug")
197n/a else:
198n/a self.build_temp = os.path.join(self.build_temp, "Release")
199n/a
200n/a # Append the source distribution include and library directories,
201n/a # this allows distutils on windows to work in the source tree
202n/a self.include_dirs.append(os.path.dirname(get_config_h_filename()))
203n/a _sys_home = getattr(sys, '_home', None)
204n/a if _sys_home:
205n/a self.library_dirs.append(_sys_home)
206n/a
207n/a # Use the .lib files for the correct architecture
208n/a if self.plat_name == 'win32':
209n/a suffix = 'win32'
210n/a else:
211n/a # win-amd64 or win-ia64
212n/a suffix = self.plat_name[4:]
213n/a new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
214n/a if suffix:
215n/a new_lib = os.path.join(new_lib, suffix)
216n/a self.library_dirs.append(new_lib)
217n/a
218n/a # for extensions under Cygwin and AtheOS Python's library directory must be
219n/a # appended to library_dirs
220n/a if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
221n/a if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
222n/a # building third party extensions
223n/a self.library_dirs.append(os.path.join(sys.prefix, "lib",
224n/a "python" + get_python_version(),
225n/a "config"))
226n/a else:
227n/a # building python standard extensions
228n/a self.library_dirs.append('.')
229n/a
230n/a # For building extensions with a shared Python library,
231n/a # Python's library directory must be appended to library_dirs
232n/a # See Issues: #1600860, #4366
233n/a if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
234n/a if not sysconfig.python_build:
235n/a # building third party extensions
236n/a self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
237n/a else:
238n/a # building python standard extensions
239n/a self.library_dirs.append('.')
240n/a
241n/a # The argument parsing will result in self.define being a string, but
242n/a # it has to be a list of 2-tuples. All the preprocessor symbols
243n/a # specified by the 'define' option will be set to '1'. Multiple
244n/a # symbols can be separated with commas.
245n/a
246n/a if self.define:
247n/a defines = self.define.split(',')
248n/a self.define = [(symbol, '1') for symbol in defines]
249n/a
250n/a # The option for macros to undefine is also a string from the
251n/a # option parsing, but has to be a list. Multiple symbols can also
252n/a # be separated with commas here.
253n/a if self.undef:
254n/a self.undef = self.undef.split(',')
255n/a
256n/a if self.swig_opts is None:
257n/a self.swig_opts = []
258n/a else:
259n/a self.swig_opts = self.swig_opts.split(' ')
260n/a
261n/a # Finally add the user include and library directories if requested
262n/a if self.user:
263n/a user_include = os.path.join(USER_BASE, "include")
264n/a user_lib = os.path.join(USER_BASE, "lib")
265n/a if os.path.isdir(user_include):
266n/a self.include_dirs.append(user_include)
267n/a if os.path.isdir(user_lib):
268n/a self.library_dirs.append(user_lib)
269n/a self.rpath.append(user_lib)
270n/a
271n/a if isinstance(self.parallel, str):
272n/a try:
273n/a self.parallel = int(self.parallel)
274n/a except ValueError:
275n/a raise DistutilsOptionError("parallel should be an integer")
276n/a
277n/a def run(self):
278n/a from distutils.ccompiler import new_compiler
279n/a
280n/a # 'self.extensions', as supplied by setup.py, is a list of
281n/a # Extension instances. See the documentation for Extension (in
282n/a # distutils.extension) for details.
283n/a #
284n/a # For backwards compatibility with Distutils 0.8.2 and earlier, we
285n/a # also allow the 'extensions' list to be a list of tuples:
286n/a # (ext_name, build_info)
287n/a # where build_info is a dictionary containing everything that
288n/a # Extension instances do except the name, with a few things being
289n/a # differently named. We convert these 2-tuples to Extension
290n/a # instances as needed.
291n/a
292n/a if not self.extensions:
293n/a return
294n/a
295n/a # If we were asked to build any C/C++ libraries, make sure that the
296n/a # directory where we put them is in the library search path for
297n/a # linking extensions.
298n/a if self.distribution.has_c_libraries():
299n/a build_clib = self.get_finalized_command('build_clib')
300n/a self.libraries.extend(build_clib.get_library_names() or [])
301n/a self.library_dirs.append(build_clib.build_clib)
302n/a
303n/a # Setup the CCompiler object that we'll use to do all the
304n/a # compiling and linking
305n/a self.compiler = new_compiler(compiler=self.compiler,
306n/a verbose=self.verbose,
307n/a dry_run=self.dry_run,
308n/a force=self.force)
309n/a customize_compiler(self.compiler)
310n/a # If we are cross-compiling, init the compiler now (if we are not
311n/a # cross-compiling, init would not hurt, but people may rely on
312n/a # late initialization of compiler even if they shouldn't...)
313n/a if os.name == 'nt' and self.plat_name != get_platform():
314n/a self.compiler.initialize(self.plat_name)
315n/a
316n/a # And make sure that any compile/link-related options (which might
317n/a # come from the command-line or from the setup script) are set in
318n/a # that CCompiler object -- that way, they automatically apply to
319n/a # all compiling and linking done here.
320n/a if self.include_dirs is not None:
321n/a self.compiler.set_include_dirs(self.include_dirs)
322n/a if self.define is not None:
323n/a # 'define' option is a list of (name,value) tuples
324n/a for (name, value) in self.define:
325n/a self.compiler.define_macro(name, value)
326n/a if self.undef is not None:
327n/a for macro in self.undef:
328n/a self.compiler.undefine_macro(macro)
329n/a if self.libraries is not None:
330n/a self.compiler.set_libraries(self.libraries)
331n/a if self.library_dirs is not None:
332n/a self.compiler.set_library_dirs(self.library_dirs)
333n/a if self.rpath is not None:
334n/a self.compiler.set_runtime_library_dirs(self.rpath)
335n/a if self.link_objects is not None:
336n/a self.compiler.set_link_objects(self.link_objects)
337n/a
338n/a # Now actually compile and link everything.
339n/a self.build_extensions()
340n/a
341n/a def check_extensions_list(self, extensions):
342n/a """Ensure that the list of extensions (presumably provided as a
343n/a command option 'extensions') is valid, i.e. it is a list of
344n/a Extension objects. We also support the old-style list of 2-tuples,
345n/a where the tuples are (ext_name, build_info), which are converted to
346n/a Extension instances here.
347n/a
348n/a Raise DistutilsSetupError if the structure is invalid anywhere;
349n/a just returns otherwise.
350n/a """
351n/a if not isinstance(extensions, list):
352n/a raise DistutilsSetupError(
353n/a "'ext_modules' option must be a list of Extension instances")
354n/a
355n/a for i, ext in enumerate(extensions):
356n/a if isinstance(ext, Extension):
357n/a continue # OK! (assume type-checking done
358n/a # by Extension constructor)
359n/a
360n/a if not isinstance(ext, tuple) or len(ext) != 2:
361n/a raise DistutilsSetupError(
362n/a "each element of 'ext_modules' option must be an "
363n/a "Extension instance or 2-tuple")
364n/a
365n/a ext_name, build_info = ext
366n/a
367n/a log.warn("old-style (ext_name, build_info) tuple found in "
368n/a "ext_modules for extension '%s'"
369n/a "-- please convert to Extension instance", ext_name)
370n/a
371n/a if not (isinstance(ext_name, str) and
372n/a extension_name_re.match(ext_name)):
373n/a raise DistutilsSetupError(
374n/a "first element of each tuple in 'ext_modules' "
375n/a "must be the extension name (a string)")
376n/a
377n/a if not isinstance(build_info, dict):
378n/a raise DistutilsSetupError(
379n/a "second element of each tuple in 'ext_modules' "
380n/a "must be a dictionary (build info)")
381n/a
382n/a # OK, the (ext_name, build_info) dict is type-safe: convert it
383n/a # to an Extension instance.
384n/a ext = Extension(ext_name, build_info['sources'])
385n/a
386n/a # Easy stuff: one-to-one mapping from dict elements to
387n/a # instance attributes.
388n/a for key in ('include_dirs', 'library_dirs', 'libraries',
389n/a 'extra_objects', 'extra_compile_args',
390n/a 'extra_link_args'):
391n/a val = build_info.get(key)
392n/a if val is not None:
393n/a setattr(ext, key, val)
394n/a
395n/a # Medium-easy stuff: same syntax/semantics, different names.
396n/a ext.runtime_library_dirs = build_info.get('rpath')
397n/a if 'def_file' in build_info:
398n/a log.warn("'def_file' element of build info dict "
399n/a "no longer supported")
400n/a
401n/a # Non-trivial stuff: 'macros' split into 'define_macros'
402n/a # and 'undef_macros'.
403n/a macros = build_info.get('macros')
404n/a if macros:
405n/a ext.define_macros = []
406n/a ext.undef_macros = []
407n/a for macro in macros:
408n/a if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
409n/a raise DistutilsSetupError(
410n/a "'macros' element of build info dict "
411n/a "must be 1- or 2-tuple")
412n/a if len(macro) == 1:
413n/a ext.undef_macros.append(macro[0])
414n/a elif len(macro) == 2:
415n/a ext.define_macros.append(macro)
416n/a
417n/a extensions[i] = ext
418n/a
419n/a def get_source_files(self):
420n/a self.check_extensions_list(self.extensions)
421n/a filenames = []
422n/a
423n/a # Wouldn't it be neat if we knew the names of header files too...
424n/a for ext in self.extensions:
425n/a filenames.extend(ext.sources)
426n/a return filenames
427n/a
428n/a def get_outputs(self):
429n/a # Sanity check the 'extensions' list -- can't assume this is being
430n/a # done in the same run as a 'build_extensions()' call (in fact, we
431n/a # can probably assume that it *isn't*!).
432n/a self.check_extensions_list(self.extensions)
433n/a
434n/a # And build the list of output (built) filenames. Note that this
435n/a # ignores the 'inplace' flag, and assumes everything goes in the
436n/a # "build" tree.
437n/a outputs = []
438n/a for ext in self.extensions:
439n/a outputs.append(self.get_ext_fullpath(ext.name))
440n/a return outputs
441n/a
442n/a def build_extensions(self):
443n/a # First, sanity-check the 'extensions' list
444n/a self.check_extensions_list(self.extensions)
445n/a if self.parallel:
446n/a self._build_extensions_parallel()
447n/a else:
448n/a self._build_extensions_serial()
449n/a
450n/a def _build_extensions_parallel(self):
451n/a workers = self.parallel
452n/a if self.parallel is True:
453n/a workers = os.cpu_count() # may return None
454n/a try:
455n/a from concurrent.futures import ThreadPoolExecutor
456n/a except ImportError:
457n/a workers = None
458n/a
459n/a if workers is None:
460n/a self._build_extensions_serial()
461n/a return
462n/a
463n/a with ThreadPoolExecutor(max_workers=workers) as executor:
464n/a futures = [executor.submit(self.build_extension, ext)
465n/a for ext in self.extensions]
466n/a for ext, fut in zip(self.extensions, futures):
467n/a with self._filter_build_errors(ext):
468n/a fut.result()
469n/a
470n/a def _build_extensions_serial(self):
471n/a for ext in self.extensions:
472n/a with self._filter_build_errors(ext):
473n/a self.build_extension(ext)
474n/a
475n/a @contextlib.contextmanager
476n/a def _filter_build_errors(self, ext):
477n/a try:
478n/a yield
479n/a except (CCompilerError, DistutilsError, CompileError) as e:
480n/a if not ext.optional:
481n/a raise
482n/a self.warn('building extension "%s" failed: %s' %
483n/a (ext.name, e))
484n/a
485n/a def build_extension(self, ext):
486n/a sources = ext.sources
487n/a if sources is None or not isinstance(sources, (list, tuple)):
488n/a raise DistutilsSetupError(
489n/a "in 'ext_modules' option (extension '%s'), "
490n/a "'sources' must be present and must be "
491n/a "a list of source filenames" % ext.name)
492n/a sources = list(sources)
493n/a
494n/a ext_path = self.get_ext_fullpath(ext.name)
495n/a depends = sources + ext.depends
496n/a if not (self.force or newer_group(depends, ext_path, 'newer')):
497n/a log.debug("skipping '%s' extension (up-to-date)", ext.name)
498n/a return
499n/a else:
500n/a log.info("building '%s' extension", ext.name)
501n/a
502n/a # First, scan the sources for SWIG definition files (.i), run
503n/a # SWIG on 'em to create .c files, and modify the sources list
504n/a # accordingly.
505n/a sources = self.swig_sources(sources, ext)
506n/a
507n/a # Next, compile the source code to object files.
508n/a
509n/a # XXX not honouring 'define_macros' or 'undef_macros' -- the
510n/a # CCompiler API needs to change to accommodate this, and I
511n/a # want to do one thing at a time!
512n/a
513n/a # Two possible sources for extra compiler arguments:
514n/a # - 'extra_compile_args' in Extension object
515n/a # - CFLAGS environment variable (not particularly
516n/a # elegant, but people seem to expect it and I
517n/a # guess it's useful)
518n/a # The environment variable should take precedence, and
519n/a # any sensible compiler will give precedence to later
520n/a # command line args. Hence we combine them in order:
521n/a extra_args = ext.extra_compile_args or []
522n/a
523n/a macros = ext.define_macros[:]
524n/a for undef in ext.undef_macros:
525n/a macros.append((undef,))
526n/a
527n/a objects = self.compiler.compile(sources,
528n/a output_dir=self.build_temp,
529n/a macros=macros,
530n/a include_dirs=ext.include_dirs,
531n/a debug=self.debug,
532n/a extra_postargs=extra_args,
533n/a depends=ext.depends)
534n/a
535n/a # XXX outdated variable, kept here in case third-part code
536n/a # needs it.
537n/a self._built_objects = objects[:]
538n/a
539n/a # Now link the object files together into a "shared object" --
540n/a # of course, first we have to figure out all the other things
541n/a # that go into the mix.
542n/a if ext.extra_objects:
543n/a objects.extend(ext.extra_objects)
544n/a extra_args = ext.extra_link_args or []
545n/a
546n/a # Detect target language, if not provided
547n/a language = ext.language or self.compiler.detect_language(sources)
548n/a
549n/a self.compiler.link_shared_object(
550n/a objects, ext_path,
551n/a libraries=self.get_libraries(ext),
552n/a library_dirs=ext.library_dirs,
553n/a runtime_library_dirs=ext.runtime_library_dirs,
554n/a extra_postargs=extra_args,
555n/a export_symbols=self.get_export_symbols(ext),
556n/a debug=self.debug,
557n/a build_temp=self.build_temp,
558n/a target_lang=language)
559n/a
560n/a def swig_sources(self, sources, extension):
561n/a """Walk the list of source files in 'sources', looking for SWIG
562n/a interface (.i) files. Run SWIG on all that are found, and
563n/a return a modified 'sources' list with SWIG source files replaced
564n/a by the generated C (or C++) files.
565n/a """
566n/a new_sources = []
567n/a swig_sources = []
568n/a swig_targets = {}
569n/a
570n/a # XXX this drops generated C/C++ files into the source tree, which
571n/a # is fine for developers who want to distribute the generated
572n/a # source -- but there should be an option to put SWIG output in
573n/a # the temp dir.
574n/a
575n/a if self.swig_cpp:
576n/a log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
577n/a
578n/a if self.swig_cpp or ('-c++' in self.swig_opts) or \
579n/a ('-c++' in extension.swig_opts):
580n/a target_ext = '.cpp'
581n/a else:
582n/a target_ext = '.c'
583n/a
584n/a for source in sources:
585n/a (base, ext) = os.path.splitext(source)
586n/a if ext == ".i": # SWIG interface file
587n/a new_sources.append(base + '_wrap' + target_ext)
588n/a swig_sources.append(source)
589n/a swig_targets[source] = new_sources[-1]
590n/a else:
591n/a new_sources.append(source)
592n/a
593n/a if not swig_sources:
594n/a return new_sources
595n/a
596n/a swig = self.swig or self.find_swig()
597n/a swig_cmd = [swig, "-python"]
598n/a swig_cmd.extend(self.swig_opts)
599n/a if self.swig_cpp:
600n/a swig_cmd.append("-c++")
601n/a
602n/a # Do not override commandline arguments
603n/a if not self.swig_opts:
604n/a for o in extension.swig_opts:
605n/a swig_cmd.append(o)
606n/a
607n/a for source in swig_sources:
608n/a target = swig_targets[source]
609n/a log.info("swigging %s to %s", source, target)
610n/a self.spawn(swig_cmd + ["-o", target, source])
611n/a
612n/a return new_sources
613n/a
614n/a def find_swig(self):
615n/a """Return the name of the SWIG executable. On Unix, this is
616n/a just "swig" -- it should be in the PATH. Tries a bit harder on
617n/a Windows.
618n/a """
619n/a if os.name == "posix":
620n/a return "swig"
621n/a elif os.name == "nt":
622n/a # Look for SWIG in its standard installation directory on
623n/a # Windows (or so I presume!). If we find it there, great;
624n/a # if not, act like Unix and assume it's in the PATH.
625n/a for vers in ("1.3", "1.2", "1.1"):
626n/a fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
627n/a if os.path.isfile(fn):
628n/a return fn
629n/a else:
630n/a return "swig.exe"
631n/a else:
632n/a raise DistutilsPlatformError(
633n/a "I don't know how to find (much less run) SWIG "
634n/a "on platform '%s'" % os.name)
635n/a
636n/a # -- Name generators -----------------------------------------------
637n/a # (extension names, filenames, whatever)
638n/a def get_ext_fullpath(self, ext_name):
639n/a """Returns the path of the filename for a given extension.
640n/a
641n/a The file is located in `build_lib` or directly in the package
642n/a (inplace option).
643n/a """
644n/a fullname = self.get_ext_fullname(ext_name)
645n/a modpath = fullname.split('.')
646n/a filename = self.get_ext_filename(modpath[-1])
647n/a
648n/a if not self.inplace:
649n/a # no further work needed
650n/a # returning :
651n/a # build_dir/package/path/filename
652n/a filename = os.path.join(*modpath[:-1]+[filename])
653n/a return os.path.join(self.build_lib, filename)
654n/a
655n/a # the inplace option requires to find the package directory
656n/a # using the build_py command for that
657n/a package = '.'.join(modpath[0:-1])
658n/a build_py = self.get_finalized_command('build_py')
659n/a package_dir = os.path.abspath(build_py.get_package_dir(package))
660n/a
661n/a # returning
662n/a # package_dir/filename
663n/a return os.path.join(package_dir, filename)
664n/a
665n/a def get_ext_fullname(self, ext_name):
666n/a """Returns the fullname of a given extension name.
667n/a
668n/a Adds the `package.` prefix"""
669n/a if self.package is None:
670n/a return ext_name
671n/a else:
672n/a return self.package + '.' + ext_name
673n/a
674n/a def get_ext_filename(self, ext_name):
675n/a r"""Convert the name of an extension (eg. "foo.bar") into the name
676n/a of the file from which it will be loaded (eg. "foo/bar.so", or
677n/a "foo\bar.pyd").
678n/a """
679n/a from distutils.sysconfig import get_config_var
680n/a ext_path = ext_name.split('.')
681n/a ext_suffix = get_config_var('EXT_SUFFIX')
682n/a return os.path.join(*ext_path) + ext_suffix
683n/a
684n/a def get_export_symbols(self, ext):
685n/a """Return the list of symbols that a shared extension has to
686n/a export. This either uses 'ext.export_symbols' or, if it's not
687n/a provided, "PyInit_" + module_name. Only relevant on Windows, where
688n/a the .pyd file (DLL) must export the module "PyInit_" function.
689n/a """
690n/a initfunc_name = "PyInit_" + ext.name.split('.')[-1]
691n/a if initfunc_name not in ext.export_symbols:
692n/a ext.export_symbols.append(initfunc_name)
693n/a return ext.export_symbols
694n/a
695n/a def get_libraries(self, ext):
696n/a """Return the list of libraries to link against when building a
697n/a shared extension. On most platforms, this is just 'ext.libraries';
698n/a on Windows, we add the Python library (eg. python20.dll).
699n/a """
700n/a # The python library is always needed on Windows. For MSVC, this
701n/a # is redundant, since the library is mentioned in a pragma in
702n/a # pyconfig.h that MSVC groks. The other Windows compilers all seem
703n/a # to need it mentioned explicitly, though, so that's what we do.
704n/a # Append '_d' to the python import library on debug builds.
705n/a if sys.platform == "win32":
706n/a from distutils._msvccompiler import MSVCCompiler
707n/a if not isinstance(self.compiler, MSVCCompiler):
708n/a template = "python%d%d"
709n/a if self.debug:
710n/a template = template + '_d'
711n/a pythonlib = (template %
712n/a (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
713n/a # don't extend ext.libraries, it may be shared with other
714n/a # extensions, it is a reference to the original list
715n/a return ext.libraries + [pythonlib]
716n/a else:
717n/a return ext.libraries
718n/a elif sys.platform[:6] == "atheos":
719n/a from distutils import sysconfig
720n/a
721n/a template = "python%d.%d"
722n/a pythonlib = (template %
723n/a (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
724n/a # Get SHLIBS from Makefile
725n/a extra = []
726n/a for lib in sysconfig.get_config_var('SHLIBS').split():
727n/a if lib.startswith('-l'):
728n/a extra.append(lib[2:])
729n/a else:
730n/a extra.append(lib)
731n/a # don't extend ext.libraries, it may be shared with other
732n/a # extensions, it is a reference to the original list
733n/a return ext.libraries + [pythonlib, "m"] + extra
734n/a elif sys.platform == 'darwin':
735n/a # Don't use the default code below
736n/a return ext.libraries
737n/a elif sys.platform[:3] == 'aix':
738n/a # Don't use the default code below
739n/a return ext.libraries
740n/a else:
741n/a from distutils import sysconfig
742n/a if sysconfig.get_config_var('Py_ENABLE_SHARED'):
743n/a pythonlib = 'python{}.{}{}'.format(
744n/a sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff,
745n/a sysconfig.get_config_var('ABIFLAGS'))
746n/a return ext.libraries + [pythonlib]
747n/a else:
748n/a return ext.libraries