config.py 13 KB

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