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

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

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