config.py 13 KB

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