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

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

#countcontent
1n/a"""distutils.command.config
2n/a
3n/aImplements the Distutils 'config' command, a (mostly) empty command class
4n/athat exists mainly to be sub-classed by specific module distributions and
5n/aapplications. The idea is that while every "config" command is different,
6n/aat least they're all named the same, and users always see "config" in the
7n/alist of standard commands. Also, this is a good place to put common
8n/aconfigure-like tasks: "try to compile this C code", or "figure out where
9n/athis header file lives".
10n/a"""
11n/a
12n/aimport os, re
13n/a
14n/afrom distutils.core import Command
15n/afrom distutils.errors import DistutilsExecError
16n/afrom distutils.sysconfig import customize_compiler
17n/afrom distutils import log
18n/a
19n/aLANG_EXT = {"c": ".c", "c++": ".cxx"}
20n/a
21n/aclass config(Command):
22n/a
23n/a description = "prepare to build"
24n/a
25n/a user_options = [
26n/a ('compiler=', None,
27n/a "specify the compiler type"),
28n/a ('cc=', None,
29n/a "specify the compiler executable"),
30n/a ('include-dirs=', 'I',
31n/a "list of directories to search for header files"),
32n/a ('define=', 'D',
33n/a "C preprocessor macros to define"),
34n/a ('undef=', 'U',
35n/a "C preprocessor macros to undefine"),
36n/a ('libraries=', 'l',
37n/a "external C libraries to link with"),
38n/a ('library-dirs=', 'L',
39n/a "directories to search for external C libraries"),
40n/a
41n/a ('noisy', None,
42n/a "show every action (compile, link, run, ...) taken"),
43n/a ('dump-source', None,
44n/a "dump generated source files before attempting to compile them"),
45n/a ]
46n/a
47n/a
48n/a # The three standard command methods: since the "config" command
49n/a # does nothing by default, these are empty.
50n/a
51n/a def initialize_options(self):
52n/a self.compiler = None
53n/a self.cc = None
54n/a self.include_dirs = None
55n/a self.libraries = None
56n/a self.library_dirs = None
57n/a
58n/a # maximal output for now
59n/a self.noisy = 1
60n/a self.dump_source = 1
61n/a
62n/a # list of temporary files generated along-the-way that we have
63n/a # to clean at some point
64n/a self.temp_files = []
65n/a
66n/a def finalize_options(self):
67n/a if self.include_dirs is None:
68n/a self.include_dirs = self.distribution.include_dirs or []
69n/a elif isinstance(self.include_dirs, str):
70n/a self.include_dirs = self.include_dirs.split(os.pathsep)
71n/a
72n/a if self.libraries is None:
73n/a self.libraries = []
74n/a elif isinstance(self.libraries, str):
75n/a self.libraries = [self.libraries]
76n/a
77n/a if self.library_dirs is None:
78n/a self.library_dirs = []
79n/a elif isinstance(self.library_dirs, str):
80n/a self.library_dirs = self.library_dirs.split(os.pathsep)
81n/a
82n/a def run(self):
83n/a pass
84n/a
85n/a # Utility methods for actual "config" commands. The interfaces are
86n/a # loosely based on Autoconf macros of similar names. Sub-classes
87n/a # may use these freely.
88n/a
89n/a def _check_compiler(self):
90n/a """Check that 'self.compiler' really is a CCompiler object;
91n/a if not, make it one.
92n/a """
93n/a # We do this late, and only on-demand, because this is an expensive
94n/a # import.
95n/a from distutils.ccompiler import CCompiler, new_compiler
96n/a if not isinstance(self.compiler, CCompiler):
97n/a self.compiler = new_compiler(compiler=self.compiler,
98n/a dry_run=self.dry_run, force=1)
99n/a customize_compiler(self.compiler)
100n/a if self.include_dirs:
101n/a self.compiler.set_include_dirs(self.include_dirs)
102n/a if self.libraries:
103n/a self.compiler.set_libraries(self.libraries)
104n/a if self.library_dirs:
105n/a self.compiler.set_library_dirs(self.library_dirs)
106n/a
107n/a def _gen_temp_sourcefile(self, body, headers, lang):
108n/a filename = "_configtest" + LANG_EXT[lang]
109n/a file = open(filename, "w")
110n/a if headers:
111n/a for header in headers:
112n/a file.write("#include <%s>\n" % header)
113n/a file.write("\n")
114n/a file.write(body)
115n/a if body[-1] != "\n":
116n/a file.write("\n")
117n/a file.close()
118n/a return filename
119n/a
120n/a def _preprocess(self, body, headers, include_dirs, lang):
121n/a src = self._gen_temp_sourcefile(body, headers, lang)
122n/a out = "_configtest.i"
123n/a self.temp_files.extend([src, out])
124n/a self.compiler.preprocess(src, out, include_dirs=include_dirs)
125n/a return (src, out)
126n/a
127n/a def _compile(self, body, headers, include_dirs, lang):
128n/a src = self._gen_temp_sourcefile(body, headers, lang)
129n/a if self.dump_source:
130n/a dump_file(src, "compiling '%s':" % src)
131n/a (obj,) = self.compiler.object_filenames([src])
132n/a self.temp_files.extend([src, obj])
133n/a self.compiler.compile([src], include_dirs=include_dirs)
134n/a return (src, obj)
135n/a
136n/a def _link(self, body, headers, include_dirs, libraries, library_dirs,
137n/a lang):
138n/a (src, obj) = self._compile(body, headers, include_dirs, lang)
139n/a prog = os.path.splitext(os.path.basename(src))[0]
140n/a self.compiler.link_executable([obj], prog,
141n/a libraries=libraries,
142n/a library_dirs=library_dirs,
143n/a target_lang=lang)
144n/a
145n/a if self.compiler.exe_extension is not None:
146n/a prog = prog + self.compiler.exe_extension
147n/a self.temp_files.append(prog)
148n/a
149n/a return (src, obj, prog)
150n/a
151n/a def _clean(self, *filenames):
152n/a if not filenames:
153n/a filenames = self.temp_files
154n/a self.temp_files = []
155n/a log.info("removing: %s", ' '.join(filenames))
156n/a for filename in filenames:
157n/a try:
158n/a os.remove(filename)
159n/a except OSError:
160n/a pass
161n/a
162n/a
163n/a # XXX these ignore the dry-run flag: what to do, what to do? even if
164n/a # you want a dry-run build, you still need some sort of configuration
165n/a # info. My inclination is to make it up to the real config command to
166n/a # consult 'dry_run', and assume a default (minimal) configuration if
167n/a # true. The problem with trying to do it here is that you'd have to
168n/a # return either true or false from all the 'try' methods, neither of
169n/a # which is correct.
170n/a
171n/a # XXX need access to the header search path and maybe default macros.
172n/a
173n/a def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
174n/a """Construct a source file from 'body' (a string containing lines
175n/a of C/C++ code) and 'headers' (a list of header files to include)
176n/a and run it through the preprocessor. Return true if the
177n/a preprocessor succeeded, false if there were any errors.
178n/a ('body' probably isn't of much use, but what the heck.)
179n/a """
180n/a from distutils.ccompiler import CompileError
181n/a self._check_compiler()
182n/a ok = True
183n/a try:
184n/a self._preprocess(body, headers, include_dirs, lang)
185n/a except CompileError:
186n/a ok = False
187n/a
188n/a self._clean()
189n/a return ok
190n/a
191n/a def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
192n/a lang="c"):
193n/a """Construct a source file (just like 'try_cpp()'), run it through
194n/a the preprocessor, and return true if any line of the output matches
195n/a 'pattern'. 'pattern' should either be a compiled regex object or a
196n/a string containing a regex. If both 'body' and 'headers' are None,
197n/a preprocesses an empty file -- which can be useful to determine the
198n/a symbols the preprocessor and compiler set by default.
199n/a """
200n/a self._check_compiler()
201n/a src, out = self._preprocess(body, headers, include_dirs, lang)
202n/a
203n/a if isinstance(pattern, str):
204n/a pattern = re.compile(pattern)
205n/a
206n/a file = open(out)
207n/a match = False
208n/a while True:
209n/a line = file.readline()
210n/a if line == '':
211n/a break
212n/a if pattern.search(line):
213n/a match = True
214n/a break
215n/a
216n/a file.close()
217n/a self._clean()
218n/a return match
219n/a
220n/a def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
221n/a """Try to compile a source file built from 'body' and 'headers'.
222n/a Return true on success, false otherwise.
223n/a """
224n/a from distutils.ccompiler import CompileError
225n/a self._check_compiler()
226n/a try:
227n/a self._compile(body, headers, include_dirs, lang)
228n/a ok = True
229n/a except CompileError:
230n/a ok = False
231n/a
232n/a log.info(ok and "success!" or "failure.")
233n/a self._clean()
234n/a return ok
235n/a
236n/a def try_link(self, body, headers=None, include_dirs=None, libraries=None,
237n/a library_dirs=None, lang="c"):
238n/a """Try to compile and link a source file, built from 'body' and
239n/a 'headers', to executable form. Return true on success, false
240n/a otherwise.
241n/a """
242n/a from distutils.ccompiler import CompileError, LinkError
243n/a self._check_compiler()
244n/a try:
245n/a self._link(body, headers, include_dirs,
246n/a libraries, library_dirs, lang)
247n/a ok = True
248n/a except (CompileError, LinkError):
249n/a ok = False
250n/a
251n/a log.info(ok and "success!" or "failure.")
252n/a self._clean()
253n/a return ok
254n/a
255n/a def try_run(self, body, headers=None, include_dirs=None, libraries=None,
256n/a library_dirs=None, lang="c"):
257n/a """Try to compile, link to an executable, and run a program
258n/a built from 'body' and 'headers'. Return true on success, false
259n/a otherwise.
260n/a """
261n/a from distutils.ccompiler import CompileError, LinkError
262n/a self._check_compiler()
263n/a try:
264n/a src, obj, exe = self._link(body, headers, include_dirs,
265n/a libraries, library_dirs, lang)
266n/a self.spawn([exe])
267n/a ok = True
268n/a except (CompileError, LinkError, DistutilsExecError):
269n/a ok = False
270n/a
271n/a log.info(ok and "success!" or "failure.")
272n/a self._clean()
273n/a return ok
274n/a
275n/a
276n/a # -- High-level methods --------------------------------------------
277n/a # (these are the ones that are actually likely to be useful
278n/a # when implementing a real-world config command!)
279n/a
280n/a def check_func(self, func, headers=None, include_dirs=None,
281n/a libraries=None, library_dirs=None, decl=0, call=0):
282n/a """Determine if function 'func' is available by constructing a
283n/a source file that refers to 'func', and compiles and links it.
284n/a If everything succeeds, returns true; otherwise returns false.
285n/a
286n/a The constructed source file starts out by including the header
287n/a files listed in 'headers'. If 'decl' is true, it then declares
288n/a 'func' (as "int func()"); you probably shouldn't supply 'headers'
289n/a and set 'decl' true in the same call, or you might get errors about
290n/a a conflicting declarations for 'func'. Finally, the constructed
291n/a 'main()' function either references 'func' or (if 'call' is true)
292n/a calls it. 'libraries' and 'library_dirs' are used when
293n/a linking.
294n/a """
295n/a self._check_compiler()
296n/a body = []
297n/a if decl:
298n/a body.append("int %s ();" % func)
299n/a body.append("int main () {")
300n/a if call:
301n/a body.append(" %s();" % func)
302n/a else:
303n/a body.append(" %s;" % func)
304n/a body.append("}")
305n/a body = "\n".join(body) + "\n"
306n/a
307n/a return self.try_link(body, headers, include_dirs,
308n/a libraries, library_dirs)
309n/a
310n/a def check_lib(self, library, library_dirs=None, headers=None,
311n/a include_dirs=None, other_libraries=[]):
312n/a """Determine if 'library' is available to be linked against,
313n/a without actually checking that any particular symbols are provided
314n/a by it. 'headers' will be used in constructing the source file to
315n/a be compiled, but the only effect of this is to check if all the
316n/a header files listed are available. Any libraries listed in
317n/a 'other_libraries' will be included in the link, in case 'library'
318n/a has symbols that depend on other libraries.
319n/a """
320n/a self._check_compiler()
321n/a return self.try_link("int main (void) { }", headers, include_dirs,
322n/a [library] + other_libraries, library_dirs)
323n/a
324n/a def check_header(self, header, include_dirs=None, library_dirs=None,
325n/a lang="c"):
326n/a """Determine if the system header file named by 'header_file'
327n/a exists and can be found by the preprocessor; return true if so,
328n/a false otherwise.
329n/a """
330n/a return self.try_cpp(body="/* No body */", headers=[header],
331n/a include_dirs=include_dirs)
332n/a
333n/a
334n/adef dump_file(filename, head=None):
335n/a """Dumps a file content into log.info.
336n/a
337n/a If head is not None, will be dumped before the file content.
338n/a """
339n/a if head is None:
340n/a log.info('%s', filename)
341n/a else:
342n/a log.info(head)
343n/a file = open(filename)
344n/a try:
345n/a log.info(file.read())
346n/a finally:
347n/a file.close()