config.py 13 KB

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